$(window).load(function(){
    bindActions();
    if(afterLoad) {loadAdmin();}
    if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
        $("#footer").css("position", "relative");
    };
    if($("#theImage").length) {
        var img = $("#theImage img");
        var width = img.width();
        var height= img.height();
        var left = img.position().left;
        var top = img.position().top;
        var il = document.createElement("a");
        il.style.left = left+"px";
        il.style.top = top+"px";
        il.style.width = width/4+"px";
        il.style.height = height+"px";
        il.setAttribute("class","over");
        il.id="overLeft";
        il.href = $("#moveLeft a")[0].href
        il.appendChild(document.createTextNode(" "));
        document.body.appendChild(il);
        var ir = document.createElement("a");
        ir.style.left = (left+(width/4*3)+1)+"px";
        ir.style.top = top+"px";
        ir.style.width = width/4+"px";
        ir.style.height = height+"px";
        ir.setAttribute("class","over");
        ir.id="overRight";
        ir.href = $("#moveRight a")[0].href
        ir.appendChild(document.createTextNode(" "));
        document.body.appendChild(ir);
    }
});
// user
function bindActions(){
    // over pro galerie
    $('.galleryImage,.galleryTitle').hover(function(e){
        $(e.target.parentNode).addClass("galleryActive");
    },function(e){
        $(e.target.parentNode).removeClass("galleryActive");
    });
    // click na galerie
    $('.gallery').click(function(e){
        location.href=$(e.target.parentNode).find("a")[0].href;
    });
    if($('#moveLeft') && $('#moveRight')){
        $('#moveLeft a').click(function(e){e.preventDefault();scrollAlbumRight(e)});
        $('#moveRight a').click(function(e){e.preventDefault();scrollAlbumLeft(e)});
        
        $("#photosInner").hover(albumScrollStart, albumScrollEnd);
        //$("#photosInner").bind("touchstart", function(e) {
        //});
    }
}
function albumScrollStart(e){
    $(window).bind("mousewheel",wheel);
    window.addEventListener('DOMMouseScroll', wheel, false);

}
function albumScrollEnd(e){
    $(window).unbind("mousewheel",wheel);
    window.removeEventListener('DOMMouseScroll', wheel, false);
}

function wheel(event){
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
                /** In Opera 9, delta differs in sign as compared to IE.
                 */
                if (window.opera)
                        delta = -delta;
        } else if (event.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                delta = -event.detail/3;
        }
        /** If delta is nonzero, handle it.
         * Basically, delta is now positive if wheel was scrolled up,
         * and negative, if wheel was scrolled down.
         */
        if (delta)
                scrollAlbum(delta);
        /** Prevent default actions caused by mouse wheel.
         * That might be ugly, but we handle scrolls somehow
         * anyway, so don't bother here..
         */
        if (event.preventDefault)
                event.preventDefault();
    event.returnValue = false;
}


function scrollAlbum(delta){
    //e.preventDefault();
    //var normal = e.detail ? e.detail * -1 : e.wheelDelta / 40;
    //console.log(normal);
    //e = e ? e : window.event;
    //var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40;
    //if(wheelDatoa<0){
    //    offset = -10;
    //}else{offset = 10;}
    offset = delta;
    
    var albumContainer = $("#photosInner")[0];
    var left = parseInt(albumContainer.style.left);
    if ((offset>0 && left <0)||(offset<0 && left>-25000)){
        albumContainer.style.left = left+offset+"px";
    }
}
function albumTouchMove(event, base) {
    touch =  event.originalEvent.touches[0];
    console.log(base);
}
    
function scrollAlbumLeft(e){
    var albumContainer = $("#photosInner")[0];
    var left = parseInt(albumContainer.style.left);
    console.log(left);
    albumContainer.style.left = left-200+"px";
}
function scrollAlbumRight(e){
    var albumContainer = $("#photosInner")[0];
    var left = parseInt(albumContainer.style.left);
    console.log(left);
    albumContainer.style.left = left+200+"px";
}


// admin
function loadAdmin() {
    console.log("ADMIN!");
    var what = document.location.pathname.split("/");
    var menu = $("div.menu>ul")[0];
    if(what[1] == "albums") {
        var album = what[2]
        var photo = what[3]
    }
    else if (what[1] == "galleries") {
        if (what.length == 3) {
            var gallery = what[2];
            var photo = false;
            var post = false;
        }
        else if (what.length == 4) {
            var gallery = what[3];
            var photo = false;
            var post = false;
        }
        else {
            var gallery = what[3];
            var photo = what[4];
            var post = false;
        }
    }
    else if (what[1] == "posts") {
            var gallery = false;
            var photo = false;
            var post = what[2];
    }
    if(gallery) {
        var mi = createMenuLink(menu, "Gallery", "#")
        mi.click(function (e){
            $('#submenu').remove();
            createSubMenu("submenu");
            if(what[3]){ //todo
                addSubMenuLink("Jako fotku galerie", function(e){e.preventDefault();setGalleryPhoto(what, photo)});
            } else  {
                addSubMenuLink("Nastavit fotku galerie", function(e){e.preventDefault();setGalleryPhoto(what, photo)});
            }
            if (what.length<3){ //todo
                addSubMenuLink("Přidat galerii", function(e){e.preventDefault();setGalleryPhoto(what, photo)});
            }
            addSubMenuLink("Přejmenovat galerii", function(e){e.preventDefault();renameGallery(what, photo)});

            return false;
        });
    }
    if(album) {
        var mi = createMenuLink(menu, "Album", "#")
        mi.click(function (e){
            $('#submenu').remove();
            createSubMenu("submenu");
            addSubMenuLink("Jako fotku alba", function(e){e.preventDefault();setAlbumPhoto(what, photo)});
            addSubMenuLink("Přejmenovat album", function(e){e.preventDefault();renameAlbum(what, photo)});
            return false;
        });
    }
    if(photo) {
        var mi = createMenuLink(menu, "Fotka", "")
        mi.click(function (e){
            $('#submenu').remove();
            createSubMenu("submenu");
            addSubMenuLink("Přejmenovat", function(e){e.preventDefault();renamePhoto(what, photo)});
            addSubMenuLink("Změnit popis", function(e){e.preventDefault();describePhoto(what, photo)});
            addSubMenuLink("Nastavit kategorie", function(e){e.preventDefault();setCategories(what, photo)});
            return false;
        });
    }
    if(post) {
        var mi = createMenuLink(menu, "Blog", "#")
        mi.click(function (e){
            $('#submenu').remove();
            createSubMenu("submenu");
            addSubMenuLink("Nový", function(e){e.preventDefault();editPost("new", what)});
            addSubMenuLink("Upravit", function(e){e.preventDefault();editPost("edit", what)});
            addSubMenuLink("Smazat", function(e){e.preventDefault();deletePost(what, post)});
            return false;
        });
    }
}
function createMenuLink(menu, title, link) {
    var li = document.createElement("li");
    var link = document.createElement("a");
    link.href=link;
    link.appendChild(document.createTextNode(title));
    li.appendChild(link);
    menu.appendChild(li);
    return $(link)
}
function createSubMenu(elId) {
    var menu = document.createElement("div");
    menu.id=elId;
    menu.style.position = "fixed";
    menu.style.right = "200px";
    menu.style.top = "30px";
    menu.style.width = "200px";
    menu = $(menu);
    menu.addClass("pageForm");
    menu.html = "podmenu";
    console.log(menu);
    $("#mainContent")[0].appendChild(menu[0]);
    return menu
}
function addSubMenuLink(title, action){
    menu = $("#submenu")[0];
    var link = document.createElement("a");
    link.href=link;
    link.appendChild(document.createTextNode(title));
    menu.appendChild(link);
    link = $(link);
    link.click(action);
    return false;
}


function renamePhoto(what, photo){
    var photoId = $('#photoId').text();
    var photoTitle = $('#photoTitle').text();
    console.log(photoId);
    var newName = prompt("Zadej nové jméno fotky:", photoTitle);
    what[3] = newName;
    $.ajax({
        url: "/adminAction/editPhoto",
        dataType: 'json',
        data: {photoId:photoId,title:newName},
        success: function (data){
            $('#photoTitle').html(newName);
            $('#submenu').remove();
        }
    });
}
function describePhoto(what, photo){
    var photoId = $('#photoId').text();
    var photoDescription = $('#photoDescription').text();
    console.log(photoId);
    var newDesc = prompt("Zadej nový popis fotky:", photoDescription);
    $.ajax({
        url: "/adminAction/editPhoto",
        dataType: 'json',
        data: {photoId:photoId,description:newDesc},
        success: function (data){
            $('#photoDescription').html(newDesc);
            $('#submenu').remove();
        }
    });
}
function setAlbumPhoto(what, photo){
    var photoId = $('#photoId').text();
    var albumId = $('#galleryId').text();
    $.getJSON("/adminAction/editAlbum", {titleImageId:photoId,albumId:albumId},function (data){
            $('#submenu').remove();
    });
}
function setGalleryPhoto(what, photo){
    var photoId = $('#photoId').text();
    var galleryId = $('#galleryId').text();
    $.getJSON("/adminAction/editGallery", {titleImageId:photoId,galleryId:galleryId},function (data){
            $('#submenu').remove();
    });
}
function setCategories(what, photo){
    var photoId = $('#photoId').text();
    $('#submenu').remove();
    var albumChooser = createSubMenu("albumChooser");
    var aSelect = document.createElement("select");
    aSelect.setAttribute("size","20");
    aSelect.setAttribute("multiple","multiple");
    albumChooser[0].appendChild(aSelect);
    albumChooser[0].style.width="180px";
    var photoGalleries = new Array();
    $.ajax({
        async: false,
        url: "/adminAction/getPhotoGalleries",
        dataType: 'json',
        data: {photoId:photoId},
        success: function (data){
            photoGalleries = data;
        }
    });
    $.getJSON("/adminAction/listAllGalleries", function (data) {
        console.log("aaa");
        console.log(photoGalleries);
        $.each(data, function (i, item){
            var asi = document.createElement("option");
            asi.setAttribute("value",item.id);
            if($.inArray(item.id, photoGalleries)<0){}else{
                console.log("je tam");
                asi.setAttribute("selected", "selected");
            }
            asi.appendChild(document.createTextNode(item.title));
            aSelect.appendChild(asi);
        });
    });
    var aButton = document.createElement("input");
    aButton.type="button";
    aButton.value=" Změnit ";
    albumChooser[0].appendChild(aButton);
    aButton=$(aButton);
    var toChange = new Array();
    aButton.click(function (e) {
        for(i=0;i<aSelect.childNodes.length;i++){
            console.log(aSelect.childNodes[i]);
            if(aSelect.childNodes[i].selected) {
                toChange.push(aSelect.childNodes[i].value);
            }
        }
        $.getJSON("/adminAction/setPhotoGalleries",  {photoId:photoId, galleryIds:toChange}, function (d){
            albumChooser.remove()        
        })    
    });
}

function editPost(edit, what){
    $('#submenu').remove();
    var box = createSubMenu("postBox")[0];
    box.style.width="400px";

    var d = document.createElement("div")
    d.appendChild(document.createTextNode("Název"));
    box.appendChild(d);
    var pite = document.createElement("input");
    pite.type="text";
    pite.id="pite";
    box.appendChild(pite);
    
    var d = document.createElement("div")
    d.appendChild(document.createTextNode("obsah"));
    box.appendChild(d);
    var ptce = document.createElement("textarea");
    ptce.setAttribute("rows",5);
    ptce.setAttribute("cols",50);
    ptce.id = "ptce";
    box.appendChild(ptce);

    var d = document.createElement("div")
    d.appendChild(document.createTextNode("fotka (album/fotka)"));
    box.appendChild(d);
    var pipe = document.createElement("input");
    pipe.type="text";
    pipe.id="pipe";
    box.appendChild(pipe);
    
    box.appendChild(document.createElement("br"));

    var pse = document.createElement("input");
    pse.type="button";
    pse.value=" Odeslat ";
    box.appendChild(pse);
    

    if(edit == "new"){
        console.log("newPost");
        $(pse).click(createPost);
    } else {
        console.log("editPost1");
        data = {
            link: what[2],
        }
        console.log("editPost2");
        /*
        $.getJSON("/adminAction/getPostByLink", data, function (d) {
            console.log("editPost3");
            ptce.innerText = d.content;
            pite.value = d.title;
            if(d.photo){pipe.value = d.photo.albumLink+"/"+d.photo.link}
            $(pse).click(modifyPost);
        });
        */
        $.ajax({
            url: "/adminAction/getPostByLink",
            dataType: "json",
            data: data,
            success: function (d) {
                console.log("editPost3");
                ptce.innerText = d.content;
                pite.value = d.title;
                if(d.photo){pipe.value = d.photo.albumLink+"/"+d.photo.link}
                $(pse).click(modifyPost);
            }
        });
    }

}
function createPost(e) {
    var data = {
        title: $("#pite")[0].value,
        content: $("#ptce")[0].value,
        titleImage: $("#pipe")[0].value
    }
    $.getJSON("/adminAction/insertPost", data, function (res) {$('#postBox').remove();});

}
function modifyPost(e) {
    var data = {
        title: $("#pite")[0].value,
        content: $("#ptce")[0].value,
        titleImage: $("#pipe")[0].value,
        postId: document.location.pathname.split("/")[2]
    }
    $.getJSON("/adminAction/updatePost", data, function (res) {$('#postBox').remove();});

}

function deletePost(what, post){ //todo
    if (confirm("Smazat prispevek?")) {
        var data = {
            postId: $('#postId').text()
        }
        $.getJSON("/adminAction/deletePost", data, function (res) {location.href="/posts/"});
    }
}

function renameGallery(what, post){
    var galleryId = $('#galleryId').text();

    var newName = prompt("Zadej nové jméno galerie:");
    what[3] = newName;
    $.ajax({
        url: "/adminAction/editGallery",
        dataType: 'json',
        data: {galleryId:galleryId,title:newName},
        success: function (data){
            $('#galleryTitle').html(newName);
            $('#submenu').remove();
        }
    });
        
}
function renameAlbum(what, post){
    var albumId = $('#galleryId').text();

    var newName = prompt("Zadej nové jméno alba:");
    what[3] = newName;
    $.ajax({
        url: "/adminAction/editAlbum",
        dataType: 'json',
        data: {albumId:albumId,title:newName},
        success: function (data){
            $('#galleryTitle').html(newName);
            $('#submenu').remove();
        }
    });
        
}


