
highLht = function(el) {
		if (!el || el.className == 'current') return false;
		var mainNews = $('#main-news')[0];
		var mainText = $('#main-text')[0];
		
		$("#main-news-image")[0].src = el.firstChild.src.replace( "small", "big" );
		$("#title-news")[0].innerHTML = $(el.childNodes.item(1)).text();
		$("#title-news")[0].src = el.src;
		$("#title-news")[0].href = el.href;
		$("#main-news-link")[0].href = el.href;
		$("#subtitle-news")[0].innerHTML = $(el.childNodes.item(2)).text();
		$(".label-location-time")[0].innerHTML = $(el.childNodes.item(3)).text();
		$(".main-news-punct a.current")[0].className = "";
		el.className = 'current';
}

highLht2 = function(el) {
	if (!el || el.className == 'current' || el.childNodes.length < 6) return false;
	var mainNews = $('#main-news')[0];
	var mainText = $('#main-text')[0];
	
	$("#main-news-img")[0].src = $(el).find("img")[0].src.replace( "s.jpg", "xl.jpg" );
	$(".main-mews-link")[0].innerHTML = $(el.childNodes.item(5)).text();
	$(".main-mews-link")[0].src = el.src;
	$(".main-mews-link")[0].href = el.href;
	$("#main-news-link")[0].href = el.href;
	var offset = 3;
	$(".main-mews-type")[0].innerHTML = $(el.childNodes.item(offset)).html();
	$(".main-news-text")[0].innerHTML = $(el.childNodes.item(offset+1)).text();
	$(".logo-plots")[0].href = el.href;
	//$(".main-mews-location")[0].innerHTML = '<a class="play-news" href="'+ el.href + '"></a>' + $(el.childNodes.item(offset+2)).html();
	var theme = $(".main-mews-name")[0];
	if (el.childNodes.length >= (offset+4)) {
		if (!theme) {
			theme = document.createElement("DIV");
			theme.className = "main-mews-name";
			var info = $(".main-news-info")[0];
			info.insertBefore(theme, info.firstChild);
		}
		theme.innerHTML = $(el.childNodes.item(offset+3)).html();
	} else if (theme) {
		theme.parentNode.removeChild(theme);
	}
	
	$(".main-news-tabs a.current")[0].className = "";
	el.className = 'current';
}

check_video = function() {
	if (location.hash.match('#video')) {
		var name = location.hash.replace('#video-','');
		var tabs = $(".main-news-tabs")[0];
		var pos = 0;
		while (pos < tabs.childNodes.length) {
			var el = tabs.childNodes[pos];
			if (el.href.match('/video/' + name + '/')) {
				highLht2(el);
				return;
			}
			pos++;
		}
		var subjects = $(".subjects")[0];
		var subject = $(subjects).find(".subject")[0];
		var subjectLabel = $(subject).find(".subject-label")[0];
		var el;
		if (subjectLabel) {
			el = subjectLabel.nextSibling;
		} else {
			el = $(subject).find("a")[0];
		}
		if (el.href.match('/video/' + name + '/')) {
			return;
		}
		if (tabs.childNodes.length > 0) {
			jQuery.get('/video/' + name + "/data.xml", "", function(xml) {
				var video = $(xml).find('video')[0];
				var id = video.getAttribute('id');
				var title = $(xml).find('longtitle').text();
				var shortTitle = $(xml).find('title')[0].firstChild.nodeValue;
				var subtitle = $(xml).find('subtitle').text();
				var info = $(xml).find('info item:last').text();
				var posted = video.getAttribute('posted');
				posted = posted.substring(0, posted.indexOf(' '));
				var formats = $(xml).find('format');
				var submenu = $(xml).find('submenu')[0];
				var mainmenu = $(xml).find('mainmenu')[0];
				var location = $(xml).find('location')[0];
				var theme = $(xml).find('theme')[0];
				var program = $(xml).find('program')[0];
				/*if (mainmenu.getAttribute('name') == 'news') {*/
					el = tabs.childNodes[tabs.childNodes.length-1];
					//var date = el.firstChild;
					//date.innerHTML = posted;
					//var img = date.nextSibling;
					var img = el.firstChild;
					el.href = "/video/" + name + "/";
					for (var i = 0; i < formats.length; i++) {
						if (formats[i].getAttribute('name') == 's') {
							img.src = $(formats[i]).text();
							break;
						}
					}
					var span = img.nextSibling.nextSibling;
					span.innerHTML = title + '&#160;›';
					span = span.nextSibling;
					if (program) {
						span.innerHTML = "<span style=\"cursor:pointer;\" onclick=\"window.location.href = '/program/" + program.getAttribute('name') + "/';\">"+ program.getAttribute('title')+"</span>"
					} else {
						span.innerHTML = "";
					}
					span = span.nextSibling;
					span.innerHTML = info;
					/*
					span = span.nextSibling;
					var txt = "<span class='date'>" + posted +"</span>" ;
					if (location) {
						txt += "<span class=\"sity\" style=\"cursor:pointer;\" onclick=\"window.location.href = '" + $(location).find('link').text() + "';\">" + $(location).find('title').text() + "</span>";
					}
					span.innerHTML = txt;
					*/
					span = span.nextSibling;
					span.innerHTML = shortTitle + '&#160;›';
					span = span.nextSibling;
					if (span && !theme) {
						span.parentNode.removeChild(span);
					} else if (theme) {
						if (!span) {
							span = document.createElement("DIV");
							span.style.display = 'none';
							el.appendChild(span);
						}
						span.innerHTML = "<span style=\"cursor:pointer;\" onclick=\"window.location.href = '" + $(theme).find('link').text() + "';\">" + $(theme).find('title').text() + "</span>";
					}
					highLht2(el);
				/*} else {
					var allSub = $(subject).find(".all-sub")[0];
					var subLink = $(subject).find(".sub-link")[0];
					var subjects = $(subjects).find(".subject-min");
					if (subjects.length > 1) {
						var last;
						for (var i = 0; i < subjects.length; i++) {
							last = subjects[i];
							if (last.childNodes[4].href.match('/video/' + name + '/')) {
								break;
							}
						}
						var a = last.childNodes[4];
						a.href = el.href;
						var span = a.firstChild;
						span.innerHTML = "<span>" + subLink.firstChild.innerHTML + "</span>"+ "<p>" + allSub.innerHTML + "</p>";
						var imgBig = subLink.nextSibling.firstChild;
						var img = span.nextSibling;
						img.src = imgBig.src.replace( "l.jpg", "sm.jpg" );
						var parent = last.parentNode;
						if (last != subjects[0]) {
							parent.removeChild(last);
							parent.insertBefore(last, subjects[0]);
						}
						if (subjectLabel && !program) {
							subject.removeChild(subjectLabel);
						} else if (program) {
							if (!subjectLabel) {
								subjectLabel = document.createElement("DIV");
								subjectLabel.className = 'subject-label';
								subject.insertBefore(subjectLabel, el);
							} 
							subjectLabel.innerHTML = "<a href=\"" +  $(program).find('link').text() + "/\">" +  $(program).find('title').text() + "</a>";
						}
						el.href = '/video/' + name + '/';
						el.name = 'video-' + name;
						span = subLink.firstChild;
						span.innerHTML = shortTitle + '&#160;›';
						allSub.innerHTML = subtitle + '&#160;›';
						for (var i = 0; i < formats.length; i++) {
							if (formats[i].getAttribute('name') == 'l') {
								imgBig.src = $(formats[i]).text();
								break;
							}
						}
					}
				}*/
			});
		}
	}		
}

switch_recommend = function(el){
	lock_popular();
	if( !isDynamic ){
		ajaxGetFile(el, "inc/popularTimelineAjax_view_null_recommend.xml" ); 
	} else {
		ajaxGet(el, 'recommend', 'typeFor=recommend'); 
	}
	setClassLink( this );
}

switch_recommend_color = function(){
	$( ".link-recommend" )[0].style.background = "#DE0034";
	$( ".link-recommend" )[0].style.color = "#FFFFFF";
	$( ".link-popular" )[0].style.background = "#FFFFFF";
	$( ".link-popular" )[0].style.color = "#000000";
	$( ".period" )[0].style.display = "none";
	
	$( ".pop-container .ad-gallery .ad-back" )[0].style.background = "transparent url(/images/list-left.gif) no-repeat scroll left bottom";
	$( ".pop-container .ad-gallery .ad-forward" )[0].style.background = "transparent url(/images/list-right.gif) no-repeat scroll left bottom";
}

switch_popular = function(el){
	lock_popular();
	if( !isDynamic ){
		ajaxGetFile(el, "inc/popularTimelineAjax_view_null_week.xml" ); 
	} else {
		ajaxGet(el, "week", 'typeFor=week' ); 
	}
	$("#link-week")[0].className = "current";
	return false;
}

switch_popular_color = function(){
	$( ".link-popular" )[0].style.background = "#DE0034";
	$( ".link-popular" )[0].style.color = "#FFFFFF";
	$( ".link-recommend" )[0].style.background = "#FFFFFF";
	$( ".link-recommend" )[0].style.color = "#000000";
	$( ".period" )[0].style.display = "";
	
	$( ".pop-container .ad-gallery .ad-back" )[0].style.background = "transparent url(/images/list-left.gif) no-repeat scroll left bottom";
	$( ".pop-container .ad-gallery .ad-forward" )[0].style.background = "transparent url(/images/list-right.gif) no-repeat scroll left bottom";
}

lock_popular = function(){
	var absolute=document.createElement('DIV');
    absolute.className='shading-glass png-scale';
    absolute.id = "shading-glass"
    absolute.innerHTML='<div class="shading-glass-one"></div><div class="shading-glass-two"><span class="shading-glass-three"></span></div>';
    $( "#container" )[0].appendChild(absolute);
}

setClassLink = function(obj) {
	$("#link-all-time")[0].className = "";
	$("#link-month")[0].className = "";
	$("#link-week")[0].className = "";
	obj.className = "current";
}

showPersons = function( id ){
	if( $( '#hiddenPersons' + id )[0].style.display == "" ){
		$( '#hiddenPersons' + id ).hide(500);
	} else {
		$( '#hiddenPersons' + id ).show(500);
		$( '#hiddenPersons' + id )[0].style.display = "";
	}
}

showPrograms = function(id)
{
	if($('#hiddenPrograms_' + id )[0].style.display == "none")
	{
		$('#hiddenPrograms_' + $('a.current_order').attr('id')).hide(500);
		$('#hiddenPrograms_' + id).show(500);
		//$('#hiddenPrograms_' + id)[0].style.display = "";
		//$('#hiddenPrograms_' + $('a.current_order').attr('id'))[0].style.display = "none";
		$('a.current_order').removeClass('current_order')
		$('#' + id).addClass('current_order');
	} 
}

isNewsPopular = function( obj ){
	if( isDynamic ){
		return "";
	} else {
		return "null";
	}
}

setIsNewsDefault = function(){
	$(".popular .types-video .type-video.current")[0].className = "type-video";
	$("#isNewsDefault")[0].className = "type-video current";
}

switchTypeVideoRightPop = function( obj ){
	if( !isDynamic ){
		ajaxGetFile(obj, "inc/popular_" + isNewsPopularRightPop( obj ) + "_" + $(".right-video .links a.current")[0].getAttribute( "type" ) + ".xml" ); 
	} else {
		ajaxGet(obj, 'switchType', isNewsPopularRightPop( obj ) + "typeFor=" + $(".right-video .links a.current")[0].getAttribute( "type" ) );
	}
	
	$('.types-video-right-video .type-video.current')[0].className = "type-video";
	obj.className = "type-video current";
}
switchPeriodVideo = function( obj, period ){
	lock_popular(); 
	
	if( !isDynamic ){
		ajaxGetFile(obj, "inc/popularTimelineAjax_view_" + isNewsPopular(null) + "_" + period + ".xml" ); 
	} else {
		ajaxGet(obj, period, isNewsPopular( null ) + 'typeFor=' + period ); 
	}
	setClassLink( this ); 
}

isNewsPopularRightPop = function( obj ){
	if( isDynamic ){
		return "";
	} else {
		return "null";
	}
}

switchPeriodRight = function( period, obj ){
	if( isDynamic ){
		ajaxGet(obj, period, isNewsPopularRightPop() + 'typeFor=' + period );
	} else {
		ajaxGetFile( obj, 'inc/popular_' + isNewsPopularRightPop() + "_" + period + ".xml" ) ;
	}
}

// ------------------ AJAX REQUEST (METHOD GET)) ----------------
function ajaxGet(element,action) {
	var parameters=ptlFormSerialize(element);
    for(var i=2; i<arguments.length; i++) {
        parameters = parameters + '&' + arguments[i];
    }
    var url = (element.tagName.toLowerCase() == "form") ? element.action : undefined;
    ajaxWithoutFormGet(action,parameters, url, null)
    return false;
}

function ajaxGetFile(element,file) {
    var parameters=ptlFormSerialize(element);
    for(var i=2; i<arguments.length; i++) {
        parameters = parameters + '&' + arguments[i];
    }
    var url = (element.tagName.toLowerCase() == "form") ? element.action : undefined;
    ajaxWithoutFormGet(file,parameters, url, file)
    return false;
}

function ajaxWithoutFormGet(action,parameters,url, file) {
   
	if(arguments.length ==1) parameters="";
    if (!url) {
    	url=window.location.href;
    }

    if(parameters.substring(0,1)!='&') parameters='&'+parameters;

    var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    var param;
    if( file != null ){ 
    	urlArr = url.split( "/" );
    	url = urlArr[0] + "//" + urlArr[2] + "/";
    	param = file;
    } else {
    	param = "?ptl-ajax=true&ptl-action=" + action + parameters;
    }

    
    request.open("GET", url + param, true);
    request.onreadystatechange = ptlCallback.bind(request);
    request.send( null );
   
    if (window.ptlAjaxCallInitiated) {
        window.ptlAjaxCallInitiated();
    }

    return false;

}

insertAppendToAnotherApplecationsBlock = function(){
	var title = document.title;
	var link = document.location.href;
	var idx = link.indexOf('?');
	if (idx > 0) {
		link = link.substring(0, idx);
	}
	if( link[link.length-1] == "/" ){
		link = link.substring(0, link.length-1);
	}
	
	var textElement = jQuery(".path-link");
	textElement.append(jQuery("#append-other-applecations").html());
	jQuery("#append-other-applecations").html( "" );
	$(document).ready( function(){
		createLinksForAppendOtherApplecations( link, title );
	});
	var inPopup = false;
	jQuery(".append-all-app").hover( function( e ){
		inPopup = true;
		jQuery(".app-popup").show();
		return false;
	}, function(){
		inPopup = false;
	    setTimeout(function () { if (!inPopup) jQuery(".app-popup").hide(); }, 1000);
	});
	jQuery(".app-popup").hover( function( e ){
		inPopup = true;
		jQuery(this).show();
		return false;
	}, function(){
		inPopup = false;
		var app = jQuery(this);
	    setTimeout(function () { if (!inPopup) app.hide(); }, 1000);
	});
	
}

var Url = {
		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
		},
	 
		// public method for url decoding
		decode : function (string) {
			return this._utf8_decode(unescape(string));
		},
	 
		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		},
	 
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
	 
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
	 
			}
	 
			return string;
		}
	 
	};
createLinksForAppendOtherApplecations = function( link, title ){
	var escapeLink = escape(link);
	var escapeTitle = Url.encode(title);
	var nameVideo = link.match( /\/video\/(.*[^\/#?])/ )[1];
	var codeBlog = "<embed name='playerblog' src='http://www.russia.ru/player/main.swf?103' flashvars='name=" + nameVideo + "&from=blog&blog=true' width='448' height='252' bgcolor='#000000' allowScriptAccess='always' allowFullScreen='true'></embed>";
	
	appendToYoutube = function( obj ){
		$(obj).click( function(){
			$.ajax({
	            type: "POST",
	            url: "/append_to_youtube",
	            data: {videoName: nameVideo, action: "auth"},
	            timeout: 30000,
	            success: function( xml ){
	            	var url = $(xml).find("url").text();
	            	window.location.href = url; 
	            }
	        });
			return false;
		});
	}
	if( window.location.href.indexOf( "from=youtube" ) >= 0 ){
		$(".append-other-applecations").hide();
		$(".progress-bar-youtube").show();
			$.ajax({
	            type: "POST",
	            url: "/append_to_youtube",
	            data: {videoName: nameVideo, action: "start_upload"},
	            timeout: 30000,
	            success: function(xml){
	            	if ($(xml).find("result").text() == "true") {
	            		var parent = $(".progress-bar-youtube");
	            		var w = 0;
		            	$(document).everyTime(1000, "", function() {
		            		$.ajax({
		        	            type: "POST",
		        	            url: "/append_to_youtube",
		        	            data: {videoName: nameVideo, action: "progress"},
		        	            timeout: 30000,
		        	            success: function(xml){
		        	            	var progress = $(xml).find("progress").text();
		        	            	if (progress == "100") {
		        	            		document.location.href = link;
		        	            	}
		        	            	w = (w + 1) % 77;
		        	            	//var w = 76 * 100 / progress;
		        	            	parent.find(".progress").css({width: w});
		        	            }
		            		})
		            	});
	            	} else {
	            		window.location.href = link;
	            	}
	            }
	        });
			return false;
	}
	
	jQuery(".app-popup").find("a").each( function(){
		var app = jQuery(this);
		if( app.hasClass("blogger") ){
			app.attr( "href", "http://www.blogger.com/blog_this.pyra?t&a=ADD_SERVICE_FLAG&passive=true&alinsu=0&aplinsu=0&alwf=true&hl=ru&skipvpage=true&rm=false&showra=1&fpui=2&naui=8&u=" + escapeLink + "&n=" + escapeTitle );
		} else if( app.hasClass("twitter") ){
			app.attr( "href", "http://twitter.com/home?status=" + escapeTitle + " " + escapeLink );
		} else if( app.hasClass("google") ){
			escapeTitleGoogle = Url.encode( shorter( $.trim($(".description").text()), 87 ) );
			app.attr( "href", "http://www.google.com/buzz/post?message=" + escapeTitleGoogle + "&url=" +  escapeLink);
		} else if( app.hasClass("gmail") ){
			app.attr( "href", "https://mail.google.com/mail/?view=cm&fs=1&to&ui=2&tf=1&shva=1&su=" + escapeTitle + "&body=" + escapeLink );
		} else if( app.hasClass("livejournal") ){
			if( !jQuery.browser.msie ){
				var form = jQuery("<form style='display:none' accept-charset='UTF-8' action='http://www.livejournal.com/update.bml' method='POST'><input type='hidden' name='subject' value='" + title + "'/><textarea name='event'>" + codeBlog + "</textarea></form>");
				app.after(form);
				app.click(function() {
					form.submit();
					return false; 
				});
			}
			app.attr( "href", "http://www.livejournal.com/update.bml?subject=" + escapeTitle + "&event=" + escapeLink );
		} else if( app.hasClass("liveinternet") ){
			app.attr( "href", "http://www.liveinternet.ru/journal_post.php?action=n_add&cntitle=" + escapeTitle + "&cnurl=" + escapeLink );
		} else if( app.hasClass("facebook") ){
			app.attr( "href", "http://www.facebook.com/share.php?u=" + escapeLink );
		} else if( app.hasClass("myspace") ){
			app.attr( "href", "https://secure.myspace.com/index.cfm?fuseaction=login.simpleform&featureName=postToV3&dest=" + escapeLink );
		} else if( app.hasClass("mailru") ){
			app.attr( "href", "http://connect.mail.ru/share?share_url=" + escapeLink );
		} else if( app.hasClass("youtube") ){
			appendToYoutube( this );
			return false;
		}
	} );
	jQuery(".append .app.big-livejournal").each( function(){
		if( !jQuery.browser.msie ){
			var form = jQuery("<form style='display:none' accept-charset='UTF-8' action='http://www.livejournal.com/update.bml' method='POST'><input type='hidden' name='subject' value='" + title + "'/><textarea name='event'>" + codeBlog + "</textarea></form>");
			jQuery(this).after(form);
			jQuery(this).click(function() {
				form.submit();
				return false;
			});
			return false;
		}
		jQuery(this).attr( "href", "http://www.livejournal.com/update.bml?subject=" + escapeTitle + "&event=" + escapeLink );
	} );
	
	jQuery(".append .app.big-twitter").each( function(){
		jQuery(this).attr( "href", "http://twitter.com/home?status=" + escapeTitle + " " + escapeLink );
		return false;
	} );
	
	jQuery(".append .app.big-vkontakte").click( function(){
		VK.Share.click(0);
		return false;
	} );
	jQuery(".append .app.big-facebook").each( function(){
		jQuery(this).attr( "href", "http://www.facebook.com/share.php?u=" + escapeLink );
		return false;
	} );
	jQuery(".append  .app.big-youtube").each( function(){
		appendToYoutube( this );
		return false;
	} );
	jQuery(".append .app.big-vkontakte").each( function(){
		jQuery(this).append( 
			VK.Share.button( 
					{image : $("meta[property=og:image]").attr("content"), description : shorter( $.trim($(".description").text()), 87 ) },
					{type: "link_noicon", text: " " } )
		);
		return false;
	} );
	jQuery(".action.print").click( function(){
		location.href = link.replace("html", "print.html");
		return false;
	} );
	
}
	
shorter = function( str, count ){
	count -= 3;
	var words = str.split( " " );
	var strShort = "";
	var i = 0;
	for( j = 0; j < words.length; j++){
		var word = words[j];
		if( strShort.length + word.length < count ){
			strShort += word;
			i++;
			
			if(i < words.length && strShort.length + words[i].length < count ){
				strShort += " ";
			} else if(i < words.length && word.match("\\W*") ){
				strShort += "...";
				break;
			} else {
				break;
			}
		}
	}
	return strShort;	
}

function init() {
	$(".top-menu").mouseover(function(){
		 var isIE = navigator.appName.indexOf("Microsoft") != -1;   
	     var flash = (isIE) ? window["altContent"] : document["altContent"];  
	     flash.sendTextToFlash("qqq1");     
	});
	$(".tv-punts .tv-news").mouseover(function() {
		$(".tv-punts .tv-news.current").removeClass("current");
		var link = $(this);
		link.addClass("current");
		var main = $(".main-tv-block .tv-block");
		var img = link.find("img");
		var href = link.attr("href");
		main.find("a:not(.all)").each(function(){ this.href = href;});
		main.find("img").each(function() {
			this.src = img.attr("src").replace( "stv.jpg", "xl.jpg" );
			
		});
		var title = link.find("p");
		var program = title.next();
		var subtitle = program.next();
		var shortTitle = subtitle.next();
		var theme = shortTitle.next();
		main.find(".tv-name").each(function(){
			$(this).html(program.html());
		})
		main.find(".tv-about h2").each(function() { $(this).html(shortTitle.html() );});
		main.find(".tv-about p").each(function() { $(this).html(subtitle.html() );});
	});	
	$(".login input[name=lb_login]").focus();
}
$(init)
