var mouseDown, heartInterval;

var Boxes = function() {
    this.fontSizeType = 'pt';
    this.maxTicketSize = 12.75;
	
    this.flickerTimer = null;
    this.flickerTimer2 = null;
    this.beforeReset = null;
	
    this.velocity = 35;
	
    _this = this;
}

Boxes.prototype = {
    addEvents: function() {
        $('.ticket .mask').bind("mouseenter", function(ev) {
            _this.stopBubble(ev);
            var thisOne = this.parentNode;
	
            $('.ticket').each(function(){
                var thisClass = this.className.split("ticket-")[1] - 1;
                var selectedThisClass = thisOne.className.split("ticket-")[1] - 1;
	
                if (thisClass != selectedThisClass) {
                    _this.animateTicket(this, _this.getTicketsSize()[thisClass].fontSize * 0.8);
                } else {
                    _this.animateTicket(this, _this.maxTicketSize, _this.showHiddenContent);
                }
            });
        }, false);
	
        $('.ticket .mask').bind("mouseleave", _this.resetSizes, false);
    },
	
    animateTicket: function(element, fontSize, callback){
        $(element).animate({
            fontSize:fontSize + _this.fontSizeType
        }, {
            duration:500,
            queue:false,
            complete: function() {
                if (callback) {
                    callback(element);
                }
            }
        });
    },

    clearTimers: function(){
        clearTimeout(_this.beforeReset);
        clearTimeout(_this.flickerTimer);
        clearTimeout(_this.flickerTimer2);
    },
	
    colorHandler: {
        changeColors: function(color1, color2) {
		
            _this.colorHandler.changeSwfColors(color1, color2);

            $("#bColor1").val(color1);
            $("#bColor2").val(color2);
			
            _this.heart.getHeartPosition();
			
            var css = '.tColor1 {color:' + color1 + ' !important;}' +
            '.bColor1 {background:' + color1 + ' !important;}' +
            '.tColor2 {color:' + color2 + ' !important;}' +
            '.bColor2 {background:' + color2 + ' !important;}';
		
            if (!$.browser.msie) {
                $("#templateColors").html(css);
            } else {
                $("#templateColors").remove();
                $("head").append('<style type="text/css" id="templateColors">' + css + '</style>');
            }
        },
		
        changeColorsHandler: function(event) {
			
            _this.showBoxes();
			
            var hPalleteLength = _this.colorHandler.getHorizontalPallet.length - 1;
            var vPalleteLength = _this.colorHandler.getVerticalPallet.length - 1;
			
            var x = parseInt(event.clientX * hPalleteLength / $("#general").width());
            var y = parseInt(event.clientY * vPalleteLength / $("#general").height());
			
            if (x > hPalleteLength)
                x = hPalleteLength;
			
            if(y > vPalleteLength)
                y = vPalleteLength;
			
            if (x < 0)
                x = 0;
			
            if (y < 0)
                y = 0;

            if (_this.colorHandler.getHorizontalPallet[x] == _this.colorHandler.getVerticalPallet[y])
                y = y - 1;

            _this.colorHandler.changeColors(_this.colorHandler.getHorizontalPallet[x], _this.colorHandler.getVerticalPallet[y]);
        },
		
        changeSwfColors: function(color1, color2) {
            if (cookiesLogo) {
                if ($("#heart-label").html())
                    cookiesLogo.changeColor(color2);
                else
                    cookiesLogo.changeColor(color1);
            }
			
            for(obj in swfObjects) {
                if (typeof(swfObjects[obj].obj.changeColors) != "undefined")
                    swfObjects[obj].obj.changeColors(color1, color2);
            }
        },
		
        getHorizontalPallet: [ "#FFFFFF", "#AFFFFF", "#00FFFF", "#00C2FF",
        "#0080FF", "#0F3FFF", "#2D00FF", "#2D00FF", "#4100FF", "#6B00FF",
        "#9F00FF", "#E000FF", "#FF00FF", "#FF00C5", "#FF0088", "#FF004D",
        "#FF0000", "#FF4200", "#FF8200", "#FFC400", "#F9FF00", "#FBFF7A",
        "#FDFFBB", "#FFFFFF", "#C1C1C1", "#878787", "#535353", "#000000",
        "#002900", "#009100", "#00FF00", "#4BFF00", "#A7FF00", "#F9FF00",
        "#FFC400", "#FF8200", "#FF4200", "#FF0000", "#FF004F", "#FF0088"],
		
        getVerticalPallet: [ "#9F00FF", "#BF00FF", "#E000FF", "#EF00FF",
        "#FF00FF", "#FF38FF", "#FF70FF", "#FF93FF", "#FFB7FF", "#FFDBFF",
        "#FFFFFF", "#E0E0E0", "#C1C1C1", "#A6A6A6", "#878787", "#6D6D6D",
        "#535353", "#2A2A2A", "#000000", "#030014", "#070028", "#0A0C5A",
        "#0D198D", "#1D0DC6", "#2D00FF", "#1E1FFF", "#0F3FFF", "#085FFF",
        "#0080FF", "#00A1FF", "#00C2FF", "#00E0FF", "#00FFFF", "#00FFDF",
        "#00FFBF", "#00FF60", "#D2FF00" ]
    },
	
    flickContent: function(element){
        $(element).not('.spacer').find('.ticket-home-content-over').hide();

        clearTimeout(_this.flickerTimer2);

        _this.flickerTimer2 = setTimeout(function() {
            $(elelement).not('.spacer').find('.ticket-home-content-over').show()
        }, 50);
    },
	
    getTicketsSize: function() {
        return [
        {
            width:213,
            height:266,
            fontSize:12
        },

        {
            width:159,
            height:199,
            fontSize:9
        },

        {
            width:119,
            height:149,
            fontSize:6.75
        },

        {
            width:89,
            height:112,
            fontSize:4.5
        },

        {
            width:67,
            height:84,
            fontSize:3.75
        },

        {
            width:50,
            height:63,
            fontSize:2.85
        },

        {
            width:37,
            height:47,
            fontSize:3.3
        }
        ];
    },
	
    heart: {
        area: '#pulsate',
        element: '#heart',
        pulsate: null,
        stopPulse: false,

        animate: function() {
            $(_this.heart.area).show();
			
            var heart = $(_this.heart.element);
            _this.heart.pulsate = setInterval(function() {
                $(heart).fadeIn(650, function() {
                    _this.heart.animationHandler()
                });
            }, 2000);
			
            $(_this.heart.element).bind("mouseenter", _this.heart.showLabel);
            $(_this.heart.element).bind("mouseleave", _this.heart.handlePulsation);
            $(_this.heart.element).bind("drag", _this.heart.hideLabel);
        },
		
        animationHandler: function() {
            if (_this.heart.stopPulse)
                clearInterval(_this.heart.pulsate);
            else
                $('#heart').fadeOut(650);
        },
		
        changeHearthColor: function(matches) {
            if (matches)
                $("#heart").attr("class", "tColor1");
            else
                $("#heart").attr("class", "tColor2");
        },
		
        getHeartPosition: function(selector) {
            var match = false;
            var tickets;
			
            var heart = $("#heart:visible");
			
            if (heart) {
                var position = heart.offset();
				
                tickets = $(".all .box");
				
                if (tickets.length < 1)
                    tickets = $('.bColor2');
				
                for (var i=0; i < tickets.length; i++) {
                    if ($(tickets[i]).parent().hasClass("hidden"))
                        tickets.splice(i, 1);
                }
				
                tickets.each(function() {
                    var ticketPosition = $(this).offset();
                    var ticketSize = {
                        "height": $(this).height(),
                        "width": $(this).width()
                    };
                    var ticketArea = {
                        "x": (ticketPosition.left + ticketSize.width),
                        "y": (ticketPosition.top + ticketSize.height)
                    }
					
                    if (((ticketPosition.top < position.top) && (position.top < ticketArea.y)) && ((ticketPosition.left < position.left) && (position.left < ticketArea.x)))
                        match = true;
                });
				
                if (match)
                    _this.heart.changeHearthColor(true);
                else
                    _this.heart.changeHearthColor(false);
            }
        },

        handlePulsation: function() {
            if (_this.heart.stopPulse) {
                _this.heart.stopPulse = false;
                _this.heart.animate();
            }
            else {
                _this.heart.stopPulse = true;
            }
        },
		
        heartAnalyzer: function() {
            if (!mouseDown)
                heartInterval = setInterval("var boxes = new Boxes(); boxes.heart.getHeartPosition()", 2000);
            else
                clearTimeout(heartInterval)
        },
		
        hideLabel: function() {
            $('#heart-label').hide();
        },
		
        saveColor: function(url) {
            $.ajax({
                type: "POST",
                url: url,
                data: {
                    "bColor1": $("#bColor1").val(),
                    "bColor2": $("#bColor2").val()
                },
                beforeSend: function() {
                    _this.heart.savingColorPosition()
                },
                success: function() {
                    /*$("#saving-color").fadeOut();*/
                    $("#saving-color-screenlock").hide();
                    _this.heart.stopPulse = false;
                    _this.heart.animate();
                },
                error: function() {
                    alert('error on save colors'); $("#saving-color-screenlock").hide();/*$("#saving-color").fadeOut();*/
                }
            });
        },
		
        savingColorPosition: function() {
            _this.heart.showScreenLock();
        /*
                        var targetEl = $("#saving-color");
                        targetEl.show();
                        
			var bodyEl = $("body"); 
				
                         targetEl.css({
				"left": (bodyEl.width() / 2) - (targetEl.width() / 2),
				"top": (bodyEl.height() / 2) - (targetEl.height() / 2)
			});
                        */
        },

        showLabel: function() {
            $('#heart-label').show();
            _this.heart.handlePulsation();
        },
		
        showScreenLock: function() {
            var doc = $(document);
            var targetSL = $("#saving-color-screenlock");
			
            targetSL.css({
                "height": doc.height(),
                "width": doc.width()
            });
			
            targetSL.show();
        }
    },

    /**
         * TODO fix movement
         */
    moveAll: function(){
        var currentPosition = $('.all').offset();
        var currentMiddle = {
            top: (currentPosition.top + ($('.all').height() / 2)),
            left: (currentPosition.left + ($('.all').width() / 2))
        };

        var left = intVal(Math.random() * ($(document).width() - $('.all').width() - 5));
        var top = intVal(Math.random() * ($(document).height() - $('.all').height() - 5));

        var distance = intVal(Math.sqrt(Math.pow((left - currentMiddle.left), 2) + Math.pow((top - currentMiddle.top), 2)));
        var duration = intVal((distance / _this.velocity) * 1000);
		
        $(".all").animate({
            top: top,
            left: left
        }, duration, _this.moveAll);
    },
	
    resetSizes: function(){
        _this.clearTimers();
        var ticketsSize = _this.getTicketsSize();
        for (var i = 0; i < ticketsSize.length; i++) {
            _this.animateTicket(".ticket-" + (i + 1), ticketsSize[i].fontSize, _this.showNormalContent);
        }
    },
	
    setGeneralSize: function() {
        if (!$.browser.msie) {
            $("#general").css({
                "width": ($(document).width() - 10),
                "height": ($(document).height() - 10)
            });
        }
    },
	
    setSizes: function() {
        var ticketsSize = _this.getTicketsSize();
        for (var i = 0; i < ticketsSize.length; i++) {
            $(".ticket-" + (i + 1)).css('font-size', ticketsSize[i].fontSize + _this.fontSizeType);
        }
    },
	
    showBoxes: function() {
        $('.all').show();
        _this.moveAll();
    },
	
    showHiddenContent: function(element){
        $(element).find('.ticket-home-content-over').show();
        $(element).find('.ticket-home-content-normal').hide();

        rc.compareSize();
		
        _this.clearTimers();
    },
	
    showNormalContent: function(element){
        $(element).find('.ticket-home-content-normal').show();
        $(element).find('.ticket-home-content-over').hide();
    },
	
    startFlickerContent: function(element){
        var nextFlickerTimer = Math.random() * 600;

        _this.flickContent(element);
        _this.flickerTimer = setTimeout(startFlickerContent, nextFlickerTimer, el);
    },

    /**
         * TODO verify active area for all browsers
         */
    stopAll: function(ev) {
        $(ev.currentTarget).stop(true);
    },

    stopBubble: function(e) {
        if (e && e.stopPropagation) {
            e.stopPropagation();
        }
        else {
            window.event.cancelBubble = true;
        }
    }
}

function intVal(value) {
    return parseInt(value, 10);
}