/**
 * @author brain2xml
 */
//var timewait = 3000; 
//var timechange = 100; 
var rotatorIndex;
var rotatorItemsCount;

function theRotator() {
	// Устанавливаем прозрачность всех картинок в 0
	$('div#rotator ul#rotator-images li').css({opacity: 0.0});

	// Берем первую картинку и показываем ее (по пути включаем полную видимость)
	$('div#rotator ul#rotator-images li:first').css({opacity: 1.0});

	// Вызываем функцию rotate для запуска слайдшоу, 5000 = смена картинок происходит раз в 5 секунд
	setInterval('rotate()',5000);

    rotatorItemsCount = $('div#rotator ul#rotator-images li').length + 1;

    $('#rotator-texts ul').css('width',rotatorItemsCount*595+'px');
    rotatorIndex = rotatorItemsCount-1;
    $('#rotator-texts ul').css('margin-left',-rotatorIndex * 595+'px');
}

function rotate() {
	// Берем первую картинку
	var current = ($('div#rotator ul#rotator-images li.show')?  $('div#rotator ul#rotator-images li.show') : $('div#rotator ul#rotator-images li:first'));

	// Берем следующую картинку, когда дойдем до последней начинаем с начала
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul#rotator-images li:first') :current.next()) : $('div#rotator ul#rotator-images li:first'));

	// Расскомментируйте, чтобы показвать картинки в случайном порядке
	// var sibs = current.siblings();
	// var rndNum = Math.floor(Math.random() * sibs.length );
	// var next = $( sibs[ rndNum ] );

	// Подключаем эффект растворения/затухания для показа картинок, css-класс show имеет больший z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1600);

	// Прячем текущую картинку
	current.animate({opacity: 0.0}, 1600)
	.removeClass('show');


     rotatorIndex--;


                            $('#rotator-texts ul').css('opacity',1).animate(
                                        { marginLeft:  -(rotatorIndex + 1)  * 595 + 275, opacity:0 }, //,
                                        300,
                                        "linear",
                                        function() { // alert('1');

                                            $('#rotator-texts ul').css('opacity',0).animate(
                                                    { marginLeft:  -rotatorIndex  * 595, opacity:1 }, //,
                                                    400,
                                                    "linear",

                                                    function() {
                                                        if (rotatorIndex == 0) {
                                                            rotatorIndex = rotatorItemsCount - 1;
                                                            $('#rotator-texts ul').css('margin-left',-rotatorIndex * 595+'px');
                                                        }
                                                    })

                                        }
                            );//.css('opacity', 1);

};

$(document).ready(function() {
	// Запускаем слайдшоу
	theRotator();
});

/*
$(document).ready(function(){

    $('#picture3, #l_1, #l_2, #l_3, #l_4, #l_5').pngFix();
    needtostart = true;
    sl_length = $('#slide_show div').length;
    step = sl_length;
	if(sl_length > 1){
    	to_init($('#slide_show'));
    	timeout = setTimeout(function(){
        	to_play($('#slide_show'))
    	}, timewait);
	}
    function to_init(div){
        div.find("div:not(:last)").css({
            zIndex: 0
        });
        $('#controls a').click(function(){
            a = $(this).attr('id').substr(2);
            if (step != a) {
                step = a;
                clearTimeout(timeout);
                to_play(div, a);
            }
			return false;
        });
        
    }

    function to_play(div, a){
		
        if (a > 0) {
            current = prev;
            prev = div.find("div:nth-child(" + a + ")");
			step = a;
        }
        else {
            current = div.find("div:nth-child(" + step + ")");
            if (step == 1) {
                prev = div.find("div:last");
            }
            else {
                prev = current.prev();
            }
			
            step--;
        }
        prev.css({
            zIndex: 0,
            opacity: 1
        });
        current.animate({
            opacity: 0
        }, timechange, function(){
            current.css({
                zIndex: 0
            });
            prev.css({
                zIndex: 10
            });
			var on = $("#controls td:nth-child(" + step + ") img")[0];
			switch(step){
				case 1: $(on).attr("src", "/themes/miro/i2/on_01.png");
				break;
				case 2: $(on).attr("src", "/themes/miro/i2/on_02.png");
				break;
				case 3: $(on).attr("src", "/themes/miro/i2/on_03.png"); 
				break;
				case 4: $(on).attr("src", "/themes/miro/i2/on_04.png");
				break;
				case 5: $(on).attr("src", "/themes/miro/i2/on_05.png");
				break;
			}
			$('#slide_links :nth-child(' + step + ')').show();
			
			
        });
        if (step == 0) {
            step = sl_length;
        }
	$('.picture_link').each(function(){
	    $(this).hide();
	});		
	
	$("#controls td img").each(function(i){
			i++;
			switch(i){
				case 1: $(this).attr("src", "/themes/miro/i2/off_01.png");
				break;
				case 2: $(this).attr("src", "/themes/miro/i2/off_02.png");
				break;
				case 3: $(this).attr("src", "/themes/miro/i2/off_03.png");
				break;
				case 4: $(this).attr("src", "/themes/miro/i2/off_04.png");
				break;
				case 5: $(this).attr("src", "/themes/miro/i2/off_05.png");
				break;
			}	
		});
        timeout = setTimeout(function(){
            to_play(div)
        }, timewait);
    }
});
*/



window.fbAsyncInit = function() {



 $().ready(function(){



    FB.init({
        appId   : 175990635802032,
        //session : 18944, // don't refetch the session when PHP already has it
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
});

 //alert('ok')
// whenever the user logs in, we refresh the page
 FB.Event.subscribe('auth.login', function() {
 //initFbloginForm();
 window.location.reload();
 });     

 $('#facebook-login-handler').click(
         function(){
             FB.getLoginStatus(function(response) {
                 fblogin();
                 /*if (response.session && response.status=='connected') {
                  initFbloginForm();
                  } else {
                  fblogin();
                  }*/
             });
         }

 );
 });

 };




 function initFbloginForm(){        
 if($('#loginForm').length==0){
     var $form=$("<form method='post'  action='/login' name='loginForm' id='loginForm'/>");
     $form.append(" <input  type='hidden' name='username' id='login_field' value=''/>");
     $("body").append($form);

 }
 $('#login_field').get(0).value="Facebook";
 $('#loginForm').get(0).submit();
 }
 function fblogin(){
 FB.login(function(response) {
             if (response.session) {
                 //alert('logged in');
                 //initFbloginForm();
             } else {
                 // user cancelled login
                 // what he doing???
             }
     //});
     }, {perms:'email'});
 }

