$(document).ready(function(){

    /*if($.browser.mozilla) {
            var scaleThem = false;
            var theirMaxHeight = false;
    } else {*/
            var scaleThem = true;
            var theirMaxHeight = '97%';
            var showDirectImage = (getUrlVars().showDirectImage==1)?true:false;
    //}

    $("a[rel='modal']").colorbox({
        maxHeight:theirMaxHeight,
        scalePhotos:scaleThem,
        initialWidth:'200px',
        initialHeight:'400px',
        current:'',
        photo:true,
        onLoad:function(){
            if (showDirectImage) return;
            $window = $(window);
            maxHeight = $(this).colorbox.getSettings().maxHeight;
            loadedHeight = $(this).colorbox.getLoadedHeight();
            interfaceHeight = $(this).colorbox.getInterfaceHeight();
            href = $(this).colorbox.getHref();
            imageScript = '/outputProductsImage.php';

            dimension = $window.height();
	    size = (typeof maxHeight === 'string') ? Math.round((/%/.test(maxHeight) ? (dimension / 100) * parseInt(maxHeight, 10) : parseInt(maxHeight, 10))) : maxHeight;

            calculatedHeight = size - loadedHeight - interfaceHeight;

            newHref = imageScript + '?src=' + encodeURIComponent(href) + '&h=' + calculatedHeight + '&q=100&s=1';

            $(this).colorbox.setHref(newHref);
        },
        onComplete:function(){
            $('#cboxPhoto').bind("contextmenu", function(e) {
                alert("Unsere Produktfotografien sind mittels eines digitalen Wasserzeichens vor unerlaubter kommerzieller Verwendung geschützt.\n\nVielen Dank für Ihr Verständnis.");
                return false;
            });
        }
    });

    $("a.products_detail_img").colorbox({
        rel:'a.products_detail_img',
        maxHeight:theirMaxHeight,
        scalePhotos:scaleThem,
        initialWidth:'200px',
        initialHeight:'400px',
        current:'',
        photo:true,
        onLoad:function(){
            if (showDirectImage) return;
            $window = $(window);
            maxHeight = $(this).colorbox.getSettings().maxHeight;
            loadedHeight = $(this).colorbox.getLoadedHeight();
            interfaceHeight = $(this).colorbox.getInterfaceHeight();
            href = $(this).colorbox.getHref();
            imageScript = '/outputProductsImage.php';

            dimension = $window.height();
	    size = (typeof maxHeight === 'string') ? Math.round((/%/.test(maxHeight) ? (dimension / 100) * parseInt(maxHeight, 10) : parseInt(maxHeight, 10))) : maxHeight;

            calculatedHeight = size - loadedHeight - interfaceHeight;

            newHref = imageScript + '?src=' + encodeURIComponent(href) + '&h=' + calculatedHeight + '&q=100&s=1';

            $(this).colorbox.setHref(newHref);
        },
        onComplete:function(){
            $('#cboxPhoto').bind("contextmenu", function(e) {
                alert("Unsere Produktfotografien sind mittels eines digitalen Wasserzeichens vor unerlaubter kommerzieller Verwendung geschützt.\n\nVielen Dank für Ihr Verständnis.");
                return false;
            });
            width = $('#cboxLoadedContent').width();
            values = $(this).attr('rel').split('|');
            id = values[0];
            size = values[1];
            baseprice = values[2];
            price = values[3];
            linktext  = values[4];
            title = $(this).attr('title');

            left = (width - 300)/2;

            html = '<table style="width:300px;position:absolute;left:' + left + 'px;top:30px;z-index:10000;margin:0;padding:0;"><thead><tr><th align="left">Größe</th><th align="right">€/Liter</th><th align="right">Preis</th><th align="right">Option</th></tr></thead><tbody><tr><td align="left">' + size + '</td><td align="right">' + baseprice + ' €/L</td><td align="right">' + price + ' €</td><td align="right"><strong><a href="#" onclick="openOrderForm(\'' + title + '\', ' + id + ')">' + linktext + ' &raquo;</a></strong></td></tr></tbody></table>';
            $(html).appendTo('#cboxLoadedContent');
        }

    });

    $("a.buy").colorbox({
        width   :   '500px',
        height  :   '100px',
        rel     :   'nofollow',
        html    :   function (){return orderform($(this).attr('rel'));},
        onComplete  : function(){
            $('input[name=quantity]').focus();
        }
    });

    $(".expand").svTruncate({maxTextLen: 300});

    $('.shopping-basket-link').mouseover(function(){
        mouseInBasket = false;
        mouseOnLink = true;
        if (basketVisible) return;
        setTimeout(function(){
            showShoppingBasket();
        }, 400);
    });
    $('.shopping-basket-link').mouseout(function(){
        mouseInBasket = false;
        mouseOnLink = false;
        setTimeout('hideShoppingBasket()', 500);
    });

    $('#shoppingBasketPreview').mouseenter(function(){
        mouseInBasket = true;
        mouseOnLink = false;
    });
    $('#shoppingBasketPreview').mouseleave(function(){
        setTimeout(function(){
            mouseInBasket = false;
            hideShoppingBasket();
        }, 500);
    });
});

var mouseOnLink = false;
var mouseInBasket = false;
var basketVisible = false;

function orderform(id){
    if (typeof(id) == 'undefined') products_id = $(this).attr('rel');
    else products_id = id;
    html = "<div align='center'>"
        + "<form action='/bestellung/warenkorb' method='get' rel='modal'>"
        + "<input type='hidden' name='products_id' value='" + products_id + "' />"
        + "<input type='text' class='small' name='quantity' value='1' />&nbsp;&nbsp;x&nbsp;&nbsp;"
        + "<strong><a href='#' onclick='$(this).closest(\"form\").submit();$.colorbox.close();return false;'>in den Warenkorb legen</a></strong>"
        + "</form>"
        + "</div>";
    return html;
}

function openOrderForm(title, id){
    $.colorbox(
    {
        rel     :   'nofollow',
        title   :   title,
        width   :   '500px',
        height  :   '100px',
        html    :   orderform(id),
        onComplete  : function(){
            $('#cboxNext').hide();
            $('#cboxPrevious').hide();
            $('input[name=quantity]').focus();
        }
    });
}

function showShoppingBasket(){
    if(!mouseOnLink) return;
    
    url = '/bestellung/warenkorb_json';

    $.getJSON(url, function(json){
            if (json.success)
            {
                //alert(json.products.length);
                if(json.products.length == 0){
                    $('#shoppingBasketPreview').empty();
                    $('#shoppingBasketPreview').append('<h2>Ihr Warenkorb ist leer</h2>');
                } else {
                    var myTable = '<h2>Ihr Warenkorb enthält:</h2>' ;
                    myTable += '<table id="shoppingBasketPreviewTable" cellspacing=0 cellpadding=0 border=0>' ;
                    myTable +=  "<thead>" ;
                    myTable +=   "<tr><th align=left>Anzahl</th><th align=left>Artikelbezeichnung</th><th align=right>Gesamtpreis</th></tr>";
                    myTable +=  "</thead>" ;
                    myTable +=  "<tbody>" ;

                    for (var i = 0; i < json.products.length; i++) {
                        myTable +=    "<tr>";
                        myTable +=    "    <td align=center>" + json.products[i]['quantity'] + "</td><td align=left>" + json.products[i]['name'] + " " + json.products[i]['sur_name'] + "</td><td align=right>" + parseFloat(json.products[i]['price_total']).toFixed(2) + " €</td>";
                        myTable +=    "</tr>";
                    }
                    myTable +=   "<tr><td colspan=3><hr /></td></tr>";
                    myTable +=   "<tr><td colspan=2 align=right><strong>Zwischensumme:</strong></td><td align=right>" + parseFloat(json.final_price).toFixed(2) + " €</td></tr>";
                    myTable +=  "</tbody>" ;
                    myTable += "</table>" ;
                    myTable += '<div>&nbsp;</div><table width=100%><tr><td align=left><a href=/bestellung/warenkorb>Zum Warenkorb »</a></td><td align=right><a href=/bestellung/lieferadresse>Zur Kasse »</a></td></tr></table>';
                    $('#shoppingBasketPreview').empty();
                    $('#shoppingBasketPreview').append(myTable);
                }
            }
            else
            {
                $('#shoppingBasketPreview').append('somethings wrong...');
            }
    });
    
    $('#shoppingBasketPreview').show();
    basketVisible = true;
}

function hideShoppingBasket(){
        if (mouseInBasket || mouseOnLink) return;
        $('#shoppingBasketPreview').hide();
        basketVisible = false;
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
