$(document).ready(function(){
	//alert( $("div.delayed_loading").length );
	/*$("div.delayed_loading").each( function( pos , el ) {
		$(el).load( "/klarnetCMSlocal/page_parts/" + el.getAttribute( "_part" ) + ".htm" );
		} );*/
	
	$("a.js-link" ).each( function( ) {
		this.setAttribute( "href" , this.getAttribute( "_href" ) );
		} );
	
	$("a.clients-sites-add" ).click( function() {
		$.fn.popup( { width: 400 , height: 100 , position: 'center' , header: 'Добавление сайта' , src: '/klarnetCMSlocal/different/messages/add_site_for_client.htm' } );
		} );	
	
	/* Форма поиска веб-студии */
	if( $( "form#U_select_by_params_form" ).length > 0 ) {
		$form = $( "form#U_select_by_params_form" );
		default_name = "поиск по названию или сайту";
		$("input[name='pan']" , $form )
			.val( default_name )
			.bind( "blur" , function() { if( this.value == "" ) { { this.value = default_name } } } )
			.bind( "focus" , function() { if( this.value == default_name ) { { this.value = "" } } } )
			.suggest( 
				"/klarnetCMSlocal/modules/users/list_by_part_of_name_or_link.php" , {
					onSelect: function() { $form.submit(); }
					}
				);
		}
		
	/* Для панели "Я хочу" */
	var $iw_current = null;
	$("dl.iw_element" ).each( function( ) { 
		var $this = $(this);
		var params = iw_element_get_params( $this );		
		iw_element_set_value( params , $.cookie( params.cookie_key ) ? $.cookie( params.cookie_key ) : params.$input.val() );
		
		$(this).bind( "click" , function( e ) {
			e.stopPropagation();
			if( e.target.tagName.toUpperCase() == "A" ) {
				if( $(e.target).parent( "li" ).hasClass( "disabled" ) ) {
					alert( "Это значение выбрать нельзя" );
					return;
					}
				else {
					iw_element_set_value( params , e.target.id );
					}
				}
			if( params.$variants.css( "display" ) == "none" ) {
				if( $iw_current ) iw_current_hide(); //Скрываем предыдущий открытый, если он еще открыт
				$iw_current = params;
				iw_current_show();
				}
			else iw_current_hide();

			
			} );
		} );
	$(document.body).bind( "click" , function() {
		if( $iw_current ) iw_current_hide();
		} );
	
	function iw_element_get_params( $element ) {
		var params = {};
		params.$visible = $( "dt" , $element );
		params.$variants = $("dd" , $element );
		params.$input = $( "input", $element );
		params.$global_container = $element.parent( "span.iw_elements_for" );
		params.cookie_key = ( params.$global_container.length ? params.$global_container.attr( "id" ) + "_" : "" ) + "iw_" + params.$input.attr( "name" );
		//console.log( params.cookie_key );
		return params;
		}
	function iw_element_set_value( params , value ) {
		var old_value = params.$input.val( );
		var $new_value_container = $( "li#" + value , params.$variants );
		if( $new_value_container.length ) {
			$( "li#" + old_value , params.$variants ).removeClass( "active" );
			
			params.$visible.text( $new_value_container.text() );
			params.$input.val( value );
			$.cookie( params.cookie_key , value , { domain: '.cmsmagazine.ru' , path: '/' } )
			$new_value_container.addClass( "active" );
			
			var element_name = params.$input.attr( "name" );
			if( element_name == "m_f" ) {
				var money_from = parseInt( value );
				$( "dl.i_want_m_t li" ).each( function() {
					if( parseInt( this.id ) ) {
						if( parseInt( this.id ) >= money_from ) {
							$(this).removeClass( "disabled" )
							}
						else {
							$(this).addClass( "disabled" );
							}
						}
					} );
				var $money_to_element = $( "dl.i_want_m_t" );
				var money_to_element_params = iw_element_get_params( $money_to_element )
				if( parseInt( money_to_element_params.$input.val() ) < money_from ) {
					iw_element_set_value( money_to_element_params , money_from );
					}
				}
			else if( element_name == "choose" ) {
				$("span#iw_elements_for_" + old_value ).hide();
				$("span#iw_elements_for_" + value ).show();
				}
			}
		}
	function iw_current_show() {
		$iw_current.$variants.show();
		$iw_current.$visible.addClass( "active" );
		}
	function iw_current_hide() {
		$iw_current.$variants.hide();
		$iw_current.$visible.removeClass( "active" );
		$iw_current = null;
		}
	
	if( $("#rss_sources_cloud").length ){
		$("#rss_sources_cloud").find( "a" ).each( function(){
			var tmpSLink = $(this).attr( "href" ) || "";
			if( tmpSLink.length ) {
				tmpSLink = tmpSLink.replace("http://www.","").replace("http://",""); 
				var lhref = location.href.replace("http://www.","").replace("http://",""); 
				if( lhref.indexOf( tmpSLink ) == 0 ) {
					$(this).addClass( "red" );
					}
				}
			});
		}
	
	rss_init();
	// установки для работы контейнера
	function rss_init(){
		var rss_container = $("#rss_container" );
		if ( !rss_container.length ) {
			return false;
			}
		var rss_max_count = rss_container.attr("max_count") || false;
		if ( !rss_max_count ) {
			return false;
			}
		var rss_firstItem = false;
		var rss_lastItem = false;
		var rss_firstId = false;
		var rss_lastId = false;
		
		// Если не удалось считать элементы контейнера, то ничего не делаем
		//DENISOV: Не понял, зачем так? Может лучше if( rss_getItems() ) .... ) ?
		if( rss_getItems() ) {
			rss_setButtons();
			
			// Вешаем обработку на кнопки
			$("div.rss_navi_up" )
				.css( "visibility", "visible" )
				.find("a.navi").bind("click", function(e){
					rss_moveTo( "up" );
				});
			$("div.rss_navi_down" )
				.css( "visibility", "visible" )
				.find("a.navi").bind("click", function(e){
					rss_moveTo( "down" );
				});
			
			// Запускаем механизм обработки ссылок
			rss_container.find( "a" ).filter( ".rss_item_link" ).each( function(e){
				rss_setLink(this);
				});
			rss_container.bind('mousewheel', function(event, delta) {
				var dir = delta > 0 ? 'up' : 'down';
				rss_moveTo( dir );
				return false;
		        });
			}
		// Считываем первый и последний элементы
		function rss_getItems( ) {
			rss_firstItem = rss_container.find(".new:first" );
			rss_lastItem = rss_container.find(".new:last");
			if( !rss_firstItem.length || !rss_lastItem.length ){
				return false;
				}
			rss_firstId = rss_firstItem.attr("id").split("_")[1] || false;
			rss_lastId = rss_lastItem.attr("id").split("_")[1] || false;
			if( !rss_firstId || !rss_lastId ){
				return false;
				}
			return true;
			}
		
		// Устанавливаем картинки на кнопки вверх и вниз
		function rss_setButtons( ){
			var rss_firstItem = rss_container.find(".new:first" );
			var rss_lastItem = rss_container.find(".new:last");
			var rss_firstId = rss_firstItem.attr("id").split("_")[1];
			var rss_lastId = rss_lastItem.attr("id").split("_")[1];
			$("div.rss_navi_up" ).find("a.navi").find("img").each( function() {
				var disabled = rss_firstId == 1 ? "_disabled" : "";
				$(this).attr( "src", adress_short + "img/buttons/rss_up" + disabled + ".gif" );
				});
			$("div.rss_navi_down" ).find("a.navi").find("img").each( function() {
				var disabled = rss_lastId == rss_max_count ? "_disabled" : "";
				$(this).attr( "src", adress_short + "img/buttons/rss_down" + disabled + ".gif" );
				});
			}

		// Запускаем перемещение по контейнеру
		function rss_moveTo( type ){
			if( !rss_getItems() ){
				return false;
				}
			// Если листаем вверх
			if( type == "up" ) {
				if( rss_firstId == 1 ){
					return false;
					}
				rss_firstItem.each(function (){
					var prevSibling = $(this).prev();
					if( prevSibling.length ){
						prevSibling.removeClass( "newHide" ).addClass( "new" );
						rss_lastItem.removeClass( "new" ).addClass( "newHide" );
						rss_setButtons();
						}
					});
				}
			// Если листаем вниз
			else if( type == "down" ) {
				if( rss_lastId == rss_max_count ){
					return false;
					}
				// обработчик для итема (новости)
				rss_lastItem.each(function (){
					var nextSibling = $(this).next();
					// Если есть следующий сосед, значит он уже подгружен, если нет, запускаем аякс подгрузку
					if( nextSibling.length ){
						nextSibling.removeClass( "newHide" ).addClass( "new" );
						rss_firstItem.removeClass( "new" ).addClass( "newHide" );
						rss_setButtons();
						}
					else {
						// Проверяем доступность прокрутки вниз
						var block_loading = rss_container.attr( "block_loading" ) || "no";
						if( block_loading == "yes" ) {
							return false;
							}
						rss_container.attr( "block_loading", "yes" );
						var url = "/klarnetCMSlocal/modules/rss/get_item.php?type=" + type + "&id=" + rss_lastId ;
						$.ajax( {
							"url":url,
							"dataType": "html",
							"type":"get",
							"success": function( html ) {
								rss_container.attr( "block_loading", "no" );
								if( html != "" ) {
									rss_firstItem.removeClass( "new" );
									rss_firstItem.addClass( "newHide" );
									rss_container.append( html );
									rss_setButtons();
									rss_container.find("#rss_" + (parseInt(rss_lastId)+1) ).find( "a" ).filter( ".rss_item_link" ).each( function(e){
										rss_setLink(this);
										});
									}
								},
							"error": function (XMLHttpRequest, textStatus, errorThrown) {
								//alert( url + ": " + textStatus + " -- " + errorThrown + " -- " + XMLHttpRequest );
								}
							});
						}
					});
				}
			}
		
		// Настройка ссылки для заголовка новостии
		function rss_setLink( linkObj ){
			var itemDiv = $(linkObj).parents( "div.rss_item");
			var itemId = itemDiv.attr("id").split("_")[1] || false;
			var url = "/klarnetCMSlocal/modules/rss/get_info.php?id=" + itemId ;
			
			/*
			itemDiv.find( ".rss_item_sourse" ).each(function (){
				var tmpSLink = $(this).text();
				var lIndexOf = location.pathname.lastIndexOf( tmpSLink );
				if( lIndexOf > 0 && location.pathname.length == tmpSLink.length + lIndexOf ){
					itemDiv.addClass( "cur_rss_source" );
					}
				});
			*/
			
			// Настройки и активация плагина для ссылки
			$( linkObj ).jHelperTip({
				trigger: "click",
				source: "ajax",
				type: "GET", 
				url: url,
				data: { },
				loadingImg: "/img/s.gif",
				loadingText: 'Загрузка...',
				autoClose: true, 
				opacity: 0.98,
				toCenter: false,
				loadingToBlock:  itemDiv.find(".rss_item_info"),
				preshowCallback: function( obj ){
					if ( navigator.userAgent.toLowerCase().indexOf("msie") ) {
						if( $(obj).find( ".rss_item_tip_announce" ).length ) {
							var tmp_height = $(obj).find( ".rss_item_tip_announce" ).height();
							if( parseInt( tmp_height ) > 200 ) {
								$(obj).find( ".rss_item_tip_announce" ).height( 200 );
								}
							else if( parseInt( tmp_height ) < 50 ){
								$(obj).find( ".rss_item_tip_announce" ).height( 50 );
								}
							}
						}
					}
			});
			return true;
			}
		}
		
	/* 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="/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;
		});
	});