$(document).ready( function() {
    // Init voucher
    $("#voucherCode3").blur(validateVoucher);
    $('#voucherCode1').keyup(function() {
        if($(this).val().length == 4) {
            $('#voucherCode2').focus();
        }
    });
    $('#voucherCode2').keyup(function() {
        if($(this).val().length == 4) {
            $('#voucherCode3').focus();
        }
    });

    // Init tooltips
    var parentPos = $("#search").offset();
    var parentWidth = parseInt($("#search").css("width"));
    var self = parseInt($("#toolTipPopup").css("width"));
    var space = parseInt($(".searchButton").css("width"));
    $("#toolTipPopupIsbn, #toolTipPopup").css("left", (parentPos.left+parentWidth+space-self) + "px");
} );

function removeVoucher()
{
    $("#voucherCode1").val("");
    $("#voucherCode2").val("");
    $("#voucherCode3").val("");

    $("#voucherErrorBox").hide();
    $("#voucherValue").text("");
}

function validateVoucher()
{
    var code = $("#voucherCode1").val()
             + $("#voucherCode2").val()
             + $("#voucherCode3").val();

    $.ajax( {
        type: 'post',
        async: true,
        url: "/ajax/validate-voucher/vouchercode",
        data: {vouchercode:code},
        dataType: "json",
        success: function(data) {
            $("#voucherValue").text(data.value);

            if(!data.success) {
                $(".errorBox").hide();
                $("#voucherErrorText").html(data.errorText);
                $("#voucherErrorBox").show();
            } else {
                $("#voucherErrorBox").hide();
            }
        }
    });
}

function showToolTip()
{
    $.ajax( {
        type: "POST",
        async: true,
        url: "/default/ajax/tooltip/?rand=" + ( new Date().getTime() ),
        dataType: "json",
        data : {
        },
        success : function(data, textStatus) {
            var parentPos = $("#search").offset();
            var parentWidth = parseInt($("#search").css("width"));
            var self = parseInt($("#toolTipPopup").css("width"));
            var space = parseInt($(".searchButton").css("width"));
            
            $("#toolTipPopup").html(data.text)
                              .css("left", (parentPos.left+parentWidth+space-self) + "px")
                              .fadeIn(500);
        }
    } );
}

function getFilteredCategory()
{
    return 0;
}

function openPurchaseTerms()
{
    openFancyBox('/ajax/purchase-term');
    return false;
}

function openGeneralTerms()
{
    openFancyBox('/ajax/general-terms');
    return false;
}

function openProtectionOfPrivacyTerms(triggerElement)
{
    openFancyBox('/ajax/protection-of-privacy');
    return false;
}

function openFancyBox(href, title)
{
    if (!title) {
        title = '';
    }
    $.fancybox({
        'autoScale'		: false,
        'autoDimensions' :false,
        'title'			: title,
        'width'         : $('#mainContent').width() - 80,
        'height'		: 600,
        'href' : href
    });
}
