﻿$(function() {
    initCorner();
    showLimitCom();
    init_button();
    setsharelink();
    setActiveCurrentImg();
    $('#main_img').load(onmainimgload);
    $("#abcxyz").click(function(){
	self.location = $("#lk_next").attr("href");
    })
    .css({
	cursor: "pointer"
    });
});

function setActiveCurrentImg() {
    var imgIDCurrent = $("#main_img").attr("src");
    imgIDCurrent = imgIDCurrent.substring(0, imgIDCurrent.lastIndexOf("/"));
    imgIDCurrent = imgIDCurrent.substring(imgIDCurrent.lastIndexOf("/") + 1, imgIDCurrent.length);
    $("#div_ps p").each(function() {
        if ($("img", $(this)).attr("src").indexOf(imgIDCurrent) != -1) {
            $(this).siblings().removeClass("photoactive").addClass("photo");
            $(this).removeClass("photo").addClass("photoactive");
        }
    })
}
function onmainimgload() {
    $('#abcxyz').css('height', $('#main_img').height() + 'px');
}
function initCorner() {
    $(".box .header").corner("top 6px").parent().corner("6px");
    $(".box .footer").corner("bottom 6px").parent().corner("6px");
    $(".box").corner("6px")
}
function hideovercmm() {

    if ($('.binhluan div.item').length == 0) {
        $("#viewallcmm").hide();
    }
    else if ($('.binhluan div.item').length > 5) {
        $('#viewallcmm').click(view_all_cmm);
        var cmmlength = $('.binhluan div.item').length;
        var i = cmmlength - 5;
        while (i < cmmlength) {
            $($('.binhluan div.item')[i]).show();
            i++;
        }
    }
    else { view_all_cmm(); }
}

function view_all_cmm() {

    $('.binhluan div.item').fadeIn('slow');
    return false

}
function toogleCom() {
    var totalCom = $(".binhluan .item").size();
    var showCom = $(".binhluan .item:visible").size();
    if (showCom < totalCom) {
        $(".binhluan .item").show();
    }
    else {
        //$(".binhluan .item:lt(" + (totalCom) + "):gt(" + (totalCom - 6) + ")").show();
        $(".binhluan .item:lt(" + (totalCom - 5) + ")").hide();
    }

}
function init_button() {


    $('#btn_thongso').click(function() {
        $("#dv_thongtin").slideToggle("slow");
        $(this).toggleClass("selected");
        $('#btn_thongtin').toggleClass("selected");
        return false
    });

    $('#btn_thongtin').click(function() {
        $("#dv_thongtin").slideToggle("slow");
        $(this).toggleClass("selected");
        $('#btn_thongso').toggleClass("selected");
        return false
    });

    new nicEditor({ iconsPath: '/images/nicEditorIcons.gif', buttonList: ['smiley', 'bold', 'italic', 'underline', 'strikeThrough', 'link', 'xhtml'], iconList: { "xhtml": 1, "bold": 2, "center": 3, "hr": 4, "indent": 5, "italic": 6, "justify": 7, "smiley": 8, "ol": 9, "outdent": 10, "right": 11, "save": 12, "strikethrough": 13, "subscript": 14, "superscript": 15, "ul": 16, "underline": 17, "image": 18, "link": 19, "unlink": 20, "close": 21} }).panelInstance('area4');
    //kiểm tra chủ ảnh
    if ($('#GuestID').val() == '0') {
        $('.guiBL').hide();
    }
    else {
        $('#bl_notify').hide();
    }

    if ($('#OwnerID').val() == $('#GuestID').val()) {


        $("#img_title").hover(function() {
            $(this).removeClass("title").addClass("titleHover");
        }, function() {
            $(this).removeClass("titleHover").addClass("title");
        });

        //Khi chu buc anh muon sua title
        $("#img_title").click(function() {
            $(this).css("display", "none")
            $(".editTitle").css("display", "block");
            $(".fieldEditText").val($(this).text()).select().focus();

        });


        $("#img_desc").hover(function() {
            $(this).removeClass("des").addClass("desHover");
        }, function() {
            $(this).removeClass("desHover").addClass("des");
        });

        //Khi chu buc anh muon sua title
        $("#img_desc").click(function() {
            $(this).css("display", "none")
            $(".editDes").css("display", "block");
            $(".fieldEditDesText").val($(this).text()).select().focus();

        });


    }
    else {
        $('.delcmm').hide();
    }

    $('#btn_delete').click(DeleteImage);

}

function showLimitCom() {
    var totalCom = $(".binhluan .item").size();
    if (totalCom == 0) {
        $("#viewallcmm").hide();
    }
    else if (totalCom <= 5) {
        $("#viewallcmm").show();
        $("#sp_totalcmm").text(totalCom);
        $(".binhluan .item").show();
    }
    else {
        $("#viewallcmm").show();
        $("#sp_totalcmm").text("Xem tất cả " + totalCom);
        $(".binhluan .item:lt(" + (totalCom) + "):gt(" + (totalCom - 6) + ")").show();
        $(".binhluan .item:lt(" + (totalCom - 5) + ")").hide();
    }
}
function submitcmm() {
    var editor1 = nicEditors.findEditor('area4');
    var Comment = editor1.getContent();

    var imageID = $('#CurrImgID').val();
    editor1.setContent("");

    if ($.trim(Comment) != "") {
        // document.getElementById('cmmloading').style.display = "block";  //alert(Comment);


        $.ajax({
            type: "POST",
            data: " { content: '" + $.trim(Comment) + "', imgID:'" + imageID + "', refID:'-1' }",
            contentType: "application/json; charset=utf-8",
            url: "/farmservice/SamService.asmx/newcomment",
            dataType: "json",
            success: function(data) {
                data = eval('(' + data.d + ')');
                if (data != '-1') {
                    // alert(data);
                    // document.location = "http://" + $('#OwnerName').val() + ".anhso.net";

                    $('<div style="" id="cmm_' + data + '" class="item"><a name="cmm_' + data + '"/><p class="ava">  <a href="http://' + $('#GuestName').val() + '.anhso.net/"><img src="' + $('#GuestAva').val() + '"/> </a></p><div class="content"><p class="author"><a href="http://' + $('#GuestName').val() + '.anhso.net/">' + $('#GuestName').val() + '</a> viết: </p><p id="cmm_content" class="comment">' + Comment + '<br/></p><p class="datetime">  Vừa gửi(<a onclick="delcmm(\'' + data + '\');return false" href="#"> Xóa</a>|<a href="#cmm_' + data + '">Link trực tiếp</a>)</p></div> </div>').insertBefore('.binhluan .cat:last').hide().show('slow');
                    //alert($(".binhluan .item").size());
                    showLimitCom();
                }
                else {
                    alert('Bạn không được phép thực hiện thao tác này!');
                }
            }
        });

    }
    else alert('Bạn chưa nhập bình luận');

}


function delcmm(cmID) {
    if (confirm("Bạn chắc chắn muốn xóa bình luận này chứ?")) {

        $.ajax({
            type: "POST",
            data: " { cmmID: '" + cmID + "' }",
            contentType: "application/json; charset=utf-8",
            url: "/farmservice/SamService.asmx/delcomment",
            dataType: "json",
            success: function(data) {
                data = data.d;
                if (data != '-1') {
                    $('#cmm_' + cmID).fadeOut(function() { $(this).remove(); showLimitCom(); });
                    //                    var totalCom = $(".binhluan .item").size() - 1;
                    //                    $("#sp_totalcmm").text(totalCom);
                    //                    if ((totalCom - 1) == 5)
                    //                        $(".binhluan .item:lt("+totalCom+"):gt("+(totalCom-5)+")").show();

                }
                else {
                    alert('Bạn không được phép thực hiện thao tác này!');
                }
            }
        });
    }
}

function doChangeTitle(ImageID) {

    var text = $(".editTitle .fieldEditText").val();
    var ownerID = $("#OwnerID").val();

    //update database
    $.post("/farmservice/photostream.asmx/updateImageProperties", { userID: ownerID, imageID: ImageID, nameProperties: "Title", value: text }, function(data) {
        $(".editTitle").hide("slow");

        if (data) {


            $("#img_title").show().html(text);
            $("#img_title").removeClass("titleHover").addClass("title");
        }
        else
            $("#img_title").show().html("Có lỗi xảy ra");
    });

}

function doChangeDes(ImageID) {

    var text = $(".fieldEditDesText").val();
    var ownerID = $("#OwnerID").val();

    //update database
    $.post("/farmservice/photostream.asmx/updateImageProperties", { userID: ownerID, imageID: ImageID, nameProperties: "Description", value: text }, function(data) {
        $(".editDes").hide("slow");
        if (data) {
            //            var re = new RegExp("\n\n\n", 'gi');
            //            text = text.replace(re, '');
            //            re = new RegExp("\n", 'gi');
            //            text = text.replace(re, '<br />');

            $("#img_desc").show().html(text);
        }
        else
            $("#img_desc").show().html("Có lỗi xảy ra");
    });
}

function hideEditPanel(nameDivShow) {

    if (nameDivShow == "title") {
        $(".editTitle").hide();

        $("#img_title").show();
        $("#img_title").removeClass("titleHover").addClass("title");
    }
    else {
        $(".editDes").hide();
        $("#img_desc").show();
        $("#img_desc").removeClass("desHover").addClass("des");
    }


};


// Share box
function setsharelink() {
    if (!document.getElementById('main_img')) return;
    var imgURL = document.getElementById('main_img').src.replace('.jpg', '');

    var maxsize = imgURL.substr(imgURL.length - 1, 1);
    $('#btn_save').attr('href', imgURL.replace('/pic/', '/download/') + '.jpg');
    $('#btn_zoom').attr('href', imgURL.replace('/l/', '/o/') + '.jpg');


    switch (maxsize * 1) {
        case 1:
            document.getElementById('lb_75').style.display = 'inline';
            document.getElementById('lb_140').style.display = 'none';
            document.getElementById('lb_240').style.display = 'none';
            document.getElementById('lb_540').style.display = 'none';
            document.getElementById('lb_1024').style.display = 'none';

            break;
        case 2:
            document.getElementById('lb_75').style.display = 'inline';
            document.getElementById('lb_140').style.display = 'inline';
            document.getElementById('lb_240').style.display = 'none';
            document.getElementById('lb_540').style.display = 'none';
            document.getElementById('lb_1024').style.display = 'none';

            break;
        case 3:

            document.getElementById('lb_75').style.display = 'inline';
            document.getElementById('lb_140').style.display = 'inline';
            document.getElementById('lb_240').style.display = 'inline';
            document.getElementById('lb_540').style.display = 'none';
            document.getElementById('lb_1024').style.display = 'none';

            break;
        case 4:
            document.getElementById('lb_75').style.display = 'inline';
            document.getElementById('lb_140').style.display = 'inline';
            document.getElementById('lb_240').style.display = 'inline';
            document.getElementById('lb_540').style.display = 'inline';
            document.getElementById('lb_1024').style.display = 'none';

            break;
        case 5:
            document.getElementById('lb_75').style.display = 'inline';
            document.getElementById('lb_140').style.display = 'inline';
            document.getElementById('lb_240').style.display = 'inline';
            document.getElementById('lb_540').style.display = 'inline';
            document.getElementById('lb_1024').style.display = 'inline';

            break;
        default:
            alert(maxsize);



    }
    changelinkshare('lb_ori', 'o');






}

var active_linkshare = "lb_ori";
function changelinkshare(elem, size) {
    var imglink = window.location;
    $('#' + active_linkshare).removeClass();
    //  $('#' + active_linkshare + ' span').removeClass();
    $('#' + elem).addClass('selected');
    //$('#' + elem + ' span').addClass('a-spaned');

    var imgtitle = $('#img_title').html();

    active_linkshare = elem;
    var imgURL = document.getElementById('main_img').src;
    var txtsize;
    var maxsize = imgURL.substr(imgURL.length - 1, 1);
    //imgURL = imgURL.replace(ori_hash.split('|')[1], ori_hash.split('|')[0]);
    switch (size) {
        case "t": txtsize = "cỡ 75px"
            break;
        case "s": txtsize = "cỡ 140px"
            break;
        case "m": txtsize = "cỡ 230px"
            break;
        case "l": txtsize = "cỡ 540px"
            break;
        case "b": txtsize = "cỡ 1024px"
            break;
        case "o": txtsize = "ảnh gốc"

            //    imgURL = imgURL.replace(ori_hash.split('|')[0], ori_hash.split('|')[1]);
            break;
    }

    var actions = imgURL.substr(imgURL.indexOf('pic/'), 5);

    $('.btnXemanhgoc').html('Xem ' + txtsize);
    imgURL = imgURL.replace(actions, 'pic/' + size);
    //alert(imgURL);
    $('.btnXemanhgoc').attr('href', imgURL);

    $('.btnXemanhgoc').attr('title', 'Xem ' + txtsize);
    document.getElementById('txtdirect').value = imgURL;
    document.getElementById('txthtml').value = '<a href="' + imglink + '" target="blank">' + '<img alt="' + imgtitle + ' | anhso.net" src="' + imgURL + '"/></a>';
    document.getElementById('txtbbcode').value = '[URL=' + imglink + ']' + '[IMG]' + imgURL + '[/IMG][/URL]';

}

function DeleteImage() {

    $("body").animate({ opacity: 0.3 }, 500, function() {
        if (confirm("Bạn chắc chắn muốn xóa ảnh này ? \n (Ảnh sẽ không thể khôi phục một khi đã xóa)")) {
            //  $("body").animate({ opacity: 1.0 }, 500);
            /*
            $.ajax({
            type: "POST",
            data: "{userID:-1,imageID:" + $('#CurrImgID').val() + "}",
            contentType: "application/json; charset=utf-8",
            url: "/farmservice/photostream.asmx/deleteImage",
            dataType: "json",
            success: function(data) {
            data = eval('(' + data.d + ')');
            if (data) {
            alert('Ảnh đã được xóa ');
            document.location = "http://" + $('#OwnerName').val() + ".anhso.net";

                    }
            else {
            alert('Bạn không có quyền xóa ảnh này');
            $("body").animate({ opacity: 1.0 }, 500);
            }
            }
            });
            */


            $.getJSON(
                "/AS_DeleteImage.aspx",
                {
                    ImageId: $('#CurrImgID').val()
                },
                function(data, textStatus) {
                    if (data.success) {
                        alert('Ảnh đã được xóa');
                        document.location = "http://" + $('#OwnerName').val() + ".anhso.net";
                    }
                    else {
                        alert('Bạn không có quyền xóa ảnh này');
                        $("body").animate({ opacity: 1.0 }, 500);
                    };
                }
            );



        }
        else {
            $("body").animate({ opacity: 1.0 }, 500);
        }

    });
    return false;
}
var ps_page = 0;
function nav_photostream(direction) {
    ps_page = (parseInt($("#ps_pageidx").val()) + parseInt(direction));

    if (ps_page == 0) { ps_page = 1; return false; }
    if (ps_page > parseInt($('#ps_total').val())) { ps_page = parseInt($('#ps_total').val()); return false };
    $.ajax({
        type: "POST",
        data: "{ownerID:" + $("#OwnerID").val() + ",ImageID:-1,pageIdx:" + ps_page + ",numGet:4}",
        contentType: "application/json; charset=utf-8",
        url: "/farmservice/SamService.asmx/jsLoadphotostream",
        dataType: "json",
        success: function(data) {
            data = eval('(' + data.d + ')');
            if (data) {

                $('#ps_pageidx').val(ps_page);
                $("#div_ps").html('');
                $.each(data[0].Obj, function(i, n) {


                    $("#div_ps").append('<p class="photo"> <a href="/UserRedirect.aspx?action=image&imgID=' + n.ImageID + '"><img src="' + n.ConvertImgUrl + '" class="imgnone"/></a></p>');

                });


            }
            else {
                alert('Load stream false');

            }
        }
    });
    $("#div_ps").ajaxComplete(function() {
        setActiveCurrentImg();
    })
    return false;
}
