﻿var ProfileImageManager =
{
    _uploadProfileImageApi: null,
    _cropProfileImageApi: null,
    _rescaleUrl: null,

    Init: function(rescaleUrl)
    {
        this._rescaleUrl = rescaleUrl;
        this._uploadProfileImageApi = $("#profile-image[rel]").overlay(
        {
            api: true
        });
        $("#upload-profileimage-form").ajaxForm(
		{
		    dataType: "json",
		    beforeSubmit: function(a, f, o)
		    {
		        //$("#upload-image-status").show();

		    },
		    success: function(data)
		    {
		        if (!data.success)
		        {
		            $("#error-panel").html(data.message).show();
		        }
		        else
		        {
		            $("#error-panel").hide();
		            $("#crop-image-panel").show();
		            $("#upload-image").attr("src", data.imageUrl).load(function()
		            {
		                ProfileImageManager._cropProfileImageApi = $.Jcrop($("#upload-image"),
		            {
		                aspectRatio: 100 / 126,
		                minSize: [100, 126]
		            });
		            });
		        }
		    }
		});
    },

    SaveSelection: function()
    {
        var selection = ProfileImageManager._cropProfileImageApi.tellSelect();
        var data = { x: selection.x, y: selection.y, w: selection.w, h: selection.h };
        $.post(ProfileImageManager._rescaleUrl, data, function(result)
        {
            $("#profile-image").attr("src", result.imageUrl);
            $("#crop-image-panel").hide();
            ProfileImageManager._cropProfileImageApi.destroy();
            ProfileImageManager._uploadProfileImageApi.close();

        }, "json");
    },

    Show: function()
    {
        ProfileImageManager._uploadProfileImageApi.load();
    }
};
