﻿$(document).ready(function() {
    fLoad();

    $("#SortOrder").bind("change", function() {
        pageIndex = $('#PageIndex').val();
        fLoad();
    })
    $(".linkCode span").css("width", "78px");
    $("img").lazyload({
        placeholder: "http://anhso.net/images/small_square.gif",
        effect: "fadeIn"
    });
})

function buildPager(totalPage, pageindex) {
    $("#pageTop").pager({ 'totalPage': totalPage, 'pageindex': pageindex });
    $("#pageBottom").pager({ 'totalPage': totalPage, 'pageindex': pageindex });
}

function fLoad() {
    var style = getHash('style');
    var pageindex = getHash('page');

    if (style == "") {
        sethash('style', '2');
        $('#PageStyle').val('2');
        setClassGrid(2);
    }
    else {
        $('#PageStyle').val(style);
        setClassGrid(style);
    }
    if (pageindex == "") {
        sethash('page', '1');
        getData(1);
    }
    else {
        sethash('page', pageindex);
        getData(pageindex);
    }
}
function setClassGrid(style) {
    if (style == 1) {
        $(".grid a:eq(0)").addClass("btnfixImg140_Active").removeClass("btnfixImg140");
        $(".grid a:eq(1)").addClass("btnfixImg230").removeClass("btnfixImg230_Active");
        $(".grid a:eq(2)").addClass("btnfixImg540").removeClass("btnfixImg540_Active");
    }
    else if (style == 2) {
        $(".grid a:eq(0)").addClass("btnfixImg140").removeClass("btnfixImg140_Active");
        $(".grid a:eq(1)").addClass("btnfixImg230_Active").removeClass("btnfixImg230");
        $(".grid a:eq(2)").addClass("btnfixImg540").removeClass("btnfixImg540_Active");
    }
    else {
        $(".grid a:eq(0)").addClass("btnfixImg140").removeClass("btnfixImg140_Active");
        $(".grid a:eq(1)").addClass("btnfixImg230").removeClass("btnfixImg230_Active");
        $(".grid a:eq(2)").addClass("btnfixImg540_Active").removeClass("btnfixImg540");
    }
}
function getData(pageIndex) {
    var style = $('#PageStyle').val();
    sethash('style', style);
    sethash('page', pageIndex);

    var sortorder = $('#SortOrder').val();
    getMyPhotoStream(pageIndex, style, sortorder);

    style = $("#PageStyle").val();
    filterSen(style, true);
}

function getPageSize(style) {
    if (style == 1)
        return 42;
    else if (style == 2)
        return 20;
    else
        return 8
}

function buildData(data, pagesize, style) {
    var owner = data[0].owner;
    if (style == 1)    //140
        template140 = (owner == "1") ? $("#template140_owner").html() : $("#template140_viewer").html();
    else if (style == 2)//230
        template230 = (owner == "1") ? $("#template230_owner").html() : $("#template230_viewer").html();
    else            //540
        template540 = (owner == "1") ? $("#template540_owner").html() : $("#template540_viewer").html();

    var html = '';

    for (var i = 0; i < pagesize; i++) {
        if (data[0].photos[i] != null) {
            var title = (data[0].photos[i].Title != "") ? data[0].photos[i].Title : "Nhập tiêu đề cho ảnh";
            var des = (data[0].photos[i].Description != "") ? data[0].photos[i].Description : "Nhập lời tựa cho ảnh";
            if (style == 1)     //140
                template = template140;
            else if (style == 2)//230
                template = template230;
            else                //540
                template = template540;

            template = template.replace(/{ImageID}|%7BImageID%7D/g, data[0].photos[i].ImageID);
            template = template.replace(/{ImageTitle}/g, title);
            template = template.replace(/{ImageDescription}/g, des);
            template = template.replace(/{ImageAvatar}|%7BImageAvatar%7D/g, data[0].photos[i].ConvertImgUrl);
            template = template.replace(/{RealAvatar}|%7BRealAvatar%7D/g, data[0].photos[i].ConvertImgUrl);
            template = template.replace(/{SenStatus}|%7BSenStatus%7D/g, data[0].photos[i].StatusID);
            template = template.replace(/{ImageCreateTime}/g, data[0].photos[i].CreatedTimeFormat);
            template = template.replace(/{ImageView}/g, data[0].photos[i].TotalView);
            template = template.replace(/{ImageComment}/g, data[0].photos[i].TotalComment);
            template = template.replace(/{ImagePricavy}/g, data[0].photos[i].ImagePrivacy);

            html += template;
        }
    }

    return html;
}

function doFilter(firstime) {
    style = $("#PageStyle").val();
    var filter = $("#hidFilter").val();

    if (filter == 0)
        $("#hidFilter").val(1);
    else
        $("#hidFilter").val(0);

    filterSen(style, firstime);
}

function filterSen(style, firsttime) {
    if (firsttime) {
        $("#listPhoto").ajaxSuccess(function() {
            processFilter(style);
        })
    }
    else
        processFilter(style);
}
function processFilter(style) {
    var filter = $("#hidFilter").val();
    var isOwner = $("input[id*=hidIsOwner]").val();
    if (filter != "0") {
        $("#listPhoto .photo").each(function() {
            status = $("#hidSenStatus", this).val();
            if (status == 2 && isOwner != 1) {
                $("#avatar", this).hide();
                $("#senAvatar", this).show();
                $("#senAvatar img", this).attr("src", "http://anhso.net/images/sen" + style + ".jpg");
            }
        })
    }
    else {
        $("#listPhoto .photo").each(function() {
            $("#avatar", this).show();
            //alert($("#avatar img", this).attr("src"));
            $("#senAvatar", this).hide();
        })
    }
}

function doShowSenImg(ImageID) {
    photo = $("#photo_" + ImageID);
    $("#avatar", photo).show();
    $("#senAvatar", photo).hide();
    //    $("#flipBox",photo).flip({
    //        direction: 'rl',
    //        color: '#f5f5f5',
    //        speed: 400,
    //        content: $('#avatar',photo)
    //    });
}

function getMyPhotoStream(pageIndex, pageType, sortOrder) {
    pageSize = getPageSize(pageType);
    urf = $('#txturf').val();

    $("#listPhoto").html('<div style="width:100%;height:200px;vertical-align:top;text-align:center;"><img src="http://anhso.net/Images/ajax_loader_32x32.gif" width="32" height="32" style="margin-top:90px;" /></div>');
    $.ajax({
        type: "POST",
        data: "{ownerID:" + urf + ",pageIndex:" + pageIndex + ",style:" + pageType + ",sortStyle:'" + sortOrder + "'}",
        contentType: "application/json; charset=utf-8",
        url: "/farmservice/photostream.asmx/photoStream",
        dataType: "json",
        success: function(data) {
            data = eval('(' + data.d + ')');
            owner = data[0].owner;

            if (pageType == 1)
                $("#listPhoto").removeClass('listPhoto230').removeClass('listPhoto540').addClass("listPhoto140");
            else if (pageType == 2)
                $("#listPhoto").removeClass('listPhoto140').removeClass('listPhoto540').addClass("listPhoto230");
            else
                $("#listPhoto").removeClass('listPhoto140').removeClass('listPhoto230').addClass("listPhoto540");

            total = data[0].total;
            if (total > 0) {
                $("#hidOwnerID").val(data[0].photos[0].OwnerID);

                totalPage = Math.ceil(parseFloat(total) / pageSize);
                buildPager(totalPage, pageIndex);
                $("input[id=TotalPage]").val(totalPage);

                $("#listPhoto").html("").html(buildData(data, pageSize, pageType));

                if (pageType == 1) {
                    initPhoto140();
                    configPhotoPanel(pageIndex, 4, 5);
                }
                else if (pageType == 2) {
                    initPhoto230_540(owner);
                    configPhotoPanel(pageIndex, 3, 4);
                }
                else {
                    initPhoto230_540(owner);
                    $("#albumPanel").show();
                    $("#photoPanel,#listPhoto").css({ "width": "680px", "padding-left": "40px" });
                }
            }
            else
                $("#listPhoto").css({ "margin": "0px 0px 0px 50px" }).html("<div style='margin:100px 0px 0px 150px;color:#777;font-weight:bold;font-size:18px'>Photo stream của bạn chưa có bức ảnh nào</div>");
        }
    });
}

function setsharelink(imageID) {
    photo = $("#photo_" + imageID);
    imgUrl = $("#hidRealAvatar", $(photo)).val();
    maxsize = parseInt(imgUrl.substr(imgUrl.length - 5, 1)) - 1;

    $(".size span:lt(" + (maxsize) + ")", $(photo)).show();
    $(".size span:gt(" + (maxsize) + ")", $(photo)).hide();

    $(".size a", $(photo)).removeClass("selected");
    $(".size a:eq(" + maxsize + ")", $(photo)).addClass("selected");

    switch (maxsize * 1 + 1) {
        case 1:
            setLinkShare(photo, imageID, imgUrl, 't');
            break;
        case 2:
            setLinkShare(photo, imageID, imgUrl, 's');
            break;
        case 3:
            setLinkShare(photo, imageID, imgUrl, 'm');
            break;
        case 4:
            setLinkShare(photo, imageID, imgUrl, 'l');
            break;
        case 5:
            setLinkShare(photo, imageID, imgUrl, 'b');
            break;
        default:
            alert('nothing to do');
    }

}

function changeLinkShare(obj, imageID, size) {
    photo = $(obj).parents('div#photo_' + imageID);
    imgUrl = $("#hidRealAvatar", $(photo)).val();
    setLinkShare(photo, imageID, imgUrl, size);
    $(".size a", $(photo)).removeClass("selected");
    $(obj).addClass("selected");
}
function setLinkShare(objDivPhoto, imageID, imgUrl, size) {
    var re = new RegExp("anhso.net/pic/[a-z]/", "g");
    imgUrl = imgUrl.replace(re, "anhso.net/pic/" + size + "/");

    $("#txtShareUrl", $(objDivPhoto)).val(imgUrl);
    $("#txtHTMLCode", $(objDivPhoto)).val('<a href="http://anhso.net/UserRedirect.aspx?action=image&imgID=' + imageID + '"  target="blank"><img src="' + imgUrl + '"anhso.net"/> </a>');
    $("#txtBBCode", $(objDivPhoto)).val('[URL=http://anhso.net/UserRedirect.aspx?action=image&imgID=' + imageID + '][IMG]' + imgUrl + '[/IMG][/URL]');

}
function doOpenOImage(obj) {
    imgUrl = $(obj).next().val();
    //    var re = new RegExp("anhso.net/pic/[a-z]/", "g");
    //    imgUrl = imgUrl.replace(re, "anhso.net/pic/o/");
    window.open(imgUrl);
}


function fixFloat(perRow) {
    $("div[class=clear]", "#listPhoto").remove();
    $(".photo", "#listPhoto").each(function() {
        index = $(".photo", "#listPhoto").index($(this));
        if ((index) % perRow == 0) {
            $(this).before("<div class='clear'></div>");
        }
    })
}

function changeStyle(style) {
    var pageindex = getHash('page');
    $('#PageStyle').val(style);
    getData(pageindex);
}

function configPhotoPanel(pageIndex, beforeCol, afterCol) {
    if (pageIndex > 1) {
        $("#albumPanel").hide();
        $("#photoPanel,#listPhoto").css({ "width": "954px", "padding": "0px" });
        fixFloat(afterCol);
    }
    else {
        $("#albumPanel").show();
        $("#photoPanel,#listPhoto").css({ "width": "720px", "padding": "0px" });
        fixFloat(beforeCol);
    }
}

function showPopUp() {
    $(".showPopUp", "#listPhoto").hide();
    $(".preView", "#listPhoto").show();
    var preView = $(this).parent();
    var popUp = $(preView).next();
    $(popUp).css({ "top": $(preView).offset().top - 25 + "px", "left": $(preView).offset().left - 18 + "px" });
    $(preView).hide();
}
function hidePopUp() {
    var preView = $(this).parent();
    var popUp = $(preView).next();
    $(popUp).show().animate({ opacity: 1.0 }, 3000, function() { $(popUp).hide(); $(preView).show(); $(".chiase").show(); })
}

function initPhoto140() {
    $(".showPopUp", "#listPhoto").hide();

    $("#listPhoto .photo").each(function() {
        var thisObj = $(this);
        //Show Popup
        $(".preView .img", thisObj).hoverIntent({ over: showPopUp, out: hidePopUp });

        //Open chia se
        $(".chiase", this).bind("click", function() {
            $(".showPopUp", "#listPhoto").css("display", "none");
            $(this).css("display", "none");
            $(".panelChiaSe").css("display", "none");
            $(".panelChiaSe", thisObj).css("display", "block");
        })

        var imgId = $("#hidImageID", thisObj).val();
        setsharelink(imgId);

    })
}

function initPhoto230_540(owner) {
    $("#listPhoto .photo").each(function() {
        var thisObj = $(this);
        if (owner == 1) {
            $("#title", this).bind("mouseover", function() {
                $(this).removeClass("title").addClass("titleHover");
            })
            $("#title", this).bind("mouseout", function() {
                $(this).removeClass("titleHover").addClass("title");
            })

            //Khi chu buc anh muon sua title
            $("#title", this).bind("click", function() {
                $(this).css("display", "none")
                $(".editTitle", thisObj).css("display", "block");
                $(".fieldEditText", thisObj).val($(this).text()).select().focus();

            })

            $("#des", this).bind("mouseover", function() {
                $(this).removeClass("des").addClass("desHover");
            })
            $("#des", this).bind("mouseout", function() {
                $(this).removeClass("desHover").addClass("des");
            })

            //Khi chu buc anh  muon sua des
            $("#des", this).bind("click", function() {
                $(this).css("display", "none");
                $(".editDes", thisObj).slideDown("slow");
                $(".fieldEditDesText", thisObj).val($(this).text()).blur().focus();
            })

            $(".pricavy", this).each(function() {
                var val = $("#sl_pricavy", thisObj).attr("rel");
                $("#sl_pricavy", thisObj).val(val);
                var text = $("#sl_pricavy :selected", thisObj).text();
                if (val == 0)
                    $(".pricavy", thisObj).show().html("<img src='images/icon_img_private.jpg' /><p class='pricavyText'> " + text + "</p><a href='javascript:void(0)' style='margin-left:5px;'>Sửa</a>");
                else
                    $(".pricavy", thisObj).show().html("<img src='images/icon_img_public.jpg' /><p class='pricavyText'> " + text + "</p><a href='javascript:void(0)' style='margin-left:5px;'>Sửa</a>");

            })
            //Khi chu buc anh muon sua pricavy
            $(".pricavy", this).bind("click", function() {
                $(this).css("display", "none");
                $(".editPricavy", thisObj).slideDown("slow");

            })
        }
        //Open chia se
        $(".chiase", this).bind("click", function() {
            $(this).css("display", "none")
            $(".panelChiaSe").css("display", "none");
            $(".panelChiaSe", thisObj).css("display", "block");

        })
        var imgId = $("#hidImageID", thisObj).val();
        setsharelink(imgId);
    })
}

function hideEditPanel(imageID, nameDivHide, nameDivShow) {

    $("." + nameDivHide, "#photo_" + imageID).css("display", "none");
    if (nameDivShow != null)
        $("." + nameDivShow, "#photo_" + imageID).css("display", "block");
};

function doDeleteImg(ImageID, perRow) {
    if (confirm("Bạn chắc chắn muốn xóa ảnh này ? \n (Ảnh này sẽ không thể khôi phục một khi đã xóa)")) {
        $.getJSON(
            "/AS_DeleteImage.aspx",
            {
                ImageId: ImageID
            },
            function(data, textStatus) {
                if (data.success) {
                    $("#photo_" + data.imageId).remove();
                    fixFloat(perRow);
                }
                else {
                    $("#photo_" + data.imageId).fadeTo(1000, 0.2).fadeTo(1000, 1);
                };
            }
        );
    }
}

function doChangeTitle(ImageID) {
    var thisObj = $("#photo_" + ImageID);
    var text = $(".fieldEditText", thisObj).val();
    var ownerID = $("#hidOwnerID").val();

    //update database    
    $.post("/farmservice/photostream.asmx/updateImageProperties", { userID: ownerID, imageID: ImageID, nameProperties: "Title", value: text }, function(data) {
        $(".editTitle", thisObj).slideUp("slow");
        if (data)
            $("#title", thisObj).show().text(text);
        else
            $("#title", thisObj).show().text("Có lỗi xảy ra");
    });

}

function doChangeDes(ImageID) {
    var thisObj = $("#photo_" + ImageID);
    var text = $(".fieldEditDesText", thisObj).val();
    var ownerID = $("#hidOwnerID").val();

    //update database
    $.post("/farmservice/photostream.asmx/updateImageProperties", { userID: ownerID, imageID: ImageID, nameProperties: "Description", value: text }, function(data) {
        $(".editDes", thisObj).slideUp("slow");
        if (data)
            $("#des", thisObj).show().text(text);
        else
            $("#des", thisObj).show().text("Có lỗi xảy ra");
    });
}
function doChangePricavy(ImageID) {
    var thisObj = $("#photo_" + ImageID);
    var val = $("#sl_pricavy", thisObj).val();
    var text = $("#sl_pricavy :selected", thisObj).text();

    var ownerID = $("#hidOwnerID").val();
    //update database

    $.post("/farmservice/photostream.asmx/updateImageProperties", { userID: ownerID, imageID: ImageID, nameProperties: "ImagePrivacy", value: val }, function(data) {
        $(".editPricavy", thisObj).slideUp("slow");
        if (data) {
            if (val == 0)
                $(".pricavy", thisObj).show().html("<img src='images/icon_img_private.jpg' /><p class='pricavyText'> " + text + "</p>");
            else
                $(".pricavy", thisObj).show().html("<img src='images/icon_img_public.jpg' /><p class='pricavyText'> " + text + "</p>");
            $("#sl_pricavy", thisObj).attr("rel", val);
            $("#sl_pricavy :selected", thisObj).val(val);
        }
        else
            $(".pricavy", thisObj).show().text("Có lỗi xảy ra");
    });

}
