﻿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' };
var discount = 0;
var colors = ["ffcc33", "e5387a", "0099cc", "669933", "999900", "6666ff"];

function contains(ar, el) {
    for (var i = 0; i < ar.length; i++) {
        if (ar[i] == el) {
            return true;
        }
    }

    return false;
}

$(document).ready(function() {
    //Меняем цвет у трафаретов
    var usedColors = [];
    $(".trafarets li").each(function() {
        var index = parseInt(Math.random() * (colors.length - 1));

        while (contains(usedColors, index)) {
            index = parseInt(Math.random() * (colors.length - 1));
        }

        $('a', $(this)).each(function() {
            $(this).attr('href', $(this).attr('href') + '?bgcolor=' + colors[index]);
        });

        $('img', this).css('background-color', "#" + colors[index]);

        usedColors.push(index);

        if (usedColors.length == 4) {
            usedColors = [usedColors[1], usedColors[2], usedColors[3]];
        }
    });

    //загружаем 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 ul.thumb img").attr('src');
        var targetSrc = $("#photo a").attr('href');
        $("#photo a").click(function() { return false; });

        var defaultImageHeight = $("#photo ul.thumb img").get(0).height;
        var defaultImageWidth = $("#photo ul.thumb img").get(0).width;

        $("#photo ul.thumb li").css({ width: defaultImageWidth + 'px', height: defaultImageHeight + 'px' });
        $("#photo ul.thumb img").css({ position: 'absolute', top: '0px', left: '0px', width: defaultImageWidth + 'px', height: defaultImageHeight + 'px' });

        $("#photo ul.thumb li").hover(Zoom, 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);

            $("#photo #zoomin").hover(Zoom);
        });

        function Zoom() {
            var $this = $("#photo ul.thumb li");
            $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: '-50px', /* The next 4 lines will vertically align this image */
		    marginLeft: '-85px',
		    top: '50%',
		    left: '50%',
		    width: objImagePreloader.width + 'px', /* Set new width */
		    height: objImagePreloader.height + 'px'/*,  Set new height */
		}, 600);
        }


        objImagePreloader.onload = function() { };
    };
    if ($("#photo a").size() > 0) {
        $("#photo a").removeAttr('title');
        objImagePreloader.src = $("#photo a").attr('href');
    }

    CalculateTotal();




    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);

        //discount
        price -= discount * 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 AddToCart(form) {
        var productX = $('#photo ul.thumb li').offset().left;
        var productY = $('#photo ul.thumb li').offset().top;


        var basketX = $('#cart-ph').offset().left;
        var basketY = $('#cart-ph').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(),
                itemPrice: $('[name=size]:checked').attr('price'),
                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(),
                bgcolor: $('#bgcolor').val(),
                quantity: $('[name=quantity]').val()
            },
            function(html) {
                cartHtml = html;
                if (flyFinished) {
                    $('#cart').removeClass('progress');
                    SetCartHtml(html);
                }
                pageTracker._trackPageview("/Cart/Add");


            }, 'html');

        $('#photo ul.thumb li 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: '#66CC00' });
	        if (cartHtml != '') {
	            $('#cart').removeClass('progress');
	            SetCartHtml(cartHtml);
	        }
	        else {
	            $('#cart').addClass('progress');
	        }
	        $(this).remove();
	    });

    }

});

//Функции обновления цвета фона и наклейки
function update_content(color, name) {
    $('#color').val(name.replace(/color /, ''));
    $('#color_code').val(color);
}
function update_back(color) {
    //someday maybe
}