﻿var imgLoading = new Image();
$(imgLoading).load().attr("src", "/popupLoading.gif");

function popupImage(imageId, api_key, director) {
    var l = Math.floor(($(window).width() - imgLoading.width) / 2);
    var t = Math.floor(($(window).height() - imgLoading.height) / 2);

    $("#popupOverlay").show();
    $("#popupLoading").css({ left: l + "px", top: t + "px" });
    $('#popupLoading').show();

    var w = (Math.floor($(window).width() / 50) * 50) - 50;
    var h = (Math.floor($(window).height() / 50) * 50) - 50;

    params = "data[content_id]=" + imageId + "&data[size][0]=popup," + w + "," + h + ",0,100,1&data[preview]=0,0,0,0,0&data[api_key]=" + api_key;

    $.ajax({
        type: "POST",
        url: director + "/index.php?/api/get_content",
        data: params,
        contentType: "application/x-www-form-urlencoded",
        dataType: "xml",
        success: popupLoad,
        error: popupError
    });

    return true;
}

function popupError(xhr, ajaxOptions, thrownError) {
    var error = "Status: " + xhr.statusText + "\r\n" + "Response: " + xhr.responseText;
    alert(error);
    popupHide();
}

function popupLoad(xml) {
    var img = new Image();
    var url = $(xml).find('popup').find('url').text();

    if (url != "") {
        $(img).load(function() {
            var pw = $("#popupWindow");
            pw.bind("click", popupFade);
            pw.append(img);
            pw.height(img.height);

            var l = Math.floor(($(window).width() - pw.width()) / 2);
            var t = Math.floor(($(window).height() - pw.height()) / 2);

            pw.css({ left: l + "px", top: t + "px" });
            $("#popupLoading").hide();
            pw.fadeIn("slow");
            $(window).bind("resize", popupHide);
        }).attr("src", url);
    } else {
        var error = $(xml).find('error').text();
        alert(error);
        popupHide();        
    }
}

function popupFade(e) {
    $("#popupWindow").fadeOut("slow", popupHide);
}

function popupHide() {
    $(window).unbind("resize");
    $("#popupLoading").hide();
    $("#popupWindow").unbind("click").hide();
    $("#popupWindow").empty();
    $("#popupOverlay").hide();
    $("#ssp")[0].closeImage();
    return false;
}
		    
