var bigRandom = false;

(function ($) {

    $.fn.horizontFlip = function (item1, speed, funct_name) {
        if (typeof speed == 'undefined') {
            speed = 300;
        }
        var el = $(this);
        _testGo(item1, speed, funct_name);

        // Смена картинки в середине кручения
        function _flip(speed, funct_name) {
            setTimeout(function(){
                if(el.hasClass('back')){
                    el.attr('src', el.attr('name'));
                    el.removeClass('back');
                } else {
                    el.attr('src', '/images/back.png');
                    el.addClass('back');
                }
            },speed);
            el.animate({"width": "toggle", "height": el.height()}, speed);
            if (funct_name != null) setTimeout(funct_name, speed * 2);
        }

        // Анимация кручения
        function _showFront(speed, funct_name) {
            el.animate({"width": "toggle", "height": el.height()}, speed,_flip(speed, funct_name));
        }

        // Основной обработчик кручения
        function _testGo(x, speed, funct_name) {

           // Если фишка лежала обратной стороной, прячем надпись, убиваем лишнии события
           if(el.hasClass('back')) {

                // alert(2);
              el.parent().find(".flipbox_text").hide();
              el.parent().unbind('mouseleave');
              set_event(el);
           }

            // Крутим фишку
            _showFront(speed, funct_name);

            // Если крутить надо несколько раз, ставим таймер на повтор
            x--;
            if(x > 0) setTimeout(function(){ _testGo(x,speed);},speed*2);

            // Если это последнее кручение, обрабатываем соответствующие события
            if (x == 0) setTimeout(function(){
                if(el.hasClass('back')) {
                    var mdiv = el.parent();
                   //  alert(2);
                    mdiv.find(".flipbox_text").css("display", "table-cell");

                }
            },speed*2);
        }

    }

})(jQuery);


// Переворачивание фишки по клику
function set_event(elem) {

    $(elem).bind('click',function(){

        var el = $(this);
        el.unbind('click');
        el.parent().bind('mouseleave',function(){
              setTimeout(function(){ el.horizontFlip(1, 200); }, 400);
              return false;
        });

        $(this).horizontFlip(1, 200);
    });
}

$(document).ready(function(){

    set_event(".flipbox > img");

	$(".random2").mousemove( function(){
		 $("#random2, #random3").css('color', '#f02794');
		 $("#random2, #random3").css('borderBottom', '1px  dashed #f02794');
	}).mouseout(function() {  
		$("#random2, #random3").css('color', '#dc3040');
		 $("#random2, #random3").css('borderBottom', '1px  dashed #dc3040'); 
	});

    // Нажали на рычаг, прокручивание фишек
    $("#random, #random2, #random3").bind('click', function(){
      if (!bigRandom) {

          // Играем с картинкой рычага
          $('#random').attr('src', '/images/ruka.gif');
          setTimeout(function(){ $('#random').attr('src', '/images/ruka.png'); },1000);
          bigRandom = true;

          // Переворачиваем все не перевернутые фишки и запускаем скролер
          $(".back").horizontFlip(1, 200, function() {
             $(".flipcontainer").load("/collection/get_fishki", function() {
                  // Запуск крутилок
                  $("#lenta1").animate({"top": 0}, 1000);
                  $("#lenta2").animate({"top": 0}, 2000);
                  $("#lenta3").animate({"top": 0}, 3000, function(){
                      // Переворачивание выйгрышных фишек, если есть...
                      if ($("#ids").val() != '')
                        $($("#ids").val()).horizontFlip(4, 300, function(){
									setTimeout("congratul()",2000);
                        });

                      // Ставим события для остальных фишек - переворачивание по клику
                      set_event(".flipbox > img");
                      bigRandom = false;
                  });
              });
           });
      }
    });

});




function myOnComplete()
{
  //  alert("The form validates! (normally, it would submit the form here).");
   // return false;
}
  
$(function () {
			
			
	$("#close_happy, #TB_sloi").click(function() {
		$(".congratulation").animate({opacity: "hide"}, "slow", function(){	 $(".congratulation").hide();	 });
		$("#TB_sloi").animate({opacity: "hide"}, "slow", function(){	 $("#TB_sloi").hide();	 });
		e=0;
	});
	 
	  
	 $(".enter_form").mousedown(function() {
		$(".enter_form").css('backgroundPosition','0px -150px'  ); 
	}).mouseout(function() { 
		$(".enter_form").css('backgroundPosition','0px -0px'  ); 
	});
	 
	  $(".face").click(function() {
			$(".face_variant").toggle();
	  });						
	 
	 
	  $(".face_var").click(function() {
			$('#faceh').val($(this).attr('lang'));
			$(".hello_dir2").html('<a class="face_var2 fa_'+$(this).attr('id')+'"  ></a>');
			$(".face_variant").toggle();
	  });
    
});


var e=0, er=0;
function setRandomGo() {
		
		if (e==1) {
			
		if (er==0){ 
			er=1;	
			$(".faza").css('backgroundPosition','0px -484px'  ); 
			} else {  
			er=0; 
			$(".faza").css('backgroundPosition','0px 0px'  ); }
			setTimeout("removeRandomGo()", 200);
		}
		
		
}

function removeRandomGo() {	
		if (e==1) setTimeout("setRandomGo()", 200); 
		 
}


function congratul(){
$("#TB_sloi").toggle();
		$(".congratulation").toggle();
		var TB_WIDTH = 509;
		
		$(".congratulation").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
			if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
					//$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
		}		
		 e = 1;
		 setTimeout("setRandomGo()", 200);
		 
	
}

