﻿/// <reference path="jquery-1.3.vsdoc.js" />
var COOKIE_NAME_PREFIX = 'TamteCzasyPhoto';
var dpDate;

$(function() {
    //    $("[id$=taCommentContentBox]").rte({
    //        css: 'jquery.rte.css',
    //        width: '99%',
    //        controls_rte: rte_toolbar
    //    });
    $("[id$=hlDelPhoto]").floatdialog("divDeletePhoto");
    var id = $('[id$=m_hidID]').val(); //get photo id
    if ($("[id$=m_hidRating]").length > 0) {
        $("#rbRate" + $("[id$=m_hidRating]").val().charAt(0)).attr("checked", "checked");
        $('.rate').rating({
            callback: function(value, link) {
                var id = $('[id$=m_hidID]').val(); //get photo id
                if ($.cookie(COOKIE_NAME_PREFIX + id) == null) {
                    vote(value);
                }
                else {
                    var rate = $("[id$=m_hidRating]").val();
                    for(var i=1;i<6;i++) {
                        $("#rbRate"+ i).removeClass("star-rating-on");
                        if(i<=rate)
                            $("#rbRate"+ i).addClass("star-rating-on");
                    }
                    status.showError("Już oceniałeś(aś) to zdjęcie");
                }

                return false;
            }
        });
        $('.rating-cancel').remove();

        dpDate = new datePanel($("#date-div"));
        dpDate.setValues($("[id$=m_hidDateFrom]").val(), $("[id$=m_hidDateTo]").val(), $("[id$=m_hidDateType]").val(), '.');


        $("[id$=taCommentContentBox]").growfield({
            min: 108
        });
        $("[id$=tbAbuseContent]").growfield({
            min: 72
        });
        $("[id$=DescriptionArea]").growfield({
            min: 126
        });
        $("[id$=taExtraInfo]").growfield({
            min: 126
        });
    }
});

function vote(rate) {
    var photoID = $('[id$=m_hidID]').val(); //get photo id
    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Photo/Actions.aspx",
        dataType: "json",
        data: {
            photoid: photoID,
            vote: rate
        },
        success: onRateSuccess,
        error: onErrorResponse
    });

    function onRateSuccess(response, statusText) {
        if (response.ok) {
            $("[id$=labRating]").html(response.value + "/5");
            var id = $('[id$=m_hidID]').val();
            $.cookie(COOKIE_NAME_PREFIX + id, "true");
            status.showInfo(response.status);
        }
        else {
            status.showError(response.status);
            $('input[id*=rbRate]').rating('select',3,'falsesdsd');
            return false; 
            //$('input[id*=rbRate]').rating('readOnly',true) 
            //$("div[class*=star-rating-on]").removeClass("star-rating-on");
        }
    };
    return false;
};

var tempDescription = $("[id$=DescriptionArea]").html();

function showEditDescription() {
    $("[id$=hlDescription]").parent().hide();
    $("#descriptionEdit-div").show();
    $("p[id$=pDescription]").hide();
    return false;
};

function cancelEditDescription() {
    $("[id$=hlDescription]").parent().show()
    $("#descriptionEdit-div").hide();
    $("p[id$=pDescription]").show();
    $("[id$=DescriptionArea]").val(tempDescription);
    return false;
};

function showPriceSelect() {
    $("#divSetPrice").show();
    return false;
};

var forSale = {
    onlyChangePrice: false,
    showSetPrice: function(a_bOnlyChangePrice) {
        if (a_bOnlyChangePrice == true) {
            this.onlyChangePrice = true;
        }
        else {
            this.onlyChangePrice = false;
        }
        $("#divSetPrice").show('slow');
        return false;
    },
    hideSetPrice: function() {
        $("#divSetPrice").hide('slow');
        return false;
    },
    noMore: function() {
        $.ajax({
            type: "POST",
            url: $('[id$=m_hidPath]').val() + "/Photo/SavePhoto.aspx",
            dataType: "json",
            success: onNoMoreSuccess,
            error: forSale.onError,
            data: {
                ForSale: "false",
                PhotoType: $("[id$=m_hidType]").val(),
                PhotoId: $('[id$=m_hidID]').val()
            }
        });

        function onNoMoreSuccess(response, statusText) {
            if (response.ok) {
                $('[id$=m_aMakeForSale]').show();
                $('[id$=m_pIsForSale]').hide();
                $('[id$=m_aForSaleNoMore]').hide();
                status.showInfo(response.status);
            }
            else {
                status.showError(response.status);
            }
        };

        return false;
    },
    sendSetPrice: function() {
        $.ajax({
            type: "POST",
            url: $('[id$=m_hidPath]').val() + "/Photo/SavePhoto.aspx",
            dataType: "json",
            success: onSetPriceSuccess,
            error: onErrorResponse,
            data: {
                ForSale: "true",
                PhotoId: $('[id$=m_hidID]').val(),
                Price: $("#inPrice").val(),
                PhotoType: $("[id$=m_hidType]").val(),
                OnlyChangePrice: this.onlyChangePrice
            }
        });

        function onSetPriceSuccess(response, statusText) {
            if (response.ok) {
                status.showInfo(response.status);
                forSale.hideSetPrice();
                $('[id$=m_aMakeForSale]').hide();
                $('[id$=m_pIsForSale]').show();
                $('[id$=m_aForSaleNoMore]').show();

                var sType = $("[id$=m_hidType]").val();

                if (sType != "Object") {
                    $('[id$=m_spanIsForSale]').html("Sprzedajesz to zdjęcie za " + response.price + " zł. ");
                }
                else {
                    $('[id$=m_spanIsForSale]').html("Sprzedajesz ten przedmiot za " + response.price + " zł. ");
                }
                $('[id$=btSetPrice]').val('Zmień');
            }
            else {
                status.showError(response.status);
            }
        };

        return false;
    }
};

function editDatePhoto() {
    var sDateType = dpDate.getTypeOfDates();
    var sDateFrom = dpDate.getFromValue();
    var sDateTo = dpDate.getToValue();

    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Photo/SavePhoto.aspx",
        dataType: "json",
        success: onDateSuccess,
        error: onErrorResponse,
        data: {
            photoid: $('[id$=m_hidID]').val(),
            edit: "date",
            created_from: sDateFrom,
            created_to: sDateTo,
            datetype: sDateType
        }
    });

    function onDateSuccess(response, statusText) {
        if (response.ok) {
            var sDateType = dpDate.getTypeOfDates();
            var sDateFrom = dpDate.getFromValue();
            var sDateTo = dpDate.getToValue();
            $("#date-div").hide();
            var sDisplayDate;
            switch (sDateType[0]) {
                case 'd':
                    sDisplayDate = sDateFrom;
                    break;
                case 'm':
                    sDisplayDate = sDateFrom.substring(3, 10);
                    break;
                case 'y':
                    sDisplayDate = sDateFrom.substring(6, 10);
                    break;
            }
            if (sDateFrom != sDateTo) {
                switch (sDateType[1]) {
                    case 'd':
                        sDisplayDate += "-" + sDateTo;
                        break;
                    case 'm':
                        sDisplayDate += "-" + sDateTo.substring(3, 10);
                        break;
                    case 'y':
                        sDisplayDate += "-" + sDateTo.substring(6, 10);
                        break;
                }
            }
            status.showInfo(response.status);
            $("[id$=spanCreated]").html(sDisplayDate + "(<a class=\"edit\" href=\"#\" onclick=\"$('#date-div').toggle(); return false\">Edytuj</a>)");
        }
        else {
        }
        return false;
    }
    
    return false;
};

function editDescriptionPhoto() {
    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Photo/SavePhoto.aspx",
        dataType: "json",
        success: onDescriptionSuccess,
        error: onErrorResponse,
        data: {
            photoid: $('[id$=m_hidID]').val(),
            edit: "description",
            value: $("[id$=DescriptionArea]").val()
        }
    });

    function onDescriptionSuccess(response, statusText) {
        if (response.ok) {
            var description = response.value;
            $("p[id$=pDescription]").html(description.replace(/\n/g, "<br/>"));
            $("p[id$=pDescription]").show();
            $("#descriptionEdit-div").hide();
            $("[id$=hlDescription]").parent().show();
            $("[id$=DescriptionArea]").html(description);
            tempDescription = $("[id$=DescriptionArea]").val();
            status.showInfo(response.status);
        }
        else {
            status.showError(response.status);
        }
    }
    
    return false;
};



function onError(xhr, textStatus, errorThrown) {
    status.showError("Błąd połączenia z bazą");
}

function showExtraInfo() {
    var userName = $("[id$=m_labLogged]").text();
    if ($("#extraInfo-div").is(":visible")) {
        $("#extraInfo-div").hide();
    }
    else if ((userName == null) || (userName == "")) {
        status.showError("Musisz się zalogować");
        window.location.href = "#";
    }
    else {
        $("[id$=taExtraInfo]").val("");
        $("#extraInfo-div").show();
    }
    return false;
};

function sendExtraInfo_Click(a_sReceiver) {
    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Messages/Actions.aspx",
        dataType: "json",
        success: onExtraInfoSuccess,
        error: onErrorResponse,
        data: {
            send: "extrainfo",
            touserlogin: a_sReceiver,
            title: "Informacje dotyczące zdjęcia: " + $('.position a').text(),
            content: $("[id$=taExtraInfo]").val(),
            photoid: $('[id$=m_hidID]').val(),
            phototype: $('[id$=m_hidType]').val(),
            photoname: $('.position a').text()
        }
    });
    
    function onExtraInfoSuccess(response, statusText) {
        if (response.ok){
            status.showInfo(response.status);
        }
        else{
            status.showError(response.status);
        }
        showExtraInfo();
    };
    
    return false;
};

function addOrDelFavorite_Click(a_lUserID, a_lPhotoID) {
    var sOperationType = "";
    if ($("[id$=aFavorite]").html().indexOf("Dodaj") > -1) {
        sOperationType = "add";
    }
    else {
        sOperationType = "del";
    }
    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Photo/SavePhoto.aspx",
        dataType: "json",
        success: onAddOrDelFavSuccess,
        error: onErrorResponse,
        data: {
            fav: sOperationType,
            photoid: a_lPhotoID
        }
    });

    function onAddOrDelFavSuccess(response, statusText) {
        if (response.ok) {
            status.showInfo(response.status);
            var favor = $("[id$=favor]");
            if ($("[id$=aFavorite]").html().indexOf("Dodaj") > -1) {
                $("[id$=aFavorite]").html("Usuń z ulubionych");
                favor.addClass("fav-remove");
            }
            else {
                $("[id$=aFavorite]").html("Dodaj do ulubionych");
                favor.removeClass("fav-remove");
                favor.addClass("fav");
            }
        }
        else {
            status.showError(response.status);
        }
    };
    
    return false;
};


function showAddToGroup_Click(a_lPhotoId, a_bIsPhotoAuthor) {
    showAjaxLoader(null, $('[id$=divAddToGroup]'), 'loader-parent-absolute');
    $("[id$=divAddToGroup]").show();
    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Group/Actions.aspx",
        dataType: "json",
        success: onShowAddPhotosSuccess,
        error: onErrorResponse,
        data: {
            photo: 'open',
            photoid: a_lPhotoId,
            isphotoauthor: a_bIsPhotoAuthor
        }
    });

    function onShowAddPhotosSuccess(response, statusText) {
        var selectGroup = $("[id$=selectGroup]");
        if (response.ok) {
            $("[id$=labGroup]").text("Grupy: ");
            selectGroup.show();
            $("[id$=btAddToGroup]").show();
            var groupSplit = response.groups.split(";");
            $.each(groupSplit, function(i, item) {
                var s = item.split(":");
                selectGroup.append(
                $("<option></option>").val(s[0]).html(s[1]));
            })
        }
        else {
            if (response.nogroup != null && response.nogroup) {
                selectGroup.hide();
                $("[id$=labGroup]").text(response.status);
                $("[id$=btAddToGroup]").hide();
                
            }
            else {
                status.showError(response.status);
            }
        }
        hideAjaxLoader(null, $('[id$=divAddToGroup]'), 'loader-parent-absolute');
    };

    return false;
};

function addToGroup_Click(a_lPhotoId) {
    showAjaxLoader(null, $('[id$=divAddToGroup]'), 'loader-parent-absolute');
    $.ajax({
        type: "POST",
        url: $('[id$=m_hidPath]').val() + "/Group/Actions.aspx",
        dataType: "json",
        success: addPhotosSuccess,
        error: onErrorResponse,
        data: {
            photo: 'add',
            photoid: a_lPhotoId,
            groupid: $("[id$=selectGroup]").val()
        }
    });

    function addPhotosSuccess(response, statusText) {
        if (response.ok) {
            $("option", $("[id$=divAddToGroup]")).remove();
            $("[id$=divAddToGroup]").hide();
            hideAjaxLoader(null, $('[id$=divAddToGroup]'), 'loader-parent-absolute');
            __doPostBack('ctl00_Main_m_upGroupsPhoto', 'newgroup');
        }
        else {
            status.showError(response.status);
        }
    };
    return false;
};
