/* Prices and Discounts */
var prices = {};
var basket = false;
var currency = false;
var alternateCurrency = false;
var onDiscountChanged = null;

function setPrice(variant, value)
{
    var active = prices[variant][value];
    prices[variant].active = active;
    $('#price' + variant + currency).text(active.price['p0'][currency]);
    if (alternateCurrency) {
        $('#price' + variant + alternateCurrency).text(active.price['p0'][alternateCurrency]);
    }
    refreshTotalDiscountPrice(variant);
}

function setDiscounts(type, on)
{
    var value = on ? 'yes' : 'no';
    var name = 'price_discount_' + type;
    var inputs = $('input[name=' + name + ']');
    for (var i = 0; i < inputs.length; i++) {
        $(inputs.get(i)).val(value);
    }
    if (basket) {
        refreshBasket();
    } else {
        for (var key in prices) {
            refreshTotalDiscountPrice(key);
        }
    }
    if (onDiscountChanged) {
        onDiscountChanged();
    }
}

function refreshTotalDiscountPrice(variant)
{
    var first = true;
    var totalPercent = 0;
    var maxPercent = 5;
    for (var key in discounts) {
        var discount = discounts[key];
        var enabled = $('input[name=price_discount_' + discount + ']').val() == 'yes';
        if (!enabled) {
            $('#price_' + variant + '_discount_' + discount + '_' + currency).text(0);
            continue;
        }
        var percent = first ? discountsPercent[0] : discountsPercent[1];
        $('#price_' + variant + '_discount_' + discount + '_' + currency).text(prices[variant].active.discount['p' + percent][currency]);
        totalPercent += percent;
        first = false;
    }

    var totalDiscountPrice = totalPercent > 0 ? prices[variant].active.discount['p' + totalPercent][currency] : 0;
    $('#price_' + variant + '_discount_total_' + currency).text(totalDiscountPrice);
    var info = prices[variant].active.price['p' + totalPercent];
    $('#price_' + variant + '_total_' + currency).text(info[currency]);

    var videoPercent = 0;
    if (totalPercent == 0) {
        videoPercent = discountsPercent[0];
    } else if (totalPercent + discountsPercent[1] < maxPercent) {
        videoPercent = discountsPercent[1];
    } else {
        videoPercent = maxPercent - totalPercent;
    }

    var videoDiscountPrice = prices[variant].active.discount['p' + videoPercent][currency];
    $('#price_' + variant + '_review_discount_' + currency).text(videoDiscountPrice);
    $('#price_' + variant + '_review_discount_' + currency + '_2').text(videoDiscountPrice);
    if (alternateCurrency) {
        var videoDiscountAlternatePrice = prices[variant].active.discount['p' + videoPercent][alternateCurrency];
        $('#price_' + variant + '_review_discount_' + alternateCurrency + '_2').text(videoDiscountAlternatePrice);
    }
}

function refreshBasket()
{
    var first = true;
    var totalPercent = 0;
    var maxPercent = 5;
    for (var key in discounts) {
        var discount = discounts[key];
        var enabled = $('input[name=price_discount_' + discount + ']').val() == 'yes';
        if (!enabled) {
            var percent = 0;
            $('#price_discount_' + discount + '_' + currency).text(prices.discounts[percent + 'percent'][currency]);
            continue;
        }
        var percent = first ? discountsPercent[0] : discountsPercent[1];
        $('#price_discount_' + discount + '_' + currency).text(prices.discounts[percent + 'percent'][currency]);
        totalPercent += percent;
        first = false;
    }

    $('#price_discount_total_' + currency).text(prices.discounts[totalPercent + 'percent'][currency]);

    var videoPercent = 0;
    if (totalPercent == 0) {
        videoPercent = discountsPercent[0];
    } else if (totalPercent + discountsPercent[1] < maxPercent) {
        videoPercent = discountsPercent[1];
    } else {
        videoPercent = maxPercent - totalPercent;
    }
    var videoDiscountPrice = videoPercent > 0 ? prices.discounts[videoPercent + 'percent'][currency] : prices.discounts['0percent'][currency];
    $('#price_discount_video_' + currency).text(videoDiscountPrice);

    // update prices according to total discount applied
    var newPrices = prices[totalPercent + 'percent'];
    for (var i = 0; i < newPrices.items.length; i++) {
        var newItemPrices = newPrices.items[i];
        $('#price_' + i + '_' + currency).text(newItemPrices[currency]);
        if (alternateCurrency) {
            $('#price_' + i + '_' + alternateCurrency).text(newItemPrices[alternateCurrency]);
        }
        $('#price_' + i + '_total_' + currency).text(newItemPrices['total_' + currency]);
        if (alternateCurrency) {
            $('#price_' + i + '_total_' + alternateCurrency).text(newItemPrices['total_' + alternateCurrency]);
        }
    }
    var update = ['total', 'subtotal', 'discount', 'delivery'];
    for (var x in update) {
        var key = update[x];
        $('#price_' + key + '_' + currency).text(newPrices[key][currency]);
        if (alternateCurrency) {
            $('#price_' + key + '_'+ alternateCurrency).text(newPrices[key][alternateCurrency]);
        }
    }
}

$(function () {
    $('select[name$=sirka]').change(function(){
        if (undefined != this.selectedIndex) {
            setPrice(this.form.variant.value, this.options[this.selectedIndex].value);
        }
    }).change();
    $('input[name$=_discount_scrap_radio]').change(function(){
        setDiscounts('scrap', this.value == 'yes');
        var inputs = $('input[name$=_discount_scrap_radio]');
        for (var i = 0; i < inputs.length; i++) {
            var input = inputs.get(i);
            if (input == this) {
                continue;
            }
            if (basket || input.form.variant.value == this.form.variant.value) {
                continue;
            }
            input.checked = input.value == this.value && this.checked;
        }
    });
    $('a.showhint').click(showHintOnClick);

});


function showHintOnClick()
{
    var root = this.parentNode.parentNode.parentNode;
    generateHints(root);
    toggleHints(root);
    return false;
}

function generateHints(root)
{
    $('.showhint', root).each(function (index, node) {
        generateHint(node);
    });
}

function toggleHints(root)
{
	$('.showhint', root).each(function (index, node) {
        var hint = $(node).data('hint');
        if (hint) {
            hint.toggle();
        }
    });
}
function generateHint(node)
{
    var jQNode = $(node);
    if (jQNode.data('hint')) {
        return;
    }
    var title = jQNode.attr('title');
    var content = $('.hintcontent', jQNode);
    if (!title && !content.length) {
        return;
    }
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(node);
	var clickElementy = getAbsoluteTop(node) - 3; //set y position

	var params = [];
	params['width'] = 250;
    params['force_right'] = jQNode.hasClass('hint_right');
    params['force_left'] = jQNode.hasClass('hint_left');

    var hint;
    var clickElementx;
	if (params['force_left'] || hasArea > ((params['width']*1)+75) && !params['force_right']) {
		hint = $("<div class='hint' style='display:none;width:"+params['width']*1+"px'><div class='hint_arrow_left'></div><div class='hint_close_left'>"+title+"</div><div class='hint_content'></div></div>");
		var arrowOffset = getElementWidth(node) + 11;
		 clickElementx = getAbsoluteLeft(node) + arrowOffset;
    } else {
        hint = $("<div class='hint' style='display:none;width:"+params['width']*1+"px'><div class='hint_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div class='hint_close_right'>"+title+"</div><div class='hint_content'></div></div>");
		clickElementx = getAbsoluteLeft(node) - ((params['width']*1) + 15);
	}
    hint.css({left: clickElementx+"px", top: clickElementy+"px"});
    if (content) {
        $('.hint_content', hint).append(content);
    }
    if (!title) {
        $('.hint_close_left, .hint_close_right', hint).hide();
    }
    $("body").append(hint);
    jQNode.data('hint', hint);
}

function getElementWidth(x) {
	return x.offsetWidth;
}

function getAbsoluteLeft(o) {
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(o) {
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

$(document).ready(function(){
    $('#billing_variant').change(function(){
        var self = $(this);
        var parent = self.parents('fieldset');
        var a = parent.children()
        a.hide();
        var b = parent.find('.' + self.val());
        b.show();
    }).change();

    $("a[rel^='prettyPhoto']").prettyPhoto({
        theme: 'facebook',
        overlay_gallery: false,
        show_title: false,
        autoplay: 'true',
        markup: locale.prettyPhoto.markup
    });

    $('.qty input').keypress(function(e){
        if (e.keyCode == 13) {
            $(this).parents('form').find('[name=action_update]').click();
            return false;
        }
    })
    $('button[type=submit]').click(function(){
        $('button', this.form).attr('disabled', true);
        this.disabled = false;
        return true;
    })
});

