﻿var flash_width = 350;
var flash_height = 420;
var flash_path = null;
var ratio = 0.5;
var basePrice = 600;
var boxPrice = 80;
var shippingPrice = 200;
var xFactor = 0.82;
var minPrice = 350;
var params = { wmode: 'transparent' };
$(document).ready(function() {
    //загружаем flash
    if ($('#sticker').length > 0 && flash_path != null) {
        swfobject.embedSWF(flash_path, "sticker", flash_width, flash_height, "9.0.0", "expressInstall.swf", {}, params);
    }
    //Обработка формы заказа
    $('input[name=size],input[name=payment],input[name=shipping]').click(function() {
        CalculateTotal();
    });
    $('input[name=quantity]').change(function() {
        CalculateTotal();
    });
    //Персчет размеров
    $('#height,#width').change(CalculateSize);
    //Валидация формы добавления в корзину
    $("form#Product").validate({
        rules: {
            quantity: { required: true, range: [1, 1000] },
            customPrice: { required: function(element) { return $('[name=size]:checked').val() == 0; } }
        },
        messages: {
            quantity: { required: "Укажите, пожалуйста, количество наклейки", range: "Укажите, пожалуйста, количество наклейки" },
            customPrice: { required: "Укажите, пожалуйста, размер наклейки" }
        }
    });
    $("form#Product").submit(
    function() {
        CalculateTotal();
        if ($(this).valid()) {
            AddToCart(this);
        }
        return false;
    });

    var objImagePreloader = new Image();
    objImagePreloader.onload = function() {

        var sourceSrc = $("#photo img").attr('src');
        var targetSrc = $("#photo a").attr('href');
        $("#photo a").click(function() { return false; });

        var defaultImageHeight = $("#photo img").get(0).height;
        var defaultImageWidth = $("#photo img").get(0).width;

        $("#photo ul.thumb li").css({ width: defaultImageWidth + 'px', height: defaultImageHeight + 'px' });
        $("#photo img").css({ position: 'absolute', top: '0px', left: '0px', width: defaultImageWidth + 'px', height: defaultImageHeight + 'px' });

        $("#photo ul.thumb li").hover(function() {
            $(this).css({ 'z-index': '10' }); /*Add a higher z-index value so this image stays on top*/
            $(this).find('img').attr('src', targetSrc);
            $(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
		.animate({
		    marginTop: '-75px', /* The next 4 lines will vertically align this image */
		    marginLeft: '-110px',
		    top: '50%',
		    left: '50%',
		    width: objImagePreloader.width + 'px', /* Set new width */
		    height: objImagePreloader.height + 'px'/*,  Set new height */
		}, 600);

        }, function() {
            $(this).css({ 'z-index': '0' }); /* Set z-index back to 0 */
            $(this).find('img').attr('src', sourceSrc);
            $(this).find('img').removeClass("hover").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
		.animate({
		    marginTop: '0', /* Set alignment back to default */
		    marginLeft: '0',
		    top: '0',
		    left: '0',
		    width: defaultImageWidth + 'px', /* Set width back to default */
		    height: defaultImageHeight + 'px'/*,  Set height back to default */
		}, 600);
        });

        objImagePreloader.onload = function() { };
    };
    if ($("#photo a").size() > 0) {
        $("#photo a").removeAttr('title');
        objImagePreloader.src = $("#photo a").attr('href');
    }

    CalculateTotal();
    LoadCartView();
});

function LoadCartView() {
    $.post('/Cart/Small',
            {},
            function(html) {
                SetCartHtml(html);
            }, 'html');
}

function SetCartHtml(html) {
    if (html == '') {
        $('#cart').html(html).removeClass('visible');
    }
    else {
        $('#cart').html(html).addClass('visible').show();
    }
}

function CalculateSize() {
    var height = 0;
    var width = 0;

    if ($(this).attr('id') == 'height') {
        //height
        height = parseInt($(this).val());
        height = height > 0 ? height : 0;
        var width = parseInt(Math.round(height / ratio));
    }
    else {
        //width
        width = parseInt($(this).val());
        width = width > 0 ? width : 0;
        var height = parseInt(Math.round(width * ratio));
    }

    $('#height').val(height);
    $('#width').val(width);

    var price = (height * width / 10000.0) * basePrice + boxPrice;
    price += xFactor * (price + shippingPrice);
    price = 1.05 * (price + shippingPrice) - shippingPrice;
    price = Math.round(price);

    price = price > minPrice ? price : minPrice;

    //round
    if (price % 10 != 0) {
        price = (parseInt(price - (price % 10)) / 10 + 1) * 10;
    }

    var isValid = height > 0 && width > 0;

    $('[name=size][value=0]').attr('price', isValid ? price : 0);
    $('#extraprice').html((isValid ? price : 0) + ' руб')
    $('#customPrice').val((isValid ? price : ''));

    CalculateTotal();
}

function CalculateTotal() {
    var price = parseInt($('input[name=size]:checked').attr('price'));
    var quantity = parseInt($('input[name=quantity]').val()) ? parseInt($('input[name=quantity]').val()) : 1;
    var payment = 0; //parseInt($('input[name=payment]:checked').attr('price'));
    var shipping = 0; //parseInt($('input[name=shipping]:checked').attr('price'));
    var total = price * quantity + payment + shipping;
    $('#TotalPrice').html(!isNaN(total) ? total : '');
}
//Функции обновления цвета фона и наклейки
function update_content(color, name) {
    $('#color').val(name.replace(/color /, ''));
    $('#color_code').val(color);
}
function update_back(color) {
    //someday maybe
}

function AddToCart(form) {
    var productX = $('#photo ul.thumb li').offset().left;
    var productY = $('#photo ul.thumb li').offset().top;


    var basketX = $('#cart').offset().left;
    var basketY = $('#cart').offset().top;

    var gotoX = basketX - productX;
    var gotoY = basketY - productY;

    var newImageWidth = $('#photo img').width() / 3;
    var newImageHeight = $('#photo img').height() / 3;

    var cartHtml = '';
    var flyFinished = false;
    $.post($(form).attr('action'),
            {
                productId: $('#productId').val(),
                height: $('[name=size]:checked').val() == 0 ? $('#height').val() : $('[name=size]:checked').val().split(',')[1],
                width: $('[name=size]:checked').val() == 0 ? $('#width').val() : $('[name=size]:checked').val().split(',')[0],
                color: $('#color').val(),
                quantity: $('[name=quantity]').val()
            },
            function(html) {
                cartHtml = html;
                if (flyFinished) {
                    $('#cart').removeClass('progress');
                    SetCartHtml(html);
                }
                pageTracker._trackPageview("/Cart/Add");


            }, 'html');

    $('#photo img')
	    .clone()
	    .prependTo('#photo')
	    .css({ 'position': 'absolute' })
	    .animate({ opacity: 0.9 }, 10)
	    .animate({ opacity: 0.4, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight }, 1000, function() {
	        flyFinished = true;
	        $('form .button').val('В корзине!');
	        $('form .button').css({ backgroundColor: '#20cc3d' });
	        if (cartHtml != '') {
	            $('#cart').removeClass('progress');
	            SetCartHtml(cartHtml);
	        }
	        else {
	            $('#cart').addClass('progress');
	        }
	        $(this).remove();
	    });

}