var _self = this;


//google.load("search", "1", {"language":"en"/*, nocss:true,"callback" : mapsLoaded*/ } );


function Copy2Clipboard( _line ){
 _line = String(_line);

 if (window.clipboardData)
	window.clipboardData.setData("Text", _line);
 else if (window.netscape){
	try{
	  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

	  var clipBoard = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService( Components.interfaces.nsIClipboardHelper );
	  clipBoard.copyString( _line );

	 }catch(err){; /*alert ("Clipboard copying error: " + err); return false*/ }
  }
 return true;
}

function GetSelection(){
	var line = '';

	if( document.getSelection ) // Mozilla
		line = document.getSelection().toString();
	else if( document.selection ) // IE
		line = document.selection.createRange().text;
	else 	if( window.getSelection ) // Mozilla
		line = window.getSelection().toString();
	
	return line;
}

function SetClipBoard(_ev){
	var slctn = GetSelection();

	if( _ev.ctrlKey == true && _ev.keyCode == 67
	&&  slctn != null && slctn != '' )
		Copy2Clipboard( slctn + '\nПодробнее: ' + window.location.href );
}


$(function(){

	function textareaCounter($textarea)
	{
		var $block = $textarea.closest('.twitter_text_label');
		var link = $block.find('span.twitter_url').text().length;
		var text =  $textarea.val().length;
		$block.find('span.counter').text('('+ (140 - link - text) +')');
	}
	
	$('.twitter_flag').click(function(){
		if($(this).val())
		{
			$('.twitter_text').show();
			$('.twitter_text_label').show();
			$('.twitter_text').val($('input[name=header]').val());
			debugger;
			//вот такая обработка для разных разделов
			if($('.twitter_text').val().length == 1)
			{
				$('.twitter_text').val($('textarea[name=cite]').val()); //сказано
				if($('.twitter_text').val().length == 1)
				{
					$('.twitter_text').val($('textarea[name=header]').val());//сделано
					if($('.twitter_text').val().length == 1)
					{
						$('.twitter_text').val($('input[name=name]').val());//книги
						if($('.twitter_text').val().length == 1)
						{
							$('.twitter_text').val($('input[name=fio]').val());//эксперты
							if($('.twitter_text').val().length == 1)
							{
								$('.twitter_text').val($('textarea[name=description]').val());//цифры
							}
						}
					}
				}
			}
			textareaCounter($('.twitter_text'));
		}
		else
		{
			$('.twitter_text').hide();
			$('.twitter_text_label').hide();
		}
	});
		
	$('.facebook_flag').click(function(){
	debugger;
		if($(this).val())
		{
			$('.facebook_text').show();
			$('.facebook_text_label').show();
			$('.facebook_text').val($('input[name=header]').val());
			if($('.facebook_text').val().length == 1)
			{
				$('.facebook_text').val($('textarea[name=cite]').val()); //сказано
				if($('.facebook_text').val().length == 1)
				{
					$('.facebook_text').val($('textarea[name=header]').val());//сделано
					if($('.facebook_text').val().length == 1)
					{
						$('.facebook_text').val($('input[name=name]').val());//книги
						if($('.facebook_text').val().length == 1)
						{
							$('.facebook_text').val($('input[name=fio]').val());//эксперты
							if($('.facebook_text').val().length == 1)
							{
								$('.facebook_text').val($('textarea[name=description]').val());//цифры
							}
						}
					}
				}
			}
		}
		else
		{
			$('.facebook_text').hide();
			$('.facebook_text_label').hide();
		}
	});

	var self = this;

	$('body')[0].setAttribute('onkeyup', 'SetClipBoard(event);');

	$('textarea, input:text').keyup( function(_ev){
		SetClipBoard( _ev.originalEvent );
	});
	
	$('.twitter_text').keyup(function(){
		textareaCounter($(this));
	});

	
	(function(){
		
		$('a.not_active').click(function(){
			return false;
		})
		  
		$('#edit_object input:text, #edit_object textarea').keyup(function(){		
			
			 var length = $(this).val().length,
			 	 counter = $(this).parent().find('b.counter,b.overflow'),
			     max = parseInt(counter.attr('rel')),
			     c_left = max-length;		
			
			 if ((c_left)<=0){			 
				 counter.removeClass().addClass('overflow').text('Вы превысили предел на '+(0-c_left)+' символов(а)' );
			 }else{
				
				 counter.removeClass().addClass('counter').text(c_left);
			 }
			
		 });
		 
		 
		 $('div.year').live('click', function(){
		 	$('#all_years').show();
		 })
		 
		 $('div.month').live('click', function(){
		 	$('#all_months').show();
		 })
		 
		 
		  $('a.prevmonth, a.nextmonth, div.years_cont li, div.months_cont li').live('click',function(){
		 	
			var param = $(this).attr('rel'),
				body  = $('#archive_body');	
			
			$.ajax({
				url: "/ajax/archive",
				type: "get",
				data:param,
				dataType: "html",
				success: function(data) {
					if (data){
						body.html(data);
						self.initCalendar();
					}
				}
			});
			
		 })
		
		if($('#mainpage').length){
	
			var $container = $('#container'),
				$lenta = $container.find('#lenta_cont'),
				$title = $lenta.find('#lenta_title'),
				$archive = $title.find('.title_archive'),
				$yesterday = $title.find('.title_yesterday'),
				$today = $title.find('.title_today'),
				//$tomorrow = $title.find('.title_tomorrow'),
				//$announcement = $title.find('.title_announcement'),
		
				$items = $lenta.find('#lenta > div'),
				
				$archiveSect = $lenta.find('#archive'),
				$yesterdaySect = $lenta.find('#yesterday'),
				$todaySect = $lenta.find('#today'),
				//$tomorrowSect = $lenta.find('#tomorrow'),
				//$announcementSect = $lenta.find('#announcement'),
				$curSect = $todaySect;
			
			var spd = 500;
			
			var $archiveShadow = $archiveSect.find('.shadow');
			var $yesterdayShadow = $yesterdaySect.find('.shadow');
			var $todayShadow = $todaySect.find('.shadow');
			
			
			var archiveFunc = function(){
				if($archiveSect.hasClass('current')) return;
				$items.removeClass('current');
				$archiveSect.addClass('current');
				$todayShadow.stop().css({ opacity:1 }).show();
				$yesterdayShadow.stop().css({ opacity:1 }).show();
				$archiveShadow.fadeOut(spd);
				$lenta.css({ left:'1600px' });
				$title.hide().removeClass().addClass('lenta_archive').fadeIn(spd);

			}
			
			var yesterdayFunc = function(){
				if($yesterdaySect.hasClass('current')) return;
				$items.removeClass('current');
				$yesterdaySect.addClass('current');
				$todayShadow.stop().css({ opacity:1 }).show();
				$archiveShadow.stop().css({ opacity:1 }).show();
				$yesterdayShadow.fadeOut(spd);
				$lenta.css({ left:'800px' });
				$title.hide().removeClass().addClass('lenta_yesterday').fadeIn(spd);
			}
			
			var todayFunc = function(){
				if($todaySect.hasClass('current')) return;
				$items.removeClass('current');
				$todaySect.addClass('current');
				$yesterdayShadow.stop().css({ opacity:1 }).show();
				$archiveShadow.stop().css({ opacity:1 }).show();
				$todayShadow.fadeOut(spd);
				$lenta.css({ left:'0' });
				$title.hide().removeClass().addClass('lenta_today').fadeIn(spd);
			}
			
			/*var tomorrowFunc = function(){
				if($tomorrowSect.hasClass('current')) return;
				$items.removeClass('current');
				$tomorrowSect.addClass('current');
		
				$lenta.animate({ left:'-800px' }, 600, function(){
					$title.removeClass().addClass('lenta_tomorrow').fadeIn('300');
				});
				$title.hide();
			}
			
			var announcementFunc = function(){
				if($announcementSect.hasClass('current')) return;
				$items.removeClass('current');
				$announcementSect.addClass('current');
		
				$lenta.animate({ left:'-1600px' }, 600, function(){
					$title.removeClass().addClass('lenta_announcement').fadeIn('300');
				});
				$title.hide();
			}*/
			
			$archive.click(archiveFunc);
			$yesterday.click(yesterdayFunc);
			$today.click(todayFunc);
			//$tomorrow.click(tomorrowFunc);
			//$announcement.click(announcementFunc);
			
			
			
			$archiveShadow.click(archiveFunc);
			$yesterdayShadow.click(yesterdayFunc);
			$todayShadow.click(todayFunc);
			//$tomorrowSect.find('.shadow').click(tomorrowFunc);
			//$announcementSect.find('.shadow').click(announcementFunc);
			
			$todayShadow.hide();
			
		}
		
	})();
	
	
	(function(){
	
		var $experts = $('.experts');
		
		if($experts.length){
		
			$experts.each(function(){
		
				var self = this,
					$this = $(this),
					$list = $this.find('.list'),
					$lenta = $list.find('.commentator'),
					$blocks = $lenta.find('> *'),
					$prev = $this.find('.prev'),
					$next = $this.find('.next'),
					$document = $(document),
					pos = 0,
					w = -61,
					lim = $blocks.length - 9,
					scrolling = false,
					i=0;
				
				$prev.hide();
				
				this.stopScrolling = function(e){
					scrolling = false;
					$document.unbind('mousemove', self.stopScrolling);
					$document.unbind('mouseup', self.stopScrolling);
				}
				
				$prev.bind('mousedown', function(){
					$document
						.bind('mousemove', self.stopScrolling)
						.bind('mouseup', self.stopScrolling);
					scrolling = true;
					self.prevFunc.apply(this);
				});
				
				$next.bind('mousedown', function(){
					$document
						.bind('mousemove', self.stopScrolling)
						.bind('mouseup', self.stopScrolling);
					scrolling = true;
					self.nextFunc.apply(this);
				});
				
				$prev.bind('mousemove', function(e){
					e.stopPropagation();
					e.cancelBubble = true;
				});
				
				$next.bind('mousemove', function(e){
					e.stopPropagation();
					e.cancelBubble = true;
				});
				
				this.prevFunc = function(){
					if(pos > 0){
						pos--;
						$lenta.stop().animate({ left:pos*w }, 150, function(){
							if(scrolling){
								setTimeout(self.prevFunc, 50);
							}
						});
						if (pos <= 0) {
							$prev.hide();
						}
						$next.show();
					}
				}
				
				this.nextFunc = function(){
					if(pos < lim){
						pos++;
						$lenta.stop().animate({ left:pos*w }, 150, function(){
							if(scrolling){
								setTimeout(self.nextFunc, 50);
							}
						});
						if (pos >= lim) {
							$next.hide();
						}
						$prev.show();
					}
				}
				
			});
		
		}
	
	})();
	
	
	this.initCalendar = function(){
	
		var $select = $('.months');
		
		if($select.length){
	
			$select.each(function(){
			
					var $this = $(this),
					$d_act = $this.find('.day_act'),
					$d_cont = $this.find('.days_cont'),
					$d_ul = $d_cont.find('ul');

				var d_cont_h, m_ul_h, m_s;
					
				$d_act.bind('click', function(e){
	
					$d_cont.show();
	
					d_cont_h = $d_cont.height();
					d_ul_h = $d_ul.height();
					d_s = (d_ul_h - d_cont_h)/d_cont_h + 0.5;
					
					$d_ul.css({ 'top' : -(d_ul_h - d_cont_h)/2 });
				
				});
	
				$d_cont.bind('mouseleave', function(){
				
					$d_cont.hide();
				
				}).bind('mousemove', function(e){
					
					var et = -(e.pageY - $d_cont.offset().top)*d_s + 30;
				
					$d_ul.css({ 'top':et });
				
				});

				
				var $this = $(this),
					$m_act = $this.find('.month_act'),
					$m_cont = $this.find('.months_cont'),
					$m_ul = $m_cont.find('ul');

				var m_cont_h, m_ul_h, m_s;
					
				$m_act.bind('click', function(e){
	
					$m_cont.show();
	
					m_cont_h = $m_cont.height();
					m_ul_h = $m_ul.height();
					m_s = (m_ul_h - m_cont_h)/m_cont_h + 0.5;
					
					$m_ul.css({ 'top' : -(m_ul_h - m_cont_h)/2 });
				
				});
	
				$m_cont.bind('mouseleave', function(){
				
					$m_cont.hide();
				
				}).bind('mousemove', function(e){
					
					var et = -(e.pageY - $m_cont.offset().top)*m_s + 30;
				
					$m_ul.css({ 'top':et });
				
				});
				
				
				
				var $y_act = $this.find('.year_act'),
					$y_cont = $this.find('.years_cont'),
					$y_ul = $y_cont.find('ul');
					
				var y_cont_h, y_ul_h, y_s;
					
				$y_act.bind('click', function(e){
	
					$y_cont.show();
	
					y_cont_h = $y_cont.height();
					y_ul_h = $y_ul.height();
					$y_ul.css({ 'top' : -(y_ul_h - y_cont_h)/2 });
				
				});
	
				$y_cont.bind('mouseleave', function(){
				
					$y_cont.hide();
				
				});
				
			});
	
		}
	
	};


	(function(){
		function DaysInMonth(_month, _year){
			 var days;


			 switch(_month){
				 case 1: case 3: case 5: case 7: case 8: case 10: case 12: 
					days = 31; break;

				  case 4: case 6: case 9: case 11:
					days = 30; break;

				  case 2: if( _year % 4==0 && _year % 100 != 0 || _year % 400==0 )
								  days = 29;
							 else
								  days = 28;
			 }

			 return days;
		};


		var $wdgt = $('div.months.monthsWidget');
		var $daySlct = $('div.select.days_cont');


		var dQty = DaysInMonth( parseInt($wdgt.find('div.month_act').attr('rel'),10), parseInt($wdgt.find('div.year_act').text(),10) );
		var dayHtml="";
		var isRel = $('div.select.months_cont ul li.act').attr('rel');


		for(i=0; i<dQty; i++)
			dayHtml += '<li rel="' + ( isRel + '&day='+ (i+1) ) + '">'+(i+1)+'</li>';

		$daySlct.find('ul').html( dayHtml );
	})();


	(function(){
	
		var $mw = $('.monthsWidget li');
		
		if($mw.length){
		
			$mw.bind('click', function(){
				var rel = $(this).attr('rel');
				document.location = rel;
			});
		
		}
	
	})();
	
	this.initCalendar();


	(function(){
	
		var $dayTheme = $('#mainpage .main_news');
		
		if($dayTheme.length){
		
			$dayTheme.each(function(){
		
				var $this = $(this),
					$imgs = $this.find('.f > span'),
					$dl = $this.find('> dl');
				
				$dl.bind('mouseenter', function(){
					var n = $dl.index(this),
						$this = $(this);
	
					$dl.removeClass('act');
					$this.addClass('act');
					$imgs.hide();
					$imgs.eq(n).show();
				});
			
			});
			
		}
	
	})();
	
	/*
	 * Tipper
	 */
	(function(){

		$('<div id="hinter"></div>').appendTo('body');
	
		var self = this,
			$hinter = $('#hinter'),
			$document = $(document);

		$hinter.css({
			position:	'absolute',
			display:	'none',
			border:		'1px solid #333333',
			background:	'#ffffcc',
			color:		'#000',
			padding:	'5px',
			opacity:	'0.9',
			zIndex:		'99999',
			maxWidth:	'200px'
		});

		//$hinter.bind('mouseover', self.hideHinter);
		
		this.showHinter = function(e){
			$hinter.css({ left:e.pageX+11, top:e.pageY+17, display:'block' });
		}

		this.setHinter = function(hint){
			$hinter.html(hint);
		}

		this.hideHinter = function(){
			$document.unbind('mousemove', self.showHinter);
			$hinter.hide();
		}
		
		$('.hintThis').live('mouseover', function(e){
			var $this = $(this), 
				hint = $this.find('.thisHint').html();

			self.setHinter(hint);
			
			self.showHinter(e);
			
			$document.bind('mousemove', self.showHinter);
			
			$this.one('mouseleave', self.hideHinter);
			
		});
		
	})();


	/*
	 * Add To Favorites
	 */
	(function(){
		var $favoriteLnk = $('#addToFavoritesLink'),
			$startPageLnk = $('#addToStartPageLink');
	
		if ($favoriteLnk.length) {
			$favoriteLnk.click(function() {
			
				var title = 'Актуальные комментарии',
					url = 'http://actualcomments.ru/';
				
				
				if (title == undefined) title = document.title;
				if (url == undefined) url = top.location.href;
				if (window.sidebar) {
					// Firefox
					window.sidebar.addPanel(title, url, '');
				}
				else 
					if (window.opera && window.print) {
						// Opera
						var a = $favoriteLnk.get(0);
						
						a.href = url;
						a.rel = "sidebar";
						a.title = url + ',' + title;
						return true;
					}
					else 
						if (window.external) {
							// IE
							window.external.AddFavorite(url, title);
						}
						else {
							this.agent = navigator.userAgent;
							this.mac = this.agent.indexOf("Mac") - 1;
							if (this.mac) alert('Чтобы добавить в избранное нажмите Command-D.');
							else alert('Чтобы добавить в избранное нажмите CTRL-D.');
						}
	
				return false;
				
			});
		}
		
		if($startPageLnk.length){
			$startPageLnk.click(function() {
			
				(function(HomePage) {
				
					if(document.all && !window.opera) {
						var a = $startPageLnk.get(0);
						a.style.behavior = 'url(#default#homepage)';
						a.setHomePage(HomePage)
					}
	
				})('http://actualcomments.ru/');
				
				return false;
				
			});
			if(!document.all || window.opera) {
				$startPageLnk.remove();
			}
		}

	})();

	 $('div.in_blog .l').live('click', function(){
	 	$('#into_blog').toggle();
	 });


	 function SetOldSearchLink( form ){
		 var href = "/oldSearch?word=" + form.input.value;
		 $('#oldSearchResult').html( "Вы можете воспользоваться <a href='" + href + "'>старой системой поиска</a>" );
	 }
	 
	 (function(){

		 var searchControl;
		 var webSrch;
		 var options;
       var drawOptions;
		 var srchLine;

		 var $srchQuery = $('div.search_result');
		 var $srchRslt = $('div.listing');
		 //var $gglSrchBar = $('<div></div>').append('body').hide();

		 // if is page "Search"
		 // if( $srchQuery.size() == 1 ){
		 if( $srchQuery.length ){

			 srchLine = $srchQuery.text();

			 //Clear serch result
			 //$srchQuery.html('');
			 //$srchRslt.html('');

			 searchControl = new google.search.SearchControl(); 

			 // Set count results per page 
			 searchControl.setResultSetSize(8);

			 // Set view mode ( tabs \ expand )
			 options = new GsearcherOptions();

			 // Set Expand mode / set root for search results / set result message
			 options.setExpandMode( GSearchControl.EXPAND_MODE_OPEN );
			 //options.setRoot( $srchRslt[0] );
			 options.setNoResultsString("Поиск не дал результатов.")

			 // Add web search & setsearch by current site
			 webSrch = new google.search.WebSearch();
			 webSrch.setSiteRestriction( "actualcomments.ru" ); //location.hostname

			 searchControl.addSearcher( webSrch, options);

			 drawOptions = new GdrawOptions();

			 // set bloc 4 search form 
			 drawOptions.setSearchFormRoot( $srchQuery[0] );//*/$gglSrchBar[0] );

			 // Draw & set bloc 4 search result
			 searchControl.draw( $srchRslt[0] , drawOptions);

          // stretch search bloc
          $('div.listing .gsc-control').css("width", "auto");

/* old search*/
			 // Link to old search
			 $srchQuery.append( "<div id='oldSearchResult'></div>" );
			 searchControl.setSearchCompleteCallback(null, function(_form){ SetOldSearchLink(_form) }   )
/*old search*/

			 searchControl.execute(srchLine);
		 }
   })();

	(function(){
		$('#select_expert_expert_id').change( function(){

			if( $(this).val()=='' )
				$('#div_create_expert').show(500);
			else
				$('#div_create_expert').hide(500);
		});
		$('#select_expert_expert_id').change();
	})();


	// socnet
	(function(){
		var list = [ [ 'a.twitter', 'http://twitter.com/home?status=%title% %url%' ]
			, [ 'a.facebook', 'http://www.facebook.com/sharer.php?u=%url%&t=%title%' ]
			, [ 'a.livejournal', 'http://www.livejournal.com/update.bml?event=%url%&subject=%title%' ]
			, [ 'a.liveinternet', 'http://www.liveinternet.ru/journal_post.php?action=n_add&cntitle=%title%&cnurl=%url%' ]
			, [ 'a.google', 'http://www.google.com/bookmarks/mark?op=edit&bkmk=%url%&title=%title%' ]
			, [ 'a.myspace', 'http://www.myspace.com/Modules/PostTo/Pages/?u=%url%&t=%title%' ]
			, [ 'a.vkontakte', 'http://vkontakte.ru/share.php?url=%url%&title=%title%&image=http://actualcomment.ru/static/i/ac.png' ]
			, [ 'a.odnoklassniki', 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=0&st._surl=%url%' ]
			, [ 'a.mail', 'http://connect.mail.ru/share?share_url=%url%' ]
			, [ 'a.yandex', 'http://zakladki.yandex.ru/newlink.xml?url=%url%' ]
                        , [ 'a.gmail', 'https://mail.google.com/mail/?ui=2&view=cm&fs=1&tf=1&su=&body=%url%' ]
                        , [ 'a.blogger', 'http://www.blogger.com/blog-this.g?t=%title%&u=%url%&n=Актуальные комментарии' ]
		]

		var isUrl = window.location.href;
		var isTitle = window.location.host + ' / ' + $('div.filling h1:first').text();
		var i;

		function Parse(_line){
			return _line.replace('%url%', isUrl).replace('%title%', isTitle)
		};


		for(i=0; i< list.length; i++)
			$( list[i][0] ).attr( 'href', Parse(list[i][1]) ).attr('target', '_blank');

	})();
        (function()
        {
            $('#none').remove();
            var kalendarPop   = $('.kalendarBlockPopup');
            var kalendarDoor  = kalendarPop.find('.kalendarDoor');
            var kalendarBlock = kalendarPop.find('.kalendarBlock');
            var close         = kalendarBlock.find('.close');
            kalendarDoor.click(function()
            {
                
                var th = $('.bor th');
                var $table = kalendarBlock.find('tbody > tr');
                $(th[6]).addClass('weekend');
                $(th[5]).addClass('weekend');
                $.each($table,function(i,element)
                {
                    var tr = $(element).find('td');
                    $(tr[6]).addClass('weekend');
                    $(tr[5]).addClass('weekend');
                });
                
                kalendarBlock.show();
            });
            close.click(function()
            {
                kalendarBlock.hide();
            });
        })();
});
function confirmDelete()
{
    if(confirm('Вы подтверждаете удаление?'))
    {
        return true;
    }
    else
    {
        return false;
    }
}


