jQuery.fn.compare = function(t) {
    if (this.length != t.length) {return false;}

    for (var i = 0; t[i]; i++) {
        if (this[i] != t[i]) {
                return false;
        }
    }
    return true;
};

jQuery.fn.arrayInArray = function(t) {
    if (this.length > t.length) {return false;}

    for (var i = 0; i < this.length; i++) {
        if (jQuery.inArray(this[i], t) == -1) {
            return false;
        }
    }
    return true;
}

var eshopProduct = new Object();
eshopProduct['images'] = [];
eshopProduct['combinations'] = {};

var eshopProductSettings = new Object();

//default eshop settings
eshopProductSettings['hasCombinations'] = 0;

eshopProductAddImage = function(hash, thumb, picture, big)
{
    eshopProduct['images'].push({hash: hash, thumb: thumb, picture: picture, big: big});
}

eshopProductAddCombination = function(id, attributes, price, stock, weight, sizeWidth, sizeHeight, sizeDepth, imageHash)
{
    //eshopProduct['combinations'].push ({id: id, attributes: attributes, price: price, stock: stock, weight: weight, sizeWidth: sizeWidth, sizeHeight: sizeHeight, sizeDepth: sizeDepth, imageHash: imageHash});
    eshopProduct['combinations'][id] = eval('({id: id, attributes: attributes, price: price, stock: stock, weight: weight, sizeWidth: sizeWidth, sizeHeight: sizeHeight, sizeDepth: sizeDepth, imageHash: imageHash})');
}

eshopSetCombination = function(attr, index)
{
    var i;

    if ((index + 1) < attr.length) {
        attr = eshopUpdateCombinationSelect(attr, index);
    }

    for (i in eshopProduct.combinations){
        if ($(attr).compare(eshopProduct.combinations[i].attributes)) {
            /*
            if (eshopProductSettings.stockType == 2 && eshopProduct.combinations[i].stock <= 0 && i != eshopProductSettings.defaultCombination) {
                break;
            }
            */
            eshopProduct.currentCombination = i;
            eshopUpdateProductView();
            return;
        }
    }
    
    //alert($.i18n('Combination not found'));
    eshopProduct.currentCombination = eshopProductSettings['defaultCombination'];
    eshopUpdateProductView();
    eshopUpdateCombinationSelect(eshopProduct.combinations[eshopProductSettings.defaultCombination].attributes,0,eshopProduct.combinations[eshopProductSettings.defaultCombination].attributes);

}

eshopUpdateCombinationSelect = function (attribute, index, def)
{

    var i, first = 1;
    var attr = [];
    for (i in attribute) {
        attr[i] = attribute[i];
    }

    index = parseInt(index);
    var testArr = attr.slice(0,index);

    if (index == 0) {
        $('#eshopProductAttrIndex-'+index+' option').removeAttr('disabled');
    } else {
        $('#eshopProductAttrIndex-'+index+' option').attr('disabled', 'disabled');
        $('#eshopProductAttrIndex-'+index+' option').removeAttr('selected');
        
        for (i in eshopProduct.combinations ) {
            if ( $(testArr).arrayInArray(eshopProduct.combinations[i].attributes) ) {
                $('#eshopProductAttrIndex-'+index+' option[value='+eshopProduct.combinations[i].attributes[index]+']').removeAttr('disabled');
                if (first == 1) {
                    first = 0;
                    
                    if (def == undefined) {
                        $('#eshopProductAttrIndex-'+index+' option[value='+eshopProduct.combinations[i].attributes[index]+']').attr('selected', 'selected');
                    }
                    
                    attr[index] = eshopProduct.combinations[i].attributes[index];
                }
            }
        }
    }

    if (def != undefined) {
        $('#eshopProductAttrIndex-'+index+' option[value='+def[index]+']').attr('selected', 'selected');
    }

    if ( (index + 1) < attr.length) {
        return eshopUpdateCombinationSelect(attr, index + 1, def);
    }

    return attr;

}

eshopUpdateProductView = function()
{
    var i;
    var product;

    //default values
    $('#eshop-product-stock').html('');
    $('#eshop-product-weight').html('');
    $('#eshop-product-sizeWidth').html('');
    $('#eshop-product-sizeHeight').html('');
    $('#eshop-product-sizeDepth').html('');
    $('#eshop-product-priceWithoutVat').html('');
    $('#eshop-product-priceWithVat').html('');
    $('#eshop-product-priceVat').html('');
    $('.eshop-product-priceNormal').hide();
    $('.eshop-product-priceDiscount').hide();
    $('.eshop-product-addToCart').hide();
    $('.eshop-product-availability').html('');

    if (eshopProductSettings['hasCombinations'] == 1) {

        product = eshopProduct.combinations[eshopProduct.currentCombination];
        for (i = 0; i < product.attributes.length; i++) {
            $("select[name=eshop-product-attr[]] option[value="+product.attributes[i]+"]:not(:selected)").parent().val(product.attributes[i]);
        }

        if (product.imageHash) {
            for (i = 0; i < eshopProduct.images.length; i++) {
                if (eshopProduct.images[i].hash == product.imageHash) {
                    product['imageId'] = i;
                    break;
                }
            }
        }

        $('input#sugVariant').val(eshopProduct.currentCombination);
        if (product.imageId == undefined)
            product['imageId'] = eshopProduct.product.imageId;
    } else {
        product = eshopProduct.product;
    }

    //price
    $('#eshop-product-priceWithoutVat').html(eshopRound(product.price.actual.withoutVat, eshopProductSettings.currency.decimals));
    $('#eshop-product-priceWithVat').html(eshopRound(product.price.actual.withVat, eshopProductSettings.currency.decimals));
    $('#eshop-product-priceVat').html(product.price.actual.vatRate + '%');
    if (product.price.old != undefined) {
        $('#eshop-product-priceNormal').html(eshopRound(product.price.old.withVat, eshopProductSettings.currency.decimals));

        //$('#eshop-product-priceDiscount').html( eshopRound((product.price.old.withVat - product.price.actual.withVat)/product.price.old.withVat*100) + '% / ' + eshopRound(product.price.old.withVat - product.price.actual.withVat, eshopProductSettings.currency.decimals));
        $('#eshop-product-priceDiscount').html( eshopRound((product.price.old.withVat - product.price.actual.withVat)/product.price.old.withVat*100, 0) + '%');
        $('.eshop-product-priceNormal').show();
        $('.eshop-product-priceDiscount').show();
    }

    $('#eshop-product-stock').html(eshopRound(product.stock, 4));
    $('#eshop-product-weight').html(eshopRound(product.weight));
    $('#eshop-product-sizeWidth').html(eshopRound(product.sizeWidth));
    $('#eshop-product-sizeHeight').html(eshopRound(product.sizeHeight));
    $('#eshop-product-sizeDepth').html(eshopRound(product.sizeDepth));

    if ( (eshopProductSettings.stockType != 1 && product.stock > 0) || eshopProductSettings.stockType == 1)
        $('.eshop-product-addToCart').show();
    
    //product availability
    if (eshopProductSettings.stockType == 1 || product.stock > 0) {
        $('.eshop-product-availability').html($.i18n('In stock'));
    }/* else if (eshopProductSettings.stockType != 1 && product.stock == 1) {
        $('.eshop-product-availability dd').html($.i18n('Last item'));
    }*/ else {
        $('.eshop-product-availability').html($.i18n('Sold out'));
    }

    if (eshopProductSettings.stockType != 1 && product.stock == 1) {
        $('div.eshop-product-detail div.eshop-lastItem').show();
    } else {
        $('div.eshop-product-detail div.eshop-lastItem').hide();
    }

    $('.eshop-product-priceSymbol').html(eshopProductSettings.currency.symbol);
    eshopDisplayImage(product.imageId);
    $('#eshop-product-images-slideshow').trigger('goto', [product.imageId]);

}

eshopDisplayImage = function (id)
{
    $("img.eshop-product-mainImage").attr('src', '/var/files/' + eshopProduct.images[id].big);
}

loadProduct = function()
{
    $(document).ready(function()
    {
	$('#eshop-product-images-slideshow').serialScroll({
		items:'li',
		prev:'a#eshop-product-prev-image',
		next:'a#eshop-product-next-image',
		offset: 0, //when scrolling to photo, stop 230 before reaching it (from the left)
		start:1, //as we are centering it, start at the 2nd
		duration: 400,
		force:true,
		stop:true,
		lock:false,
		cycle:false,//don't pull back once you reach the end
                onBefore: function(e, t, s, c, p){
                    $(c).removeClass('selected');
                    $(t).addClass('selected');
                    eshopDisplayImage($(t).attr('id').split('-')[1]);
                }
		/*easing:'easeOutQuart', //use this easing equation for a funny effect*/
		/*jump: true //click on the images to scroll to them*/
	});

        eshopUpdateProductView();
        //$("div#eshop-product-images-slideshow ul li").hover(function(){eshopDisplayImage($(this).attr('id').split('-')[1]);});

        $("select[name=eshop-product-attr[]]").bind('change', function(){eshopSetCombination($("select[name=eshop-product-attr[]] option:selected").map(function(i, e){return parseInt(e.value);}).get(), $(this).attr('id').split('-')[1]);});

    });
}

eshopProductAddIntoCart = function(id, comb, unit, quantity)
{

    if (id == undefined) {
        id = eshopProduct.id;
        if (eshopProductSettings['hasCombinations'] == 1) {
            comb = eshopProduct.currentCombination;
        }

        unit = $('select[name=eshop-product-unit]').val();
        quantity = $('input[name=eshop-product-quantity]').val();
    }
    $.ajax({
        type: "POST",
        url: "/system/eshop/addProduct/",
        async: false,
        data: {
            productId: id,
            unitId: unit,
            combinationId: comb,
            quantity: quantity,
            lang: pageLang
        },
        dataType: "json",
        success: function(ret){
            if (ret.err != null) {
                showDialog($.i18n('Error'), ret.err);
                return;
            }

            $('p span.eshop-basketPanel-price').html(ret.totalPrice.withVat);
            $('p span.eshop-basketPanel-totalItems').html(ret.totalItems);
            $('p span.eshop-basketPanel-totalItemsTxt').html(ret.totalItemsTxt);
            
            showDialog ($.i18n('Info'), $.i18n('The product has been added to cart'));

            $('div.basket').effect("highlight", {}, 500);
            //$('div.eshop-basketPanel-totalPrice div.eshop-basketPanel-productsList').html(ret.basketPanelTable); -product list table

        }
    });

}

eshopProductRemoveFromCart = function (itemId)
{
    $.ajax({
        type: "POST",
        url: "/system/eshop/removeProduct/",
        async: false,
        data: {
            itemId: itemId,
            lang: pageLang
        },
        dataType: "json",
        success: function(ret){
            if (ret.err != null) {
                showDialog($.i18n('Error'), ret.err);
                return;
            }

            if (ret.totalPrice)
                $('div.eshop-basketPanel-totalPrice p span.eshop-basketPanel-price').html(ret.totalPrice.withVat);
            else
                $('div.eshop-basketPanel-totalPrice p span.eshop-basketPanel-price').html(0);

            $('div.eshop-basketPanel-totalPrice div.eshop-basketPanel-productsList table tbody tr#basket-item-'+itemId).remove();
            //$('div.eshop-basketPanel-totalPrice div.eshop-basketPanel-productsList').html(ret.basketPanelTable);
            
        }
    });
}

eshopUpdateBasket = function (itemId, inputId)
{
    var count;
    if (inputId) {
        count = $('input#item-'+inputId).val();
    } else{
        count = 0;
    }

    $.ajax({
        type: "POST",
        url: "/system/eshop/update-basket/",
        async: false,
        data: {
            itemId: itemId,
            count: count,
            lang: pageLang
        },
        dataType: "json",
        success: function(ret){
            if (ret.err != null) {
                $('input#item-'+inputId).val(ret.count);
                showDialog($.i18n('Error'), ret.err);
                return;
            }

            $('div#eshop-basket-content').html(ret.content);
        }
    });
    
}

eshopUpdateSelectPayment = function()
{
    $.ajax({
        type: "POST",
        url: "/system/eshop/update-select-payment/",
        async: false,
        data: {
            lang: pageLang,
            country: $('#sap_country').val()
        },
        dataType: "json",
        success: function(ret){
            if (ret.err != null) {
                showDialog($.i18n('Error'), ret.err);
                return;
            }

            $('#sap_payment').html(ret.content);
            $('#sap_payment input[type=radio]').bind('change', function(){eshopUpdateSelectShipping();});
            $('#sap_payment input:checked').trigger('change');
        }
    });
}

eshopUpdateSelectShipping = function()
{
    $.ajax({
        type: "POST",
        url: "/system/eshop/update-select-shipping/",
        async: false,
        data: {
            lang: pageLang,
            country: $('#sap_country').val(),
            payment: $('#sap_payment input:checked').val()
        },
        dataType: "json",
        success: function(ret){
            if (ret.err != null) {
                showDialog($.i18n('Error'), ret.err);
                return;
            }

            $('#sap_shipping').html(ret.content);
        }
    });
}

eshopRound = function(value, decimals)
{
    value = parseFloat(value);
    
    if (decimals == undefined)
        decimals = 2;

    return value.toFixed(decimals);
}

eshopProductSuggestToFriend = function(loggedIn)
{

    var btns = {};

    btns[$.i18n('Send email')] = function() {
        if (!validatorRequire('#sugToEmail', $.i18n('Please enter email'), $.i18n('Error'))) return false;
        if (!validatorEmail('#sugToEmail', $.i18n('Please enter valid email'), $.i18n('Error'))) return false;
        if (!validatorRequire('#sugFromEmail', $.i18n('Please enter email'), $.i18n('Error'))) return false;
        if (!validatorEmail('#sugFromEmail', $.i18n('Please enter valid email'), $.i18n('Error'))) return false;
        if (!validatorRequire('#sugFromName', $.i18n('Please enter name'), $.i18n('Error'))) return false;
        if (loggedIn != 1)
            if (!validatorCaptcha('#sugDialogCaptcha_word', '#sugDialogCaptcha_id', $.i18n('Please enter valid code'), $.i18n('Error'))) return false;
        
        $('form#productSuggestForm').submit();

    };

    btns[$.i18n('Close')] = function() {$(this).dialog("close");};

    $("#eshop-dialogSuggest").dialog({
        modal: true,
        position: 'center',
        bgiframe: true,
        minWidth: 380,
        minHeight: 400,
        resizable: false,
        title: $.i18n('Suggest product'),
        close: function(event, ui) {
                $('#eshop-dialogSuggest').dialog('destroy');
        },
        open: function(event, ui) {
            reloadCaptcha('sugDialogCaptcha');
        },
        buttons: btns

    });

}

