var dontInit;


// Init autocomplete
function initAutocomplete()
{
    var searchBoxWidth = $("#search").width();
    searchBoxWidth += parseInt($("#search").css("padding-left"), 10) + parseInt($("#search").css("padding-right"), 10);
    searchBoxWidth += parseInt($("#search").css("margin-left"), 10) + parseInt($("#search").css("margin-right"), 10);

    $("#search").autocomplete( "/ajax/suggest/", {
            minChars: 3,
            mustMatch: false,
            matchContains: false,
            cacheLength: 0,
            autoFill: false,
            selectFirst: false,
            width:  searchBoxWidth,
            delay: 300,
            formatItem: function(row) {
                return '<span>'+ row[1] +'</span>';
            },
            onItemSelect: function(item) {
                // id = item.selectValue
                prepareAddItem(item);
                elem = $("#search")[0].value = "";
                $("#search").focus();
            },
            extraParams: {
            }
        } )
}

function addTooltips()
{
    var fontColor = '#333';

    $('#purchaseGroupForm span.ui-dialog-show-upper[title!=""]').qtip({
            style: {
                color: fontColor,
                name: 'cream',
                tip: 'topLeft',
                width: 350,
                title: {
                    'color': fontColor
                }
            },
            position : {
                corner: {
                     target: 'bottomMiddle',
                     tooltip: 'topLeft'
                },
                adjust: {
                    y: 8
                }
            },
            content: {
                title : {
                    text : 'Beschreibung'
                }
            }
        })
        .css('cursor', 'help');

    $('#purchaseGroupForm span.ui-dialog-show-lower[title!=""]').qtip({
            style: {
                color: fontColor,
                name: 'cream',
                tip: 'bottomLeft',
                width: 350,
                title: {
                    'color': fontColor
                }
            },
            position : {
                corner: {
                     target: 'topMiddle',
                     tooltip: 'bottomLeft'
                },
                adjust: {
                    y: -8
                }
            },
            content: {
                title : {
                    text : 'Beschreibung'
                }
            }
        })
        .css('cursor', 'help');

    $('#purchaseGroupForm option[title!=\'\']').qtip({
            style: {
                color: fontColor,
                name: 'cream',
                tip: 'rightMiddle',
                width: 350,
                title: {
                    'color': fontColor
                }
            },
            position : {
                corner: {
                     target: 'leftMiddle',
                     tooltip: 'rightMiddle'
                },
                adjust: {
                    x: -10
                }
            },
            content: {
                title : {
                    text : 'Beschreibung'
                }
            }
        })
        .css('cursor', 'help');
}

function addClassesToButtons()
{
    $('.ui-dialog-buttonpane button').each(
        function()
        {
            if ($(this).text() == 'Abbrechen') {
                $(this).addClass('asTextLink');
            } else {
                $(this).addClass('asSellButton');
                $(this).addClass('addToBasketButton');
            }
        });
}

function addDetailRow(id, rid, auto)
{
    var item = {};
    item.selectValue = id;
    item.extra = [];
    item.extra[1] = rid;

    prepareAddItem(item)

    //addItem(id);
}

function prepareAddItem(item)
{
    var id = item.selectValue,
    productPurchaseRuleId = 0;

    // has ProductPurchaseRule ? extra field index 1
    if (item.extra[1]) {
        productPurchaseRuleId = item.extra[1];
    }

    // nothing to show before adding
    if (!productPurchaseRuleId) {
        addItem(id);
    } else {
        showProductPurchaseRuleGroup(productPurchaseRuleId, id);
    }
}

function showProductPurchaseRuleGroup(productPurchaseGroupId, productId)
{
    if (!productPurchaseGroupId || !productId) {
        showError('Bitte wählen Sie einen Artikel aus der Liste!');
        setTimeout(
            function()
            {
                removeError();
            }, 3000);
        return false;
    }
    // Add loading div
    var loaderDiv = addItemRowLoader(),
    data = {
        'gid' : productPurchaseGroupId,
        'id' : productId
    };

    $.ajax( {
        type: "GET",
        async: true,
        url: "/default/ajax/get-rule-group",
        dataType: "json",
        data : data,
        success : function(data, textStatus) {
            // Wenn keine sichtbaren Reglen abgefragt werden müssen,
            // wird das Produkt direkt in den Warenkorb gelegt.
            if(data.couldAdd) {
                showDetailsRow(data.detailsRow, loaderDiv);
                $(".errorBox").hide();
                showShippinglabel(data.shippingLabelMessage, data.shippingLabelLimitReached);
                showSumRow(data.sumRow.html, data.sumRow.value);
            } else {
                 // remove old dialogs
                 $('div.asDialog').remove();
                 // build a new one
                 $(data.content).dialog({
                    autoOpen: false,
                    modal: true,
                    title : data.title,
                    dialogClass : 'productPurchaseRuleDialog',
                    width: 'auto',
                    height: 'auto',
                    buttons : {
                        'Hinzufügen': function(){
                                loaderDiv.hide();
                                params = $(this).children('form').serialize();
                                addItem(productId, params);
                                $(this).dialog('close');
                                $(this).dialog('destroy');
                        },
                        'Abbrechen' : function(){
                                loaderDiv.hide();
                                $(this).dialog('close');
                                $(this).dialog('destroy');
                            }
                        },
                    close: function(){
                        $("#search").focus();
                        loaderDiv.hide();
                    }
                });

                // delayed opener
                setTimeout(function()
                    {
                        addTooltips();
                        addClassesToButtons();
                        $('div.asDialog').dialog('open');
                    }, 500);
            }
        }
    });
}

function productPurchaseRuleValueCheckAmount()
{
    data = $('#purchaseGroupForm').serialize();

    $.ajax({
        type: "post",
        async: true,
        url: "/default/ajax/get-down-price-amount/",
        data: data,
        dataType: "json",
        success: function(data) {
                if (data.price) {
                    $('span.productPricePurchase').text(data.price);
                }
        },
        error: function() {
            showError('Die Anfrage konnte nicht erfolgreich abgeschlossen werden!');
        }
    });
    return false;
}

function showSuccess(text){
    return showError(text);
}
function showError(text){
    return showErrorBox(text);
}

// Adds a new item to the basket
function addItem(id, data)
{
    // Add loading div
    var loaderDiv = addItemRowLoader();

    $.ajax( {
        type: "POST",
        async: true,
        url: "/default/ajax/add-item/id/" + id + '/auto/false',
        dataType: "json",
        data : data,
        success : function(data, textStatus) {
            // Remove loaderDiv and show item details row, if succeeded
            if(data.couldAdd) {
                showDetailsRow(data.detailsRow, loaderDiv);
                $(".errorBox").hide();
                showShippinglabel(data.shippingLabelMessage, data.shippingLabelLimitReached);
                showSumRow(data.sumRow.html, data.sumRow.value);
            } else {
                loaderDiv.hide();
                showErrorBox(data.message);
            }
        }
    } );

    removeError();
    $("#search").focus();
}

// Removes an item from the basket
function removeItem(id,who)
{
    var elementRow = who;
    $.ajax( {
        type: "GET",
        url: "/default/ajax/remove-item/id/" + id,
        async: true,
        dataType: "json",
        data : {
        },
        success : function(data, textStatus) {
            $("#container")[0].removeChild(elementRow.parentNode);
            showSumRow(data.sumRow.html, data.sumRow.value);
            showShippinglabel(data.shippingLabelMessage, data.shippingLabelLimitReached);
        }
    } );

    removeError();
    $("#search").focus();
}

// Initializes the basket
function initSaleList()
{
    $.ajax( {
        type: "GET",
        url: "/default/ajax/get-basket",
        async: true,
        dataType: "json",
        data : {
        },
        success : function(data, textStatus) {
            for(var i=0; i<data.rows.length; i++) {
                showDetailsRow(data.rows[i]);
            }
            if (data.rows.length != 0) {
                showShippinglabel(data.shippingLabelMessage, data.shippingLabelLimitReached);
            }
            showSumRow(data.sumRow.html, data.sumRow.value);
        }
    } );
}

// Shows the item loading div
function addItemRowLoader()
{
    var loaderDiv = document.createElement("div");
    loaderDiv.className = "itemRowComplete";

    loaderDiv = $(loaderDiv);
    loaderDiv.css("background-color", "#ddd")
             .css("height", "65px")
             .css("font-size", "1.1em")
             .css("color", "#000")
             .css("font-weight", "bold")
             .css("text-align", "center")
             .css("padding-top", "65px")
             .text("Laden...");
    loaderDiv.fadeIn(500);

    $("#container").prepend(loaderDiv);
    return loaderDiv;
}

// Shows a item detail row
function showDetailsRow(html, container)
{
    if(container) {
        container.hide()
        container.replaceWith(html);
        container.show();
    } else {
        var itemRow = $("#container").prepend(html);
        itemRow.show();
    }
}

// Shows the sum row for the basket
function showSumRow(html, value)
{
    $("#sumRowContainer, #sumRowContainer1, #sumRowContainer2").html(html);
    $("#basketHeadline").html( "Aktuelle Versandbox" + value );

    onAfterShowSumRow(value);
}

// Forces a search
function checkSearch(e)
{
    if(e.type == "click") {
        $("#search")[0].autocompleter.forceSearch();
    }

    if(e.keyCode == 13) {
        $("#search")[0].autocompleter.forceSearch();
    }
} // checkSearch()

// Shows the error box
function showErrorBox(text)
{
    var tagBefore = '<div class="noticeBox"><img src="/images/default/info.png" />';
    var tagAfter = '<br style="clear:both" /></div>';

    removeError();

    $("#errorBoxHead").html(tagBefore + text + tagAfter);
    $("#errorBoxHead").fadeIn(250);
}

// Removes the error box
function removeError()
{
    $("#errorBoxHead").html("");
    $("#errorBoxHead").hide();
}

// Return the value from the category filter
function getFilteredCategory()
{
    return $("#categoryFilter").val() ? $("#categoryFilter").val() : 0;
}

// Forces the search after the category has been changed. If switched to "books" we show the ISBN-toolTip
function filterCategories()
{
    _filteredCategory = $("#categoryFilter").val();

    // Books?
    if(_filteredCategory == 91) {
        $("#toolTipPopupIsbn").fadeIn(500);
        window.setTimeout( function(){$("#toolTipPopupIsbn").fadeOut(500);}, 4000 );
    }

    $("#search").focus();
    $("#search")[0].autocompleter.forceSearch();
}


function showShippinglabel(message, limitReached)
{
    if (limitReached) {
        $('#shippingLabelGuaranteed').removeClass('limit-not-reached');
    } else {
        $('#shippingLabelGuaranteed').addClass('limit-not-reached');
    }

    $('#shippingLabelGuaranteed').html(message);
    $('#shippingLabelGuaranteed').show();
}

// Init all stuff after the document is loaded
$(document).ready( function() {
    $(".whatIsTheEAN > span").hover(
        function(e) {
            xOffset = 15;
            yOffset = -25;
            $(".eanInfoImage").fadeIn(500).css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px");
        },
        function() {
            $(".eanInfoImage").fadeOut(100);
        }
    );

    // Hack for reBuy.tv
    if(!dontInit) {
        initSaleList();
    }
    initAutocomplete();
    $("#search").focus();
    if(forceInitialSearch) {
        $("#search")[0].autocompleter.forceSearch();
    }
} );
