$(document).ready(function(){
    //$(document).pngFix();
    
    $('.imgOriginal').lightBox();
    $('.imgGOriginal').lightBox();

    /* height apply */
    var h = 
        parseInt( $('#header').height() ) + 
        parseInt( $('#mainMenuWrap').height() ) + 
        parseInt( $('.layout_header').height() ) +
        parseInt( $('#footer').height() )+
        50;
    var win_height = $(window).height();
    var layout_inner_height = $('.layout_inner').height();
    
    var calc_h = win_height - h;
    if(layout_inner_height < calc_h){
        $('.layout_inner').height(calc_h);
    }
    /* END height apply */
    
    /* pgn */
    if( $('.pgn_app').length ){
        if($('.channel').length){
            //PGNchannel = new _PGNchannel();
        } else {
            initPgn();
            //PGNModifer();
        }
        
    }
    /* END pgn */
    
    /* pgn */
    if( $('.pgn_src').length ){
        if($('.channel').length){
            //PGNchannel = new _PGNchannel();
        } else {
            initPgn2();
            //PGNModifer();
        }
        
    }
    /* END pgn */
    
    txt_timeout = '';
    
    if( $('.navi_biography').length ){
        BiographyNavi = new _BiographyNavi();
    }
    if( $('.navi_glossary').length ){
        GlossaryNavi = new _GlossaryNavi();
    }
    if( $('.navi_history').length ){
        HistoryNavi = new _HistoryNavi();
    }
    if( $('.navi_strategy').length ){
        StrategyNavi = new _StrategyNavi();
    }
    if( $('.navi_p_tournaments').length ){
        TournamentsNavi = new _TournamentsNavi();
    }
    if( $('.p_gallery').length ){
        PGallery = new _PGallery();
    }
    
    
    
    // slideshow with play/pause
    if($('.slides').length){
        var slideShow = $('.playPauseExample').slideShow({
            interval: 8
        });
        // now add logic to play/pause button
        $('.playPauseExample a.togglePlayback, .playPauseExample a.page').click(function() {
            if (slideShow.isPlaying()) {
                $('.playPauseExample a.togglePlayback').html('Play');
            } else {
                $('.playPauseExample a.togglePlayback').html('Stop');
            }
            slideShow.togglePlayback();
            return false;
        });

        var w = 30+$('.slideShow .navigation li').length*16;
        $('.slideShow .navigation').width(w);
        //===
    }
    //AbsAuth = new _AbsPopupAuth();
    errorChecker();
    
    
    
    
   
    
    
    
});

var creatPGNCols56 = function(cm_container){
    console.warn(cm_container.html());
    //not_empty = cm_container.html();
}


var PGNModifer = function(end){

}

var PGNTextareaBottom = function(){

}

var initPgn = function(){

    $.each($('.pgn_app'),function(i,item){
        if( $(item).attr('board_size') ){
            var board_size = $(item).attr('board_size');
        } else {
            var board_size = 29;
        }
        var cont = '<div class="abs_pgn_applet"><div id="'+$(item).attr('match_id')+'-container"></div><div class="pgn_format" id="'+$(item).attr('match_id')+'-moves"></div><div class="clear"></div></div>';
        //console.warn(item);
        $(item).before(cont); 
//        $(item).before('<div id="'+$(item).attr('match_id')+'-moves"></div>'); 
//        $('#'+$(item).attr('match_id')+'-moves').addClass('pgn_format');
        $(item).remove();
        
        var VR = new PgnViewer({ 
            boardName: $(item).attr('match_id'),  
            pgnString: str_replace($(item).attr('pgn'),'@@','"'),
            pieceSet: 'leipzig', 
            
            showCoordinates: true,
            movesFormat: "main_on_own_line",
            autoScrollMoves: true,
            //showBracketsOnVariation: false,
            hideBracketsOnTopLevelVariation: true,
            moveAnimationLength: 0.3,
            newlineForEachMainMove: false, 
            
//            highlightFromTo: true,
//            showCoordinates: true,
//            autoScrollMoves: true,
            //movesFormat: 'main_on_own_line',
            pieceSize: board_size 
          }  
        );  
        //console.warn(PGN_single_game_title);   
        $(item).hide();

        cm_container = $('#'+$(item).attr('match_id')+'-container');
        cm_timer = 0;
        cm_interval = 10;
        cm_timeout = '';
        //if(_timer()){
        //    console.warn(cm_container.html());
        //}
        
    });
}


var initPgn2 = function(){
    $.each($('.pgn_src'),function(i,item){
        $(item).before('<div id="'+$(item).attr('match_id')+'-container"></div>'); 
        $(item).before('<div id="'+$(item).attr('match_id')+'-moves"></div>'); 
        $('#'+$(item).attr('match_id')+'-moves').addClass('pgn_format');
        new PgnViewer({ 
            boardName: $(item).attr('match_id'),  
            pgnString: $(item).html(),
            pieceSet: 'leipzig', 
            showCoordinates: true,
            movesFormat: "main_on_own_line",
            autoScrollMoves: true,
            //showBracketsOnVariation: false,
            hideBracketsOnTopLevelVariation: true,
            moveAnimationLength: 0.3,
            newlineForEachMainMove: false,
            //movesFormat: 'main_on_own_line',
            pieceSize: 29  
          }  
        );  

        $(item).hide();

        cm_container = $('#'+$(item).attr('match_id')+'-container');
        cm_timer = 0;
        cm_interval = 10;
        cm_timeout = '';
        //if(_timer()){
        //    console.warn(cm_container.html());
        //}
        
    });
}

function _BiographyNavi() {
    
    var obj;
    var alert_text;
    var init = function(){ 
        obj = $('.navi_biography');
        alert_text = obj.find('.alpha_navi_alert').html();
        
        obj.find('.type_item').click(function(){
            if( $(this).hasClass('type_selected') ){
                $(this).removeClass('type_selected');
            } else {
                obj.find('.type_item').removeClass('type_selected');
                $(this).addClass('type_selected');
            }
            setCondition();
            return false;
        });
        
        obj.find('.select_all_categories').click(function(){
            obj.find('.type_item').addClass('type_selected');
            setCondition();
            return false;
        });
        
        obj.find('.deselect_all_categories').click(function(){
            obj.find('.type_item').removeClass('type_selected');
            setCondition();
            return false;
        });
        
        obj.find('.letter_active').live('click',function(){
            if( $(this).hasClass('letter_selected') ){
                $(this).removeClass('letter_selected');
            } else {
                obj.find('.letter_active').removeClass('letter_selected');
                $(this).addClass('letter_selected');
            }
            setCondition();
            return false;
        });
        
        obj.find('.search_by_letter_and_type').live('click',function(){
            var search_arr = new Array;
            if( obj.find('.type_selected').length ){
                search_arr.push('categories-'+obj.find('.type_selected').attr('type_id'));
            }
            if( obj.find('.letter_selected').length ){
                search_arr.push('alphabetic-'+obj.find('.letter_selected').html());
            }
            if(search_arr.length > 0){
                var link = '/biography/list-'+search_arr.join('-')+'.html';
                document.location.href = link;
            }
            return false;
        });
        
        obj.find('.search_by_type').live('click',function(){
            if( obj.find('.type_selected').length ){
                var link = '/biography/list-categories-'+obj.find('.type_selected').attr('type_id')+'.html';
                document.location.href = link;
            }
            return false;
        });
        
        obj.find('.search_by_letter').live('click',function(){
            if( $('.letter_selected').length ){
                var link = '/biography/list-alphabetic-'+obj.find('.letter_selected').html()+'.html';
                document.location.href = link;
            }
            return false;
        });
        
        setCondition();
    }
    
    var setCondition = function(){

        obj.find('.alpha_tb td').removeClass('letter_active');
        if(obj.find('.type_selected').length){
            var arr = BNavi[obj.find('.type_selected').attr('type_id')];
            $.each(obj.find('.alpha_tb td'),function(j,jtem){
                //console.warn($(jtem).html());
                if( in_array( $(jtem).html(),arr ) ){
                    //console.info('in_array');
                    $(jtem).addClass('letter_active');
                }
            });
        } else {
            $.each( obj.find('.type_item'), function(i,item){
                var arr = BNavi[$(item).attr('type_id')];
                $.each(obj.find('.alpha_tb td'),function(j,jtem){
                    //console.warn($(jtem).html());
                    if( in_array( $(jtem).html(),arr ) ){
                        //console.info('in_array');
                        $(jtem).addClass('letter_active');
                    }
                });
            });
        }
        $.each( obj.find('.alpha_tb td'), function(i,item){
            if( !$(item).hasClass('letter_active') ){
                $(item).removeClass('letter_selected');
            }
        });
        
        if( obj.find('.type_selected').length ){
            obj.find('.type_navi_alert').html('<a class="search_by_type" href="#">Search by Category</a>');
        } else {
            obj.find('.type_navi_alert').html('Choose category');
        }
        if( obj.find('.letter_selected').length ){
            if( obj.find('.type_selected').length ){
                obj.find('.alpha_navi_alert').html('<a class="search_by_letter_and_type" href="#">Search by Letter and Category</a>');
            } else {
                obj.find('.alpha_navi_alert').html('<a class="search_by_letter" href="#">Search by Letter</a>');
            }   
        } else {
            obj.find('.alpha_navi_alert').html('Choose Letter');
        }
    }
    
    init();
} 


function _GlossaryNavi() {
    var init = function(){ 
        $('.navi_glossary .letter_active').live('click',function(){
            if( !$(this).hasClass('letter_selected') ){
                $('.navi_glossary .letter_active').removeClass('letter_selected');
                $(this).addClass('letter_selected');
            } 
            return false;
        });
        $('.search_glossary_by_letter').live('click',function(){
            if( $('.navi_glossary .letter_selected').length ){
                var link = '/glossary/letter-'+$('.navi_glossary .letter_selected').attr('letter_id')+'-'+$('.navi_glossary .letter_selected').html()+'.html';
                document.location.href = link;
            }
            return false;
        });
    }
    init();
}

function _HistoryNavi() {
    var init = function(){ 
        $('.navi_history .letter_active').live('click',function(){
            if( !$(this).hasClass('letter_selected') ){
                $('.navi_history .letter_active').removeClass('letter_selected');
                $(this).addClass('letter_selected');
            } 
            return false;
        });
        $('.search_glossary_by_letter').live('click',function(){
            if( $('.navi_history .letter_selected').length ){
                var link = '/history/letter-'+$('.navi_history .letter_selected').attr('letter_id')+'-'+$('.navi_history .letter_selected').html()+'.html';
                document.location.href = link;
            }
            return false;
        });
    }
    init();
}


function _StrategyNavi() {
    
    var obj;
    var alert_text;
    var init = function(){ 
        obj = $('.navi_strategy');
        alert_text = obj.find('.alpha_navi_alert').html();
        
        obj.find('.type_item').click(function(){
            if( $(this).hasClass('type_selected') ){
                $(this).removeClass('type_selected');
            } else {
                obj.find('.type_item').removeClass('type_selected');
                $(this).addClass('type_selected');
            }
            setCondition();
            return false;
        });
        
        obj.find('.select_all_categories').click(function(){
            obj.find('.type_item').addClass('type_selected');
            setCondition();
            return false;
        });
        
        obj.find('.deselect_all_categories').click(function(){
            obj.find('.type_item').removeClass('type_selected');
            setCondition();
            return false;
        });
        
        obj.find('.letter_active').live('click',function(){
            if( $(this).hasClass('letter_selected') ){
                $(this).removeClass('letter_selected');
            } else {
                obj.find('.letter_active').removeClass('letter_selected');
                $(this).addClass('letter_selected');
            }
            setCondition();
            return false;
        });
        
        obj.find('.search_by_letter_and_type').live('click',function(){
            var search_arr = new Array;
            if( obj.find('.type_selected').length ){
                search_arr.push('categories-'+obj.find('.type_selected').attr('type_id'));
            }
            if( obj.find('.letter_selected').length ){
                search_arr.push('alphabetic-'+obj.find('.letter_selected').html());
            }
            if(search_arr.length > 0){
                var link = '/strategy/list-'+search_arr.join('-')+'.html';
                document.location.href = link;
            }
            return false;
        });
        
        obj.find('.search_by_type').live('click',function(){
            if( obj.find('.type_selected').length ){
                var link = '/strategy/list-categories-'+obj.find('.type_selected').attr('type_id')+'.html';
                document.location.href = link;
            }
            return false;
        });
        
        obj.find('.search_by_letter').live('click',function(){
            if( $('.letter_selected').length ){
                var link = '/strategy/list-alphabetic-'+obj.find('.letter_selected').html()+'.html';
                document.location.href = link;
            }
            return false;
        });
        
        setCondition();
    }
    
    var setCondition = function(){

        obj.find('.alpha_tb td').removeClass('letter_active');
        if(obj.find('.type_selected').length){
            var arr = BNavi[obj.find('.type_selected').attr('type_id')];
            $.each(obj.find('.alpha_tb td'),function(j,jtem){
                //console.warn($(jtem).html());
                if( in_array( $(jtem).html(),arr ) ){
                    //console.info('in_array');
                    $(jtem).addClass('letter_active');
                }
            });
        } else {
            $.each( obj.find('.type_item'), function(i,item){
                var arr = BNavi[$(item).attr('type_id')];
                $.each(obj.find('.alpha_tb td'),function(j,jtem){
                    //console.warn($(jtem).html());
                    if( in_array( $(jtem).html(),arr ) ){
                        //console.info('in_array');
                        $(jtem).addClass('letter_active');
                    }
                });
            });
        }
        $.each( obj.find('.alpha_tb td'), function(i,item){
            if( !$(item).hasClass('letter_active') ){
                $(item).removeClass('letter_selected');
            }
        });
        
        if( obj.find('.type_selected').length ){
            obj.find('.type_navi_alert').html('<a class="search_by_type" href="#">Search by Category</a>');
        } else {
            obj.find('.type_navi_alert').html('Choose category');
        }
        if( obj.find('.letter_selected').length ){
            if( obj.find('.type_selected').length ){
                obj.find('.alpha_navi_alert').html('<a class="search_by_letter_and_type" href="#">Search by Letter and Category</a>');
            } else {
                obj.find('.alpha_navi_alert').html('<a class="search_by_letter" href="#">Search by Letter</a>');
            }   
        } else {
            obj.find('.alpha_navi_alert').html('Choose Letter');
        }
    }
    
    init();
}


function _TournamentsNavi() {
    var init = function(){ 
        obj = $('.navi_p_tournaments');
        setCondition();
        $('.navi_p_tournaments .letter_active').live('click',function(){
            if( !$(this).hasClass('letter_selected') ){
                $('.letter_active').removeClass('letter_selected');
                $(this).addClass('letter_selected');
            } 
            setCondition();
            return false;
        });
        $('.navi_p_tournaments .search_by_letter').live('click',function(){
            if( $('.navi_p_tournaments .letter_selected').length ){
                var link = '/p_tournaments/list-letter-'+$('.navi_p_tournaments .letter_selected').html()+'.html';
                document.location.href = link;
            }
            return false;
        });
    }
    
    var setCondition = function(){
        if( $('.navi_p_tournaments .letter_selected').length ){
           obj.find('.alpha_navi_alert').html('<a class="search_by_letter" href="#">Search by Letter</a>');
        } else {
           obj.find('.alpha_navi_alert').html('Choose category');
        }
    }
    
    init();
}


function _PGNchannel() {
    var _timer;
    var interval = 5000;
    var url = '/component/pgn/';
    var init = function(){ 
        if($('.channel').length){
            initPgn();
            PGNModifer(true);
            PGNTextareaBottom();
            _timer = setTimeout(function(){renew();},interval);
            //renew();
        }
    }
    
    var start = function(){
        _timer = setTimeout(function(){renew();},interval);
    }
    
    var renew = function(){
        $.post(url, {
                act : 'renew',
                id: $('.match_id').val()
            }, function(data){
                var t = $('.pgn_src').html();
                if(data != t){
                    $('.pgn_src').html(data);
                    $('.ct-board-container').remove();
                    $('.pgn_format').remove();
                    initPgn();
                    PGNModifer(true);
                    PGNTextareaBottom();
                }
            }
        );
        _timer = setTimeout(function(){renew();},interval);
    }
    
    init();
}

function _PGallery() {
    
    var _length;
    var _cols = 5;
    var _first = 1;
    var _last;
    
    var init = function(){ 
        
        _length = $('.b_gallery_tb .imgOriginal').length;
        
        $('.navi_na').live('click',function(){
            return false;
        });
        
        if(_length <= _cols){
            return false;
        }
        
        _last = $('.g_visible:last').attr('img_id');

        $('.navi_a_right').live('click',function(){
            scrollRight();
            return false;
        });
        
        $('.navi_a_left').live('click',function(){
            scrollLeft();
            return false;
        });
    }
    
    var scrollRight = function(){
        if(_last < _length){
            $('.gallery_td_'+_first).addClass('g_hidden').removeClass('g_visible');
            $('.gallery_td_'+(parseInt(_last)+1)).addClass('g_visible').removeClass('g_hidden');
            _first++;
            _last++;
            _setNavi();
        }
    }
    
    var scrollLeft = function(){
        if(_first > 1){
            $('.gallery_td_'+(parseInt(_first)-1)).addClass('g_visible').removeClass('g_hidden');
            $('.gallery_td_'+_last).addClass('g_hidden').removeClass('g_visible');
            _first--;
            _last--;
            _setNavi();
        }
    }
    
    var _setNavi = function(){
        if(_last == _length){
            $('.navi_a_right').addClass('navi_na');
        }
        if(_last != _length){
            $('.navi_a_right').removeClass('navi_na');
        }
        
        if(_first == 1){
            $('.navi_a_left').addClass('navi_na');
        }
        if(_first > 1){
            $('.navi_a_left').removeClass('navi_na');
        }
    }
    
    init();
}

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    }
    else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}


function errorChecker(){
    
    

	$(document).keypress(
		function(e) {
			//если посетитель нажал Ctrl + Enter…
			if (e.which == 13 && e.ctrlKey || e.which==10){
              //…ищем выделенный текст… 
			  var selectedText = document.getSelection ? document.getSelection() : document.selection.createRange().text;
              var cont = 
                   'Press <b>Send</b> to send error report or press <b>Cancel</b> to close window.<br>'+
                   '<div class="report_error" style="padding:2px 0; color:red; font-size:11px; display:none;">Empty error text</div>'+
                   '<br>'+
                    '<p><textarea style="width:98%; height:200px; padding:0px;" id="errorChecker_form">'+selectedText+'</textarea></p>';
              $( "#dialog" ).html(cont); 
			
              //alert(selectedText);
              $( "#dialog" ).dialog({
                  width:500,
                  buttons: {
                        "Send": function() {
                            var text = trim( $('#errorChecker_form').val() );
                            if(!text){
                                $('.report_error').show();
                                return;
                            }
                            $('.report_error').hide();
                            $.post('/component/error_report', {
                                    act : 'error_reporting',
                                    text: $('#errorChecker_form').val(),
                                    url: document.location.href
                                }, function(data){
                                    $( "#dialog" ).html('<br><br>Thanks for Reporting<br><br><br>');
                                    setTimeout(function(){ $( "#dialog" ).dialog( "close" ); },2000);
                                }
                            );
                        },
                        Cancel: function() {
                            $( this ).dialog( "close" );
                        }
                    }
              });
              
              //$("#dialog").html(selectedText);
					
//				var posX = '50px';
//       			var posY = '50px';
//			  	var winId = 'errorChecker';
//			  	var cont = 'Выделенный Вами текст скопирован в окно. Если Вы считаете нужным добавить описание ошибки, мы будем Вам благодарны.<br>'+
//			  	

//					  	
//				document.mochaUI.newWindow({
//					loadMethod: 'html',
//					id: 'errorChecker',
//					title: 'Сообщение об ошибке',
//					content: cont,
//					width: 500,
//					height: 350,
//					y:getScrollTop() + 30,
//					x:30,
//					resizable: true,
//					modal: false
//				});
//						
//				$j('#'+winId+' #errorChecker_save_button').click(function(){
//					var c = $j("#errorChecker_form").val();
//					if(!trim(c )){
//						alert('Сообщение об ошибке пустое.'+"\n"+'Пожалуйста, опишите ошибку. Спасибо.');
//					} else{
//						$j.get(overallAJ,{ 
//								act				: 'errorChecker',
//								selectedText	: c,
//								url				: document.URL
//							},
//							function(data){
//								$j('#'+winId+'_content')
//						    	.css('text-align','center')
//						    	.css('padding-top','140px')
//						    	.html('Ваще сообщение принято. Спасибо за участие в жизни GLOBER');
//						    	var ti = setTimeout(function(){
//						    			document.mochaUI.closeWindow($(winId));
//						    		}
//						    		,1200
//						    	);
//							}
//						);
//					}
//					return false;
//				});				
//				
//				$j('#'+winId+' #errorChecker_save_cancel_button').click(function(){
//					document.mochaUI.closeWindow($(winId));
//					return false;
//				});	
			}
		}
	);
}
