var currentVideo = 0;
var currentPhoto = 0;
var videos = new Array();
var preloaderState = 0;
var preloaderInterval = null;
var preloaderTimeout = null;

jQuery.preloadImages = function () {
    if (typeof arguments[arguments.length - 1] == 'function') {
        var callback = arguments[arguments.length - 1];
    } else {
        var callback = false;
    }
    if (typeof arguments[0] == 'object') {
        var images = arguments[0];
        var n = images.length;
    } else {
        var images = arguments;
        var n = images.length - 1;
    }
    var not_loaded = n;
    for (var i = 0; i < n; i++) {
        jQuery(new Image()).load(function() {
            if (--not_loaded < 1 && typeof callback == 'function') {
                callback();
            }
        }).attr('src', images[i]);
    }
}

function updateAlbumPhoto(rel) {
    if (preloaderInterval == null) {
        preloaderState = 0;
        preloaderTimeout = setTimeout(function() {
            if (preloaderTimeout != null) {
                var p = $('<div id="album-preloader"><span>Следующий</span></div>');
                p.css('display', 'none');
                $('.about-album-rb').append(p);
                p.fadeIn(300);
                preloaderInterval = setInterval(function(){
                    preloaderState++;
                    if (preloaderState == 4) preloaderState = 0;

                    var preloaderText = 'Следующий';
                    for(var i = 0; i < preloaderState; i++)
                        preloaderText += '.';
                    $('#album-preloader span').text(preloaderText);
                }, 500);
            }
        }, 500);
    }

    $.ajax({
        url: '/' + rel,
        type: "POST",
        dataType: "json",
        success: function (data) {
            if (data != null) {
                var photos = new Array();
                if (data.image1 != '') 
                    photos.push('/' + data.image1);
                if (data.image2 != '') 
                    photos.push('/' + data.image2);

                $.preloadImages(photos, function () {
                    if (data.queryid == currentPhoto) {
                        $('.about-album').append('<div id="about-album-rb-temp1" class="about-album-rb pngfix" style="display:none"></div>');
                        var t1 = $('#about-album-rb-temp1');
                        $('.about-album').append('<div id="about-album-rb-temp2" class="about-album-rb pngfix" style="display:none"></div>');
                        var t2 = $('#about-album-rb-temp2');
                        t1.css('background-image', $('.about-album-rb:eq(0)').css('background-image'));
                        t2.css('background-image', 'url(/' + data.image1 + ')');
                        t1.show();						
                        $('.about-album-rb:eq(0)').css('background-image', 'none');
                        t1.fadeOut(500);
                        t2.fadeIn(500, function() {
                            $('.about-album-rb:eq(0)').css('background-image', 'url(/' + data.image1 + ')');
                            $('.about-album-rb:gt(0)').remove();
                        });
							
                        $('.about-album-photo').fadeOut(240, function() {
                            $(this).css('background-image', 'url(/' + data.image2 + ')').fadeIn(240);
                        });
							
                        $('.about-album-info h3').html(data.title);
                        $('.about-album-info .post').html(data.longtitle);
                        $('.about-album-info .description').html(data.summary);
                        clearInterval(preloaderInterval);
                        clearTimeout(preloaderTimeout);
                        preloaderInterval = null;
                        preloaderTimeout = null;
                        $('#album-preloader').fadeOut(300, function(){
                            $(this).remove();
                        });
                    }
                });
					
            }
        }
    }); 
}

$(document).ready(function() {

    var allowed = ['0','1','2','3','4','5','6','7','8','9','0','-',')','(','+'];
    $('.callback-contols').keyboard({
        over: 'cb-active-btn',
        revert: 'cb-revert',
        allowedArray:allowed
    });
	
    $('.header-callback-text a').click(function() {
        $('.callback').fadeToggle(300);
        return false;
    });
	
	
    $('.callback-close').click(function() {
        $('.callback').fadeOut(300);
    });
	
    $('#searchForm').click(function() {
        if ($('#searchForm input:eq(0)').val() == 'Поиск')
            $('#searchForm input:eq(0)').val('');
    });
	
    $('.search .button').click(function() {
        $('#searchForm').submit();
    });
	
    
    var ua = $.browser;
    if (ua.opera || (ua.msie && ua.version < 8))
        $(window).resize(function(){
            var my = $('.back');
            my.css('min-height',my.height());
            setTimeout(function(){
                my.css('min-height','100%')
                },1);
        });

    $('#scrollable').scrollable({
        horizontal: false,
        size: 3
    });

    if (ua.msie && ua.version < 7) {
        $('.about-securities-list li img').hover(
            function() {
                $(this).css('border', '1px solid #fa4c00');
            },
            function() {
                $(this).css('border', '1px solid #5d6d73');
            }
            );
    }
    
    if (ua.mozilla) {
        $('#searchForm input').css({
            'padding-top': 0,
            'height': '19px'
        });
    }

    $('.about-album-side .items li a').bind('click', function() {
        if ($(this).parent().hasClass('active'))
            return;

        if ($('.about-album-rb').length > 1) 
            return false;
			
        currentPhoto++;
        updateAlbumPhoto($(this).attr('rel') + '?queryid='+currentPhoto);
        $('.about-album-photo').removeAttr('rel');
    });
	
    $('.about-album-photo').bind('click', function() {
        if ($('.about-album-rb').length > 1) 
            return false;
			
        var rel = $('.about-album-side .items .active a').attr('rel');
        var params = {
            "queryid":++currentPhoto
            };
        var t = $(this).attr('rel');
        if (t != undefined) {
            $(this).removeAttr('rel');
        }
        else {
            params.type = 1;
            $(this).attr('rel', '1');
        }
        rel += '?' + $.param(params);
        updateAlbumPhoto(rel);
    });

    /*lightbox*/
    $('a.loadimglink').live("click", function(){
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: $(this).attr('href'),
            success: function(data){
                $.fancybox(data, {
                    'padding'           : 0,
                    'transitionIn'      : 'none',
                    'transitionOut'     : 'none',
                    'type'              : 'image',
                    'changeFade'        : true,
                    'showCloseButton'	: true,
                    'titlePosition'     : 'inside',
                    'titleFormat'		: formatTitle,
                    'showNavArrows'     : true
                });
            },
            error: function(){
                alert('Отладочная информация : Для данной страницы нет изображений:(');
            }
            
        });
        
        return false;
       
    });
    $('a.loadimggallery').live("click", function(){ 
        var hrefs = new Array();
        $('a[rel=' + $(this).attr('rel') + ']').each(function(el, ob){
            /*console.log(el);*/
            //              console.log($(ob).attr('href'));
            hrefs.push($(ob).attr('href'));
        });
        //console.log(hrefs);
        $.fancybox(hrefs,{
            'index'             : hrefs.indexOf($(this).attr('href')),
            'padding'           : 0,
            'transitionIn'      : 'none',
            'transitionOut'     : 'none',
            'type'              : 'image',
            'changeFade'        : true,
            'showCloseButton'	: true,
            'titlePosition'     : 'inside',
            'titleFormat'		: formatTitle,
            'showNavArrows'     : true
        });
        return false;
       
    });
    $('a.loadimgpreview').click(function(){
        $.fancybox($(this).attr('href'), {
            'padding'           : 0,
            'transitionIn'      : 'none',
            'transitionOut'     : 'none',
            'type'              : 'image',
            'changeFade'        : true,
            'showCloseButton'	: true,
            'titlePosition'     : false,
            'titleFormat'       : false,
            'showNavArrows'     : false
        });
        return false;
    });
    
    $("a.left_move").live('click', function(){
        $.fancybox.prev();
    });
    $("a.right_move").live('click', function(){
        $.fancybox.next();
    });
    
    /*video*/
    if($('.video-link').length > 0){
        var loaded = false;
        $('a.video-link').click(function(){
            currentVideo = 0;
            videos = $(this).siblings('.video-links').find('a');
            //console.log(videos);
            loaded = false;
            if(videos.length > 0){
                try{
                    if(!loaded){
                        jwplayer('portfmediaspace').setup({
                            'flashplayer': '/assets/templates/fit/mediaplayer/player.swf',
                            'file': videos.first().attr('href'),
                            'controlbar': 'bottom',
                            'width': '426',
                            'height': '393'
                        });
                        loaded = true;
                    }
                    else{
                        videos.first().attr('href');
                    }
                }
                catch(ex){
                    //console.log(ex);
                    alert('Видео не может быть загружено');
                }
                $.fancybox({
                    'href' : '#portfmediaspace'
                },{
                    'scrolling'     : 'no',
                    'titleShow'     : true,
                    'width': '426',
                    'height': '393',
                    'autoDimensions': false,
                    'showCloseButton': true,
                    'titlePosition': 'inside',
                    'titleFormat':  portfFormatTitle,
                    'showNavArrows': true,
                    'onClosed' : function(){
                        /*console.log("close");
                        console.log($('.video-wrap'));*/
                        var div = $('.video-wrap').find('div');
                        //console.log(div);
                        // div.html('');
                        div.attr('id', 'portfmediaspace');
                    }
                });
			  
                /*}
               else{
                   console.log("test");
                   console.log("/" + videos.eq(currentVideo).attr('href'));
                   jwplayer().load({'file': videos.eq(currentVideo).attr('href')});
               }*/
                $("a.video_left_move").live('click', function(){
                    /*console.log(currentVideo);
				   console.log(videos.length);*/
                    if(currentVideo > 0){
                        currentVideo--;
                        jwplayer().load("/" + videos.eq(currentVideo).attr('href'));
                    }
                /*console.log(currentVideo);
				   console.log(videos.length);*/
                });
                $("a.video_right_move").live('click', function(){
                    /*console.log(currentVideo);
				   console.log(videos.length);*/
                    if(currentVideo < (videos.length - 1)){
                        currentVideo++;
                        jwplayer().load("/" + videos.eq(currentVideo).attr('href'));
                    }
                /*console.log(currentVideo);
				   console.log(videos.length);*/
                });
            }
            return false;
        });
    }
    /*end video*/

    /*end lightbox*/

    /*video services*/

    if($('#mediaspace').length > 0){
        jwplayer('mediaspace').setup({
            'flashplayer': '/assets/templates/fit/mediaplayer/player.swf',
            'file': "/" + $('.serv-links').find('a').attr("rel"),
            'controlbar': 'bottom',
            'width': '426',
            'height': '393'
        });

        $('.serv-links').find('a.videolink').click(function(){
            jwplayer().load($(this).attr("rel"));
            var text = $(this).find('img').html() != null ? $(this).find('img').attr('alt') : $(this).html();
            $('.video-description').html(text);
        });

        $('.video-description').html($('.serv-links').find('img:first').attr("alt"));
        jwplayer().load("/" + $('.serv-links').find('a:first').attr("rel"));
    }
    /*end video services*/

    /*image-upload*/
    $('.loadPicturesBtn').click(function(){
        $('.file_upload_form').remove();
        $(this).parent().append('<div class="file_upload_form">  <form method="POST"><input id="file_upload" name="file_upload" type="file" /></form><a href="javascript:void(0)" class="uploadAll">Загрузить файлы</a></div>');
        $('#file_upload').uploadify({
            'uploader'  : '/assets/snippets/evogallery/client-side/uploadify/uploadify.swf',
            'script'    : '/assets/snippets/evogallery/client-side/uploadify/upload.php',
            'cancelImg' : '/assets/snippets/evogallery/client-side/uploadify/cancel.png',
            'folder'    : '/assets/galleries',
            'scriptData': {
                "id" : $(this).attr("rel")
                },
            'auto'      : false,
            'multi'     : true,    
            'sizeLimit'   : 10240000,
            'onComplete'  : function(event, ID, fileObj, response, data) {
                alert('There are ' + data.fileCount + ' files remaining in the queue.');
            }
        });
    });
    $('.uploadAll').live("click",function(){
        $('#file_upload').uploadifyUpload();
        return false;
    });

    /*end image-upload*/

    /*graphics*/
    $('.serv-categories').find('a').click(function(){
        if(!$(this).hasClass('active')){
            var tempthis = $(this);
            var parents = tempthis.parent().parent().parent();
            parents.find('.active').removeClass('active');
            $(this).addClass("active");
            $.ajax({
                url: tempthis.attr('href'),
                type: "GET",
                success: function(data){
                    var temp = parents.parent().find('.serv-links');
                    temp.fadeOut(300, function(){
                        temp.html(data);
                        temp.fadeIn(300);
                    });
                //;
                }
            });
        }
        return false;
    });
    /*end-graphics*/
    $('a.cb-submit').click(function(){
        var rel = $(this).attr('rel');
        var phone = $('#feedbackForm').find('input[name=phone]').val();
        $.ajax({
            type: 'POST',
            url: rel,
            data: "phone=" + phone,
            success: function(data){
        			
            }
        });
        alert("Ваша заяка учтена.");
        $('#feedbackForm').find('input[name=phone]').val('');
        $('.callback-close').click();
        return false;
    });
    $('#feedbackForm').submit(function() {
        $('a.cb-submit').click();
        return false;
    });
    $('a.mtb-submit').click(function(){
        
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: this.getAttribute('rel'),
            data: ({
                submit: true
            }),
            success: function(data){
            	if(data.status){
	                $('.mt-submitted').find('span').html(data.willgo);
	                $('.mt-discarded').find('span').html(data.notgo);
            	}
            },
            error:function(data){
                alert("Для голосования необходима регистрация");
            }
        });
    });
    $('a.mtb-discard').click(function(){
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: this.getAttribute('rel'),
            data: ({
                discard: true
            }),
            success: function(data){
            	if(data.status){
	                $('.mt-submitted').find('span').html(data.willgo);
	                $('.mt-discarded').find('span').html(data.notgo);
            	}
            },
            error:function(data){
                alert("Для голосования необходима регистрация");
            }
        });
    });
    $('#vk_btn').click(function(){
        window.open($(this).attr("href"),
            'displayWindow', 
            'width=700,height=400,left=200,top=100,location=no, directories=no,status=no,toolbar=no,menubar=no');
        return false;
    });
    $('#fb_btn').click(function(){
        window.open($(this).attr("href"),
            'displayWindow', 
            'width=700,height=400,left=200,top=100,location=no, directories=no,status=no,toolbar=no,menubar=no');
        return false;
    });
    $('#tw_btn').click(function(){
        window.open($(this).attr("href"),
            'displayWindow', 
            'width=700,height=400,left=200,top=100,location=no, directories=no,status=no,toolbar=no,menubar=no');
        return false;
    });
    var pageuri = $('#url').attr('href');
/*  VK = {};
    VK.Share = {};
    // ��������� callback �����
    VK.Share.count = function(index, count){
        // ��������� � DOM
    	/*console.log(pageuri);
    	console.log(index, count);
        $('#vk_sharer span').text(count);
    };*/
    
//$.getJSON('http://vkontakte.ru/share.php?act=count&index=1&url=' + pageuri + '&format=json&callback=?');
/*$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + pageuri + '&callback=?', function(data) {
        // ��������� � DOM
    	/*console.log(pageuri);
    	console.log(data);
        $('#tw_sharer span').text(data.count);
    });
    $.getJSON('https://graph.facebook.com/' + pageuri + '&callback=?',function(data) {
		/*console.log(pageuri);
    	console.log("1");
    	console.log(data);
        $('#fb_sharer span').text(data.share);
	});*/
/*  $.ajax({
    	type: 'GET',
    	dataType: 'json',
    	url: 'https://graph.facebook.com/?ids=' + pageuri, 
    	success: 
    });*/
		
/*VK.init({apiId: API_ID, onlyWidgets: true});
  VK.Widgets.Like("vk_like", {type: "full"});*/
});


function portfFormatTitle(title, currentArray, currentIndex, currentOpts) {
    lclass = "video_left_move";
    rclass = "video_right_move";
    //console.log(currentVideo);
    if(currentVideo == (videos.length - 1)){
        rclass += " disabled";
    }
    if(currentVideo == 0){
        lclass += " disabled";
    }
    return '<div id="lightbox-title" style="background-color:white;"><a class="' + lclass +'" href="javascript:void(0);"></a>'
    + title +
    '<a class="' + rclass + '" href="javascript:void(0);"></a></div>';
}
function formatTitle(title, currentArray, currentIndex, currentOpts) {
    lclass = "left_move";
    rclass = "right_move";
    if(currentIndex == (currentArray.length - 1)){
        rclass += " disabled";
    }
    if(currentIndex == 0){
        lclass += " disabled";
    }
    return '<div id="lightbox-title" style="background-color:white;"><a class="' + lclass +'" href="javascript:void(0);"></a>'
    + title +
    '<a class="' + rclass + '" href="javascript:void(0);"></a></div>';
}

  



