$(document).ready(function(){
	$("#klarnet_open" ).bind( "click" , function() {
		var lang = this.className;
		var width = 20;
		var height = 20;
		var tmp_window = window.open( "/klarnetCMS/" + ( lang ? "?_lang=" + lang : "" ) , "cms" , "width=" + width +",height=" + height + ",menubar=no,resizable=yes" );
		if( tmp_window ) { 
			tmp_window.moveTo( parseInt( screen.availWidth - width ) / 2 , parseInt( screen.availHeight - height ) / 2 );
			tmp_window.focus();
			}
		});
	
	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/button_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/button_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/ajax-loader.gif',
				loadingText: 'Загрузка...',
				autoClose: true, 
				opacity: 0.9,
				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;
			}
		}
	
	/* Для панели "Я хочу" */
	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( );
		$( "li#" + old_value , params.$variants ).removeClass( "active" );
		var $new_value_container = $( "li#" + value , params.$variants );
		params.$visible.text( $new_value_container.text() );
		params.$input.val( value );
		$.cookie( params.cookie_key , value )
		$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;
		}
	$( "#topPanel_hide" ).bind( "click" , function() {
		$.cookie( "iw_show" , "no" , { path: '/' } );
		$( "#topPanel_opened" ).addClass("dn");
		$( "#topPanel_closed" ).removeClass("dn");
		} );
	$( "#topPanel_open" ).bind( "click" , function() {
		$.cookie( "iw_show" , "yes" , { path: '/' } );
		$( "#topPanel_opened" ).removeClass("dn");
		$( "#topPanel_closed" ).addClass("dn");
		} );
		
	if( $.cookie( "iw_show" ) == "no" ) {
		$( "#topPanel_hide" ).triggerHandler( "click" );
		}
	/* */
	
	/* Подписка */
	$( "form#subscription" ).bind( "submit" , function() {
		//alert( 'ddd' );
		var $email = $( "input[name=email]" , $(this) );
		var email = $email.val();
		if( !email ) {
			alert( 'Укажите свой e-mail' );
			$email.focus();
			}
		else if( ! /^\w[\w.\-\&]*\@\w[\w.\-]*\w{2,}/.test(email) ) {
			alert( 'Укажите корректный e-mail' );
			$email.focus();
			}
		else {
			$( "#subscription_container" ).load( "/klarnetCMSlocal/modules/subscriptions/add.php?email=" + email );
			}
		//alert( email );
		return false;
		} );
});