﻿//var AppPath = "http://localhost/contento/";
var AppPath = "http://www.contento.com.pt/";
$(document).ready(function() {

    try {
        changeValor(decValorInicial, decValorLinha);
        $(".txtLinha").change(function() {
            changeValor(decValorInicial, decValorLinha);
            $(".divLinha[linha=" + $(this).attr("linha") + "]").html($(this).val());
            if ($(this).attr("linha") == 1) {
                orderTXT1 = $(this).val();
            } else if ($(this).attr("linha") == 2) {
                orderTXT2 = $(this).val();
            } else if ($(this).attr("linha") == 3) {
                orderTXT3 = $(this).val();
            }
        });
    } catch (ex) { }


    var strDefaultImgHome = $('.imgHome').attr('src');

    $('.linkMenuCentral').mouseenter(function() {
        if ($(this).attr("imgHome") != "") {
            $('.imgHome').attr('src', $(this).attr("imgHome"));
        } else {
            $('.imgHome').attr('src', strDefaultImgHome);
        }
    }).mouseleave(function() {
        $('.imgHome').attr('src', strDefaultImgHome);
    });

    orderTXTAlign = "center";

    $('#imgBtnAlignLeft').click(function() { $(".divLinha").css("text-align", "left"); orderTXTAlign = "left"; });
    $('#imgBtnAlignCenter').click(function() { $(".divLinha").css("text-align", "center"); orderTXTAlign = "center"; });
    $('#imgBtnAlignRight').click(function() { $(".divLinha").css("text-align", "right"); orderTXTAlign = "right"; });

    try {
        $(".divUploading").dialog({ modal: true, autoOpen: false, closeOnEscape: false, minHeight: 50, resizable: false, show: 'drop', hide: 'drop' });

        var fuFoto = $(".fuFoto").attr('id');
        var uploadFoto = new Ajax_upload(fuFoto, {
            action: AppPath + 'ajax/upload.ashx',
            onSubmit: function(file, ext) {
                //if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
                if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)) {

                    $('#divFotoToUpload').html('Uploading ' + file);

                    $(".divUploading").dialog('open');

                } else {

                    // extension is not allowed
                    alert('Só são permitidas imagens.');
                    // cancel upload
                    return false;
                }

            },
            onComplete: function(file, response) {
                try {
                    $('#divFotoToUpload').html('');
                    $('#imgToResize').attr('src', AppPath + 'ajax/upload/' + String(response).replace("<pre>", "").replace("</pre>", "").replace("<PRE>", "").replace("</PRE>", ""));
                    urlImg = AppPath + 'ajax/upload/' + String(response).replace("<pre>", "").replace("</pre>", "").replace("<PRE>", "").replace("</PRE>", "");
                    //alert(urlImg);
                    imgRealWidth = 0;
                    changeRectToHorToV();
                    resetImage();
                } catch (ex) { }
                $(".divUploading").dialog('close');
            }
        });
    } catch (ex) { }

    try {
        $('img#imgToResize').imgAreaSelect({ handles: true, aspectRatio: intRectWidth + ":" + intRectHeight, onSelectEnd: function(img, selection) {
            //alert('width: ' + selection.x1 + '; height: ' + selection.y1);
            actualSelection = selection;
        }
        });
    } catch (ex) { }

    $('#btnReset').click(function() { resetImage() });
    $('#btnOK').click(function() { resizeImage(actualSelection) });
    $('#btnRemover').click(function() {
        $('#imgToResize').attr('src', '');
        $('#imgToResize').css('display', 'none');
        $.ajax({
            url: AppPath + "ajax/removerImagem.ashx",
            success: function(data, textStatus) {
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    });

    $("input[type='radio']").click(function() {
        for (i = 0; i < $("input:checked").length; i++) {
            if ($($("input:checked")[i]).val() == "h") {
                changeRectToH();
                //alert($($("input:checked")[i]).val() + i + $("input:checked").length);
            } else if ($($("input:checked")[i]).val() == "v") {
                changeRectToV();
            } else if ($($("input:checked")[i]).val() == "a") {
                $(".divLinha").css("font-family", "Arial");
                orderTXTLetra = "Arial";
            } else if ($($("input:checked")[i]).val() == "c") {
                $(".divLinha").css("font-family", "Comic Sans MS");
                orderTXTLetra = "Comic";
            }
        }
    });

    //    //alert($(".detalheOpcoesFormato").length);
    //    $(".detalheOpcoesFormato").change(function() {
    //        for (i = 0; i < $("input:checked").length; i++) {
    //            //alert($($("input:checked")[i]).val());
    //            if ($($("input:checked")[i]).val() == "h") {
    //                changeRectToH();
    //            } else if ($($("input:checked")[i]).val() == "v") {
    //                changeRectToV();
    //            } else if ($($("input:checked")[i]).val() == "a") {
    //                $(".divLinha").css("font-family", "Arial")
    //            } else if ($($("input:checked")[i]).val() == "c") {
    //                $(".divLinha").css("font-family", "Comic Sans MS")
    //            }
    //        }
    //    });

    //    $(".detalheOpcoesTiposLetra").change(function() {
    //        for (i = 0; i < $("input:checked").length; i++) {
    //            if ($($("input:checked")[i]).val() == "h") {
    //                changeRectToH();
    //            } else if ($($("input:checked")[i]).val() == "v") {
    //                changeRectToV();
    //            } else if ($($("input:checked")[i]).val() == "a") {
    //                $(".divLinha").css("font-family", "Arial");
    //                orderTXTLetra = "Arial";
    //            } else if ($($("input:checked")[i]).val() == "c") {
    //                $(".divLinha").css("font-family", "Comic Sans MS");
    //                orderTXTLetra = "Comic";
    //            }
    //        }
    //    });

    try {
        if (urlImg == "") {
            $('#imgToResize').css('display', 'none');
        } else {
            $('#imgToResize').css('display', 'block');
        }
        for (i = 0; i < $("input:checked").length; i++) {
            if ($($("input:checked")[i]).val() == "h") {
                changeRectToH();
            } else if ($($("input:checked")[i]).val() == "v") {
                changeRectToV();
            } else if ($($("input:checked")[i]).val() == "a") {
                orderTXTLetra = "Arial";
            } else if ($($("input:checked")[i]).val() == "c") {
                orderTXTLetra = "Comic";
            }
        }

    } catch (ex) { }

    $(".divImagemDetalhe a").lightBox({
        overlayOpacity: 0.8,
        imageLoading: AppPath + 'images/lightbox-ico-loading.gif',
        imageBtnClose: AppPath + 'images/lightbox-btn-close.gif',
        imageBtnPrev: AppPath + 'images/lightbox-btn-prev.gif',
        imageBtnNext: AppPath + 'images/lightbox-btn-next.gif'
    });

    $(".divImgLupa a").lightBox({
        overlayOpacity: 0.8,
        imageLoading: AppPath + 'images/lightbox-ico-loading.gif',
        imageBtnClose: AppPath + 'images/lightbox-btn-close.gif',
        imageBtnPrev: AppPath + 'images/lightbox-btn-prev.gif',
        imageBtnNext: AppPath + 'images/lightbox-btn-next.gif'
    });

    try {
        if (strFoto != null) {
            $('#imgToResize').attr('src', AppPath + 'ajax/upload/' + strFoto);
            urlImg = AppPath + 'ajax/upload/' + strFoto;
            resetImage();
        }

    } catch (ex) { }

    try {
        var strBT = $(".divOK").attr('bt');
        $(".divOK").dialog({ modal: true, autoOpen: false, closeOnEscape: false, minHeight: 50, resizable: false, show: 'drop', hide: 'drop', buttons: { "Ok": function() { $(this).dialog("close"); }, strBT: function() { redirect(AppPath + "cart.aspx"); } } });

        $("button:contains('strBT')").html(strBT);

        $(".divERROR").dialog({ modal: true, autoOpen: false, closeOnEscape: false, minHeight: 50, resizable: false, show: 'drop', hide: 'drop', buttons: { "Ok": function() { $(this).dialog("close"); } } });
    } catch (ex) { }

    $('.imgBtnFinalizar').click(function() {
        //        var optionSelected = ""
        //        if ($("option[selected='selected']:eq(1)").lenght > 0) {
        //            optionSelected = $("option[selected='selected']:eq(1)").attr('value');
        //        } else {
        //            optionSelected = $("option[selected='true']:eq(1)").attr('value');
        //        }


        $.ajax({
            url: AppPath + "ajax/addCart.ashx?idProduct=" + $(this).attr('idProduct') + "&for=" + intIdFormato + "&foto=" + urlImg + "&orderImgX=" + orderImgX + "&orderImgY=" + orderImgY + "&orderImgW=" + orderImgW + "&orderImgH=" + orderImgH + "&orderTXT1=" + orderTXT1 + "&orderTXT2=" + orderTXT2 + "&orderTXT3=" + orderTXT3 + "&orderTXTLetra=" + orderTXTLetra + "&orderTXTAlign=" + orderTXTAlign + "&id=" + get0100Random(),
            success: function(data, textStatus) {
                if (data != "nok") {
                    var arrArtigosTotal = data.split(":");
                    $('#divArtigosNumber').html(arrArtigosTotal[0].toString());
                    $('#divTotalNumber').html(Number(String(arrArtigosTotal[1]).replace(",", ".")).toFixed(2).toString().replace(".", ",") + "€");
                    $(".divOK").dialog('open');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $(".divERROR").dialog('open');
            }
        });
    });

});

function get0100Random() {
    return Math.floor(Math.random() * 101);
}

function changeRectToHorToV() {
    for (i = 0; i < $("input:checked").length; i++) {
        if ($($("input:checked")[i]).val() == "h") {
            changeRectToH();
        } else if ($($("input:checked")[i]).val() == "v") {
            changeRectToV();
        }
    }
}

function changeRectToH() {
    try {
        $('#divDetalheFormatoImagem > img').attr('src', imgH);
    } catch (ex) { }
    try {
        $('.divDetalheFotoResize').css('width', intRectWidthH + "px");
        $('.divDetalheFotoResize').css('height', intRectHeightH + "px");
        $('.divDetalheFotoResize').css('margin-left', intMarginLeftH + "px");
        $('.divDetalheFotoResize').css('margin-top', intMarginTopH + "px");
        $(".divLinha").css("width", intRectWidthH + "px")
        intRectWidth = intRectWidthH;
        intRectHeight = intRectHeightH;
        resetImage();
        if (urlImg == "") {
            $('#imgToResize').css('display', 'none');
        } else {
            $('#imgToResize').css('display', 'block');
        }
    } catch (ex) { }
}

function changeRectToV() {
    try {
        $('#divDetalheFormatoImagem > img').attr('src', imgV);
    } catch (ex) { }
    try {
        $('.divDetalheFotoResize').css('width', intRectWidthV + "px");
        $('.divDetalheFotoResize').css('height', intRectHeightV + "px");
        $('.divDetalheFotoResize').css('margin-left', intMarginLeftV + "px");
        $('.divDetalheFotoResize').css('margin-top', intMarginTopV + "px");
        $(".divLinha").css("width", intRectWidthV + "px")
        intRectWidth = intRectWidthV;
        intRectHeight = intRectHeightV;
        resetImage();
        if (urlImg == "") {
            $('#imgToResize').css('display', 'none');
        } else {
            $('#imgToResize').css('display', 'block');
        }
    } catch (ex) { }
}

function setRealImageSize(tempImage) {
    if (tempImage.complete) {
        imgRealWidth = tempImage.width;
        imgRealHeight = tempImage.height;
        //alert(imgRealWidth + "," + imgRealHeight);
    }

}

var actualSelection;

var urlImg = "";

var imgRealWidth = 0;
var imgRealHeight = 0;
var imgResetWidth = 0;
var imgResetHeight = 0;
var imgActualWidth = 0;
var imgActualHeight = 0;
var imgWidth = 0;
var imgHeight = 0;
var imgActualX = 0;
var imgActualY = 0;
var imgX = 0;
var imgY = 0;

var orderImgX = 0;
var orderImgY = 0;
var orderImgW = 0;
var orderImgH = 0;
var orderTXT1 = "";
var orderTXT2 = "";
var orderTXT3 = "";
var orderTXTLetra = "";
var orderTXTAlign = "";

function resetImage() {
    if (imgRealWidth == 0) {
        tempImage = new Image();
        tempImage.src = urlImg;

        try {
            tempImage.onload = setRealImageSize(tempImage);
        } catch (ex) { }
        //imgRealWidth = tempImage.width; //REVER ISTO
        //imgRealWidth = 1024;
        //imgRealHeight = tempImage.height;
        //imgRealHeight = 768;
        if (imgRealWidth == 0) {
            setTimeout("resetImage();", 1000);
        }
    }

    if (((imgRealHeight * intRectWidth) / imgRealWidth) < intRectHeight) {
        imgResetWidth = intRectWidth;
        imgResetHeight = (imgRealHeight * intRectWidth) / imgRealWidth;
    } else {
        imgResetHeight = intRectHeight;
        imgResetWidth = (imgRealWidth * intRectHeight) / imgRealHeight;
    }
    //imgResetWidth = intRectWidth;
    //imgActualWidth = intRectWidth;
    //alterar para redimensionar do lado correcto




    $('#imgToResize').css('width', Math.round(imgResetWidth) + "px");
    $('#imgToResize').css('height', Math.round(imgResetHeight) + "px");
    var intLeft = 0;
    var intTop = 0;
    if (Math.round(imgResetWidth) == intRectWidth) {
        intTop = (intRectHeight - Math.round(imgResetHeight)) / 2;
    } else {
        intLeft = (intRectWidth - Math.round(imgResetWidth)) / 2;
    }
    $('#imgToResize').css('left', Math.round(intLeft) + "px");
    $('#imgToResize').css('top', Math.round(intTop) + "px");

    $('img#imgToResize').imgAreaSelect({ enable: "true", hide: "false", aspectRatio: intRectWidth + ":" + intRectHeight });

    if (urlImg == "") {
        $('#imgToResize').css('display', 'none');
    } else {
        $('#imgToResize').css('display', 'block');
    }
}

function resizeImage(selection) {
    try {
        if (imgRealWidth == 0) {
            tempImage = new Image();
            tempImage.src = urlImg;
            tempImage.onload = setRealImageSize(tempImage);
        }

        var imgWidthAux = (imgRealWidth * selection.width) / imgResetWidth;
        imgWidth = (imgRealWidth * intRectWidth) / imgWidthAux;
        var imgHeightAux = (imgRealHeight * selection.height) / imgResetHeight;
        imgHeight = (imgRealHeight * intRectHeight) / imgHeightAux;

        var imgXAux = (imgRealWidth * selection.x1) / imgResetWidth;
        imgX = (imgXAux * intRectWidth) / imgWidthAux;
        var imgYAux = (imgRealHeight * selection.y1) / imgResetHeight;
        imgY = (imgYAux * intRectHeight) / imgHeightAux;

        $('#imgToResize').css('width', Math.round(imgWidth) + "px");
        $('#imgToResize').css('height', Math.round(imgHeight) + "px");
        $('#imgToResize').css('left', "-" + Math.round(imgX) + "px");
        $('#imgToResize').css('top', "-" + Math.round(imgY) + "px");

        $('img#imgToResize').imgAreaSelect({ disable: "true", hide: "true" });

        orderImgX = Math.round(imgXAux);
        orderImgY = Math.round(imgYAux);
        orderImgW = Math.round(imgWidthAux);
        orderImgH = Math.round(imgHeightAux);
    } catch (ex) { }

    if (urlImg == "") {
        $('#imgToResize').css('display', 'none');
    } else {
        $('#imgToResize').css('display', 'block');
    }
}

function changeValor(decValorInicial, decValorLinha) {
    var decValor = decValorInicial;
    if ($(".txtLinha").length > 0) {
        for (i = 0; i < $(".txtLinha").length; i++) {
            if ($($(".txtLinha")[i]).val() != "") {
                decValor = decValor + decValorLinha;
            }
        }
    }
    $(".spanDetalheModeloPreco").html(decValor.toFixed(2).toString().replace(".", ",") + "€");
}

function changeQty(control, action) {
    var txtControl = document.getElementById(control);
    var decTxtValue = parseInt(txtControl.value);

    if (action == 0) {
        if (decTxtValue > 0) {
            if ((decTxtValue - 1) > 0) {
                txtControl.value = decTxtValue - 1;
            }
            else {
                txtControl.value = 1;
            }
        }
    }
    else {
        txtControl.value = decTxtValue + 1;
    }
}

function res(control) {
    control.value = control.value.replace(/([^0-9])/g, "");
}

function redirect(url) {
    window.location = url
}

function cvv() {
    var wWidth = 400;
    var wHeight = 350;
    var wTop = (screen.availHeight - wHeight) / 2
    var wLeft = (screen.availWidth - wWidth) / 2
    var vbvWindow = window.open(AppPath + '/cvv.htm', 'cvv', 'width=' + wWidth + ',height=' + wHeight + ',top=' + wTop + ',left=' + wLeft);
}

function vbv() {
    var wWidth = 330;
    var wHeight = 300;
    var wTop = (screen.availHeight - wHeight) / 2
    var wLeft = (screen.availWidth - wWidth) / 2
    var vbvWindow = window.open(AppPath + 'vbv.aspx', 'vbv', 'width=' + wWidth + ',height=' + wHeight + ',top=' + wTop + ',left=' + wLeft);
}