$(document).ready(function(){
	$("a.js-link" ).each( function() {
		this.setAttribute( "href" , this.getAttribute( "_href" ) );
	});
	
	/* Отображение нужно кол-ва комментариев экспертов */
	$("#experts_opinions_show_part" ).each( function() {	
		var $this = $(this);
		var min_random = 0;
		var max_random = $this.attr( "_count" );
		var max_count = $this.attr( "_visible_count" );
		var range = max_random - min_random;
		var random = null;
		var used_randoms = new Array();
		var max_attempts;
		
		for( var k = 0 ; k < max_count ; k++ ) {
			max_attempts = 50;
			while( ( random === null || $.inArray( random , used_randoms ) !== -1 ) && --max_attempts > 0 ) {
				random = Math.floor( Math.random() * range ) + min_random;
			}
			used_randoms[ used_randoms.length ] = random;
			$("#" + random , $this ).show();
		}
	});
	
	/* Разворачивание подчиненных строк */
	function rowClick( $tr ) {
		var obj_id = $tr.attr( "id" );
		if( obj_id ) {
			var $container = $tr.parents( "#with-rows-with-childs" );
			
			//Скрываем предыдущий открытый
			$("tr.active.row-with-childs[id!=" + obj_id + "]" , $container ).each(function() { rowClick( $(this) ); });
			
			$childs_container = $("#" + obj_id + "_childs" , $container );
			
			if( $tr.is( ".active" ) ) {
				$childs_container.slideToggle("fast");
				$tr.removeClass( "active" );
			}
			else {
				if( $childs_container.html() == "" ) {
					$childs_container.html( '<tr><td><img style="padding-left: 46px" src="/img/progressbar.gif"/></td></tr>' );
					$childs_container.slideToggle("fast");
					var load_script_address = "/klarnetCMSlocal/modules/rating/load_source.php?" + ( $container.attr( "_for_load_source" ) ) + "&companies_id=" + obj_id + "&page=1-1000";
					$.get( load_script_address , function(data){	
						var tmp_height = $childs_container.height();
						$childs_container.html( data );
						var tmp_new_height = $childs_container.height();
						//$childs_container.css( "height" , tmp_height );
						$childs_container.css( "height" , tmp_new_height );
						//$childs_container.css( "overflow" , "hidden" );
						//console.log( tmp_new_height );
						//alert( tmp_new_height );
						//$childs_container.animate( { "height" : tmp_new_height } , "fast" );
					} );/**/
				}
				else {
				$childs_container.slideToggle("normal");
				}

				$tr.addClass( "active" );
			}
		}
	}
	
	function rowLoadMoreChilds( $tr ) {
		var $container = $tr.parents( "#with-rows-with-childs" );
		var obj_id = $tr.attr( "_obj_id" );
		var page = $tr.attr( "_load_page" );
		if( obj_id && page ) {
			$( "td.container" , $tr ).html( '<img src="/img/progressbar.gif" />' );
			var load_script_address = "/klarnetCMSlocal/modules/rating/load_source.php?" + ( $container.attr( "_for_load_source" ) ) + "&companies_id=" + obj_id + "&page=" + page;
			$.get( load_script_address , function(data){
				$tr.after( data );
				$tr.remove();
			} );
		}
	
	}
	
	$("#with-rows-with-childs" ).bind( "click" , function(e) {
		var $tr = $(e.target).parents( "tr:first" );
		
		if( $(e.target).hasClass( "load_childs" ) ) {
			var table = this;
			if( $tr.is('.row-with-childs') ) rowClick( $tr );
			}
		else if( $tr.hasClass('load_more_childs') ) {
			rowLoadMoreChilds( $tr );
			}
	});
	
	$("select.paging" ).bind( "change" , function(e) {
		$el = $(this);
		var new_href = document.location.href;
		var is_new_page_first = false;
		//alert( this );
		//Определяем, находимся ли мы не на первой странице
		$("option" , $el ).each( function( k ) {
			//alert( k );
			if( k == 0 && this.value == $el.val() ) {
				is_new_page_first = true;
				}
			if( new_href.indexOf( this.value ) >= 0 ) {
				new_href = new_href.replace( this.value , "[REPLACE]" );
				}
			//alert( new_href.indexOf( this.value ) );
			} );
		if( new_href.indexOf( "[REPLACE]" ) >= 0 ) {
			if( is_new_page_first ) {
				new_href = new_href.replace( "[REPLACE]/" , "" );
				new_href = new_href.replace( "[REPLACE]" , "" );
				}
			else {
				new_href = new_href.replace( "[REPLACE]" , $el.val() );
				}
			}
		else {
			new_href = new_href + ( new_href.substr( new_href.length -1 , 1 ) == "/" ? "" : "/" ) + $el.val() + "/";
			}
		document.location.href = new_href; 
	});
	
	$("select.go-to-page" ).bind( "change" , function(e) {
		$el = $(this);
		if( $el.val() != "" ) {
			document.location.href = $el.val();
			}
	});
	
	/* */
	
	/* Подсвечивание контекстных пунктов меню */
	var tmp_links_arr = new Array();
	tmp_links_arr[ 0 ] = "official-sponsors-2009";
	tmp_links_arr[ 1 ] = "information-partners-2009";
	tmp_links_arr[ 2 ] = "regional-partners-2009";		
	tmp_links_arr[ 3 ] = "information-support-2009";		
	for( var k = 0 ; k < tmp_links_arr.length ; k++ ) {
		if( document.location.href.indexOf( tmp_links_arr[ k ] ) > 0 ) {
			var $tmp_link = $( "#" + tmp_links_arr[ k ] + "_link" );
			if( $tmp_link.length ) {
				$tmp_link.addClass( "active" );
				}
			break;
			} 
		}
		
	/* Обработка версии для печати */
	$to_print_link = $("a.to_print_link" );
	if( $to_print_link.length ) {
		$to_print_link.bind( "click" , function() {
			var tmp_href = document.location.href;
			if( tmp_href.indexOf( "#" ) > 0 ) tmp_href = tmp_href.substr( 0 , tmp_href.indexOf( "#" ) );
			tmp_href += ( tmp_href.indexOf( "?" ) > 0 ? "&" : "?" ) + "print=yes";
			var tmp_window = window.open( tmp_href ,"print","resizable=yes,scrollbars=yes,width=600,height=800" );
			if( tmp_window ) tmp_window.focus();
			} );
		}
	
	/* Обработка вставки в блог */
	$paste_to_blog_link = $("a.paste_to_blog_link" );
	if( $paste_to_blog_link.length ) {
		$paste_to_blog_link.bind( "click" , function() {
			var str_header = "";
			$header_container = $( "p.text_after_header" );
			if( $header_container.length > 0 ) {
				var tmp_str_header = $header_container.html();
				if( tmp_str_header.length > 0 && tmp_str_header.indexOf( "ТОП" ) == 0 ) {
					str_header = "ТОП-5" + tmp_str_header.substr( 3 );
					}
				}
			var str_source = "/scripts/for_blog.php?" + $paste_to_blog_link.attr( "_for_load_source" );
			$popup = $.wPopup( { 
				header: "Код для вставки в блог" , 
				src: str_source , 
				width: "530px" , 
				height: "580px" , 
				position: "center" ,
				after_content_load: function( $content ) {
					//alert( $content );
					$code_container = $( "#code_container" , $content );
					content_for_paste = $code_container.html();
					content_for_paste = content_for_paste.replace( /(\t|\r\n|\n)/g , "" );
					if( str_header ) {
						content_for_paste = content_for_paste.replace( /id="header">([^<]*)<\/h1>/g , '"id="header">' + str_header + '</h1>' );
						}
					$code_button = $( "#code_button" , $content );
					$code_content = $( "#code_content" , $content );
					$result_button = $( "#result_button" , $content );
					$result_content = $( "#result_content" , $content );
					
					$( "textarea" , $code_content ).val( content_for_paste );
					$result_content.html( content_for_paste );
					
					$result_button.bind( "click" , function() {
						$result_button.addClass( "active" );
						$code_button.removeClass( "active" );
						$code_content.hide();
						$result_content.show();
						} );
						
					$code_button.bind( "click" , function() {
						$result_button.removeClass( "active" );
						$code_button.addClass( "active" );
						$code_content.show();
						$result_content.hide();
						} );
					} 
				} );
			} );
		}
	
	/* IMAGES LINKS */
	var image_jpopup__current_loading = '';
	var $image_jpopup__progress = $('<div style="display: none; position: absolute; background: #FFFFFF; z-index: 104;" class="ahtung_message"><div>Пожалуйста, подождите.</div><div><img src="http://www.cmsmagazine.ru/img_out/progressbar.gif"/></div></div>');
	$('body').append($image_jpopup__progress);
	var image_jpopup__progressbar = {
		show: function(){
			$image_jpopup__progress.css( "top" ,  parseInt( $(window).scrollTop() + ( $(window).height() - $image_jpopup__progress.height() ) / 2 ) );
			$image_jpopup__progress.css( "left" ,  $(window).scrollLeft() + ( $(window).width() - $image_jpopup__progress.width() ) / 2 );
			$image_jpopup__progress.show();
			},
		hide: function(){
			$image_jpopup__progress.hide();
			}
		};
	$('a.image_jpopup').click(function(){
		var img_src = $(this).attr('href');
		image_jpopup__progressbar.show();
		var img = new Image();
		img.onload = function(){
			if( img_src == image_jpopup__current_loading ){
				image_jpopup__progressbar.hide();
				$.fn.popup({
					'height'	: 570,
					'width'		: 420,
					'position'	: 'center',
					'html'		: '<div style="width: 400px; height: 550px; background: url( '+img_src+' ) center center no-repeat">&nbsp;</div>'
					});
				}
			};
		img.src = img_src;
		image_jpopup__current_loading = img_src;
		return false;
		});
		
	/* Окно с отзывом о РР */
	$( "a#RR_review" ).bind( "click" , function() {
		image_jpopup__progressbar.show();
		$.ajax({
			url: '/scripts/for_RR_review.php',
			success: function(data) {
				image_jpopup__progressbar.hide();
				location.hash = "review";
				$popup = $.wPopup( { 
					header: "Отзыв о работе проекта" , 
					html: data , 
					width: "700px" , 
					height: "600px" , 
					position: "center" ,
					before_remove: function() { location.hash = ""; return true; }
					} );
				}
			});
		});
		
	/* Ценовой фильтр */
	$filter_by_prices_steps = $("div#filter_by_prices_steps" );
	if( $filter_by_prices_steps.length ) {
		$( "select" , $filter_by_prices_steps ).bind( "change" , function() {
			var tmp_current_sites_types_id = this.value;
			$( "div.steps" , $filter_by_prices_steps ).hide().filter( function() { return this.id == "price_for_" + tmp_current_sites_types_id } ).show();
			} );
			
		function filter_by_prices_step( attrName , keys , $table , className ) {
			var tmp_arr = keys.split( "," );
			//alert( tmp_arr.length );
			$( "tr" , $table ).removeClass( className ).filter( function() { return keys ? ( $(this).attr( attrName ) && $.inArray( $(this).attr( attrName ) , tmp_arr ) === -1 ) : false  } ).addClass( className );
			}
	
		$with_rows_with_childs = $("#with-rows-with-childs" );
		$filters_links = $( "a.filter" , $filter_by_prices_steps );
		$filters_links.bind( "click" , function() {
			$this = $(this);
			if( $this.hasClass( "price_step_active" ) ) {
				filter_by_prices_step( "id" , "" , $with_rows_with_childs , "inactiveClass" );
				$this.removeClass( "price_step_active" );
				}
			else {
				$filters_links.removeClass( "price_step_active" );
				filter_by_prices_step( "id" , $this.attr( "_ids" ) , $with_rows_with_childs , "inactiveClass" );
				document.location.hash = $( "tr[id>0]:not(.inactiveClass):first" , $with_rows_with_childs ).attr( "id" );
				$this.addClass( "price_step_active" );
				}
			
			} );
		}
		
	/* Обработка hash */
	if( location.hash ) {
		var hash = location.hash.substr( 1 );
		if( parseInt( hash ) ) {
			rowClick( $("tr#" + hash ).filter( ".row-with-childs" ) );
			}
		else if( hash == "review" ) {
			$( "a#RR_review" ).click();
			}
		}
	
	/* FAVORITES */
	(function(){						//return;
		var  COOKIE_NAME = 'favorites'
			,COOKIE_PARAMS = { path:'/', expires: 7 }
			,favorites = {count:0}
			,$counter = $('#fav_counter')
			,$fav_container = $('#fav_container');
			
		if( typeof( $.cookie( COOKIE_NAME ) ) == 'string' )
			favorites = JSON.parse( $.cookie( COOKIE_NAME ) );
		
		function update_counter_view(){
			if( favorites.count > 0 )
				$counter.html( favorites.count+' поз.' );
			else
				$counter.html('');
		}
		function save_favorites(){
			update_counter_view();
			$.cookie( COOKIE_NAME, JSON.stringify( favorites ), COOKIE_PARAMS );
		}
			
		function add_favorites( obj ){
			if( typeof( favorites[ obj.type ] ) != 'object' )
				favorites[ obj.type ] = new Array();
			
			favorites[ obj.type ].push( obj.id );
			favorites.count++;
			save_favorites();
			//process_page();
		}
		
		function remove_favorites( obj ){
			if( typeof( favorites[ obj.type ] ) == 'object' ){
				var found_at = $.inArray( obj.id, favorites[ obj.type ] );
				if( found_at >= 0){
					favorites[ obj.type ].splice( found_at, 1 );
					--favorites.count;
					save_favorites();
					//process_page();
				}
			}
		}
		
		function is_in_favorites( obj ){
			/*if( typeof( favorites[ obj.type ] ) == 'object' && $.inArray( obj.id, favorites[ obj.type ] ) >= 0 ) return true;
			else return false;*/
			return ( typeof( favorites[ obj.type ] ) == 'object' && $.inArray( obj.id, favorites[ obj.type ] ) >= 0 );
		}
		
		function favorites_button_handler(){
			var  $this = $(this)
				,this_obj = { id:$this.attr('obj_id'), type:$this.attr('obj_type') };
			
			if( $this.is('.fav_add') ){
				add_favorites( this_obj );
				favorites_button_set_view( $this, 'remove' );
			} else{
				remove_favorites( this_obj );
				favorites_button_set_view( $this, 'add' );
			}
			
			update_counter_view();
		}
		
		function favorites_button_set_view( $button, view_type ){
			$button.attr('title', view_type=='add' ? 'Добавить в избранное' : 'Удалить из избранного')
				.removeClass(view_type=='add' ? 'fav_remove' : 'fav_add')
				.addClass(view_type=='add' ? 'fav_add' : 'fav_remove');
		}
		
		function process_page(){
			$('div.favorites_button').click(favorites_button_handler).each(function(){
				var $this = $(this);
				var this_obj = { id:$this.attr('obj_id'), type:$this.attr('obj_type') };
				if( is_in_favorites( this_obj ) )
					favorites_button_set_view( $this, 'remove' );
				else
					favorites_button_set_view( $this, 'add' );
			});
			$('input.f_list_delete').click(function(){
				var $this = $(this);
				remove_list_el( { id:$this.attr('obj_id'), type:$this.attr('obj_type') } );
			});
			$('input.f_list_clean').click(function(){
				favorites = {count:0};
				save_favorites();
				update_counter_view();
				$('.fav_list', $fav_container).remove();
				$('.fav_nothing', $fav_container).show();
			});
		}
		
		function remove_list_el( obj ){
			$('div[fav_pp_id='+obj.type+'_'+obj.id+']').remove();//remove obj views
			remove_favorites( obj );//remove obj from cookie
			if( !(favorites.count > 0) ){
				$('.fav_list', $fav_container).remove();
				$('.fav_nothing', $fav_container).show();
			}
			else
				update_categories_view();
		}
		
		function update_categories_view(){
			var  $categories = $('div.fav_category', $fav_container)
				,categories_length = $categories.length;
			
			for(var i=0; i<categories_length; i++){
				if( !($('div[fav_pp_id]', $categories.eq(i)).length) ){
					$categories.eq(i).remove();
				}
			}
		}
		
		process_page();
		update_counter_view();
		
	})();
});