/**
	General slider
*/
$.fn.slider = function(options) {
    var settings = $.extend({},{speed:300,size:1,scroll:1,slideToActive:false,direction:'left',leftArrowCallback:false,        rightArrowCallback:false}, options);
    return this.each(function() {
            var container = $(this),ul = $(".slider-inner ul",container),nr = $("li",ul).size(),sliderDim = 0;
            if (settings.direction == 'left') {paddinga = 'padding-left';paddingb = 'padding-right';} 
			else {paddinga = 'padding-top';paddingb = 'padding-bottom';}
            $("li:first",ul).addClass("current");
            $("li",ul).each(function() {sliderDim += sliderItemSize($(this),settings);});
            if (settings.direction == 'left') {ul.width(sliderDim).css(settings.direction,"0");} 
			else {ul.height(sliderDim).css(settings.direction,"0");}	
            if (nr>1) {
                    var curItem = $("li",ul).index($("li.current"));
					$(".prev-active",container)
						.removeClass("prev-active")
						.addClass("prev-inactive");						
                    if (nr > settings.size) {
						$(".next-inactive",container)
							.removeClass("next-inactive")
							.addClass("next-active");
					}	
                    $(".next",container).click(function(event) {
                            sliderMoveForward(container,settings);
                            event.stopImmediatePropagation();
                    });
                    $(".prev",container).click(function(event) {
                            sliderMoveBackward(container,settings);
                            event.stopImmediatePropagation();
                    });
            }
    });
}

function sliderItemSize(element,settings) {
    var size = settings.direction == 'left' ? element.width() : element.height();
    return size + parseInt(element.css(paddingb)) + parseInt(element.css(paddinga));
}
function sliderCheckNavigation(nav,curItem,last,settings) {	
    if (curItem == 0) {
		nav.find(".prev").removeClass("prev-active").addClass("prev-inactive");		
	} else {
		nav.find(".prev").removeClass("prev-inactive").addClass("prev-active");		
	}	
    if (curItem == last) {
		nav.find(".next").removeClass("next-active").addClass("next-inactive");
	} else {
		nav.find(".next").removeClass("next-inactive").addClass("next-active");
	}	
}

function sliderMoveForward(container,settings) {
    var ul = $(".slider-inner ul",container),
            nr = $("li",ul).size(),
            last = nr - settings.size,
            scroll = settings.scroll,
            curItem = $("li",ul).index($("li.current")),
            poz = parseInt(ul.css(settings.direction));

            if(ul.is(':not(":animated")') && curItem < last) {
                    if (curItem + scroll > last) scroll = last - curItem;
                    itemDim = sliderItemSize($("li:eq(" + curItem + ")",ul),settings);
                    css = (settings.direction == 'left') ? {left: poz - scroll * itemDim} : {top: poz - scroll * itemDim};
                    curItem += scroll;
                    $("li.current",ul).removeClass("current");
                    $("li:eq(" + curItem + ")",ul).addClass("current");
                    ul.animate(css,settings.speed,"linear");
					//Don't wait the slider to finish the animation, change the navigation buttons
					sliderCheckNavigation(container,curItem,last,settings);
                    if ($.isFunction(settings.rightArrowCallback)) {settings.rightArrowCallback.call(this);}
            }
}
function sliderMoveBackward(container,settings) {
    var ul = $(".slider-inner ul",container),
            nr = $("li",ul).size(),
            last = nr - settings.size,
            scroll = settings.scroll,
            curItem = $("li",ul).index($("li.current")),
            poz = parseInt(ul.css(settings.direction));

            if(ul.is(':not(":animated")') && poz != 0) {
                    if (curItem - scroll < 0) scroll = curItem;
                    curItem -= scroll;
                    itemDim = sliderItemSize($("li:eq(" + curItem + ")",ul),settings);
                    css = (settings.direction == 'left') ? {left: poz + scroll * itemDim} : {top: poz + scroll * itemDim};
                    $("li.current",ul).removeClass("current");
                    $("li:eq(" + curItem + ")",ul).addClass("current");
                    ul.animate(css,settings.speed,"linear");
					//Don't wait the slider to finish the animation, change the navigation buttons
					sliderCheckNavigation(container,curItem,last,settings);
                    if ($.isFunction(settings.rightArrowCallback)) {settings.rightArrowCallback.call(this);}
            }
}
$.slider = {
	moveForward : function(element, settings) {sliderMoveForward(element,settings);},
	moveBackward : function(element, settings) {sliderMoveBackward(element,settings);}
};

/**
	General hover slider
*/
function sliderMove(sliderID,wrapperDim,sliderDim,sdirection,speed) {	
	var slider = $("#slider-" + sliderID),poz = parseInt(slider.css("left")),absPoz = Math.abs(poz),container = slider.parents(".media-sliderWrapper"),prev = container.find(".prev"),next = container.find(".next"),sw = sliderDim - wrapperDim,rightSD = sw - absPoz,scroll = 0;	
		
	switch (sdirection) {
		case "forward":			
			prev.removeClass("prev-inactive").addClass("prev-active");
			scroll = -20;									
			if (rightSD < Math.abs(scroll)) {
				scroll = 0 - rightSD;
			} else if (Math.abs(poz) == sw) {
				next.removeClass("next-active").addClass("next-inactive");
				return;			
			}							
			break;
		case "backward":			
			next.removeClass("next-inactive").addClass("next-active");			
			if (poz >= 0) {
				prev.removeClass("prev-active").addClass("prev-inactive");
				return;
			}	
			if (absPoz < 20) scroll = absPoz;
			else scroll = 20;			
			break;
	}
	if (slider.is(':not(":animated")')) {		
		slider.animate({left:poz + scroll},80,"linear");	
	}		
}

$.fn.hoverSlider = function(options) {	
	function getSize(element) {
		size = element.width();
		return size + parseInt(element.css("padding-left")) + parseInt(element.css("padding-right"))
	}
	
	return this.each(function() {
		var container = $(this),ul = $(".slider-inner ul",container),id = ul.attr("id").replace("slider-",""),sliderDim = 0,wrapperDim = $(".slider-inner",container).width(),moveID = 0;
		
		$("li",ul).each(function() {sliderDim += getSize($(this));});			
		ul.width(sliderDim);			
			
		if ($("li",ul).size() > 1) {
			if (sliderDim > wrapperDim) {
				$(".next-inactive",container).removeClass("next-inactive").addClass("next-active");
							
				$(".next",container).hover(
					function() {moveID = setInterval('sliderMove("'+id+'","'+wrapperDim+'","'+sliderDim+'","forward")',10);},
					function() {clearTimeout(moveID);}
				);
				$(".prev",container).hover(
					function() {moveID = setInterval('sliderMove('+id+',"'+wrapperDim+'","'+sliderDim+'","backward")',10);},
					function() {clearTimeout(moveID);}
				);
			}	
		}	
	});	
};

/**
	Media slider + Preview
*/
$.fn.mediaSlider = function(options) {
	var settings = $.extend({},{			
			offsetDIV: ".media-single"//The document will scrollTop to this div in order to have a better view of the gallery
		}, options);
	
	//Calculate navigation buttons' width
	function calculateNavWidth(preview,itemNav,index) {
		var curImgW = $("img:eq(" + index + ")",preview).width() + 2;
			
		if (itemNav.length) {
			itemNav.width(function() {
				var prevW = preview.width();				
				return Math.round((prevW - curImgW) / 2);
			});
		}
	}	
	
	return this.each(function() {			
		var $this = $(this),container = $(".media-sliderWrapper",this),preview = $(".media-item",this),count = $(".number .count",this),itemNav = $(".item-navigation",preview),singleNav = $(".single-navigation",preview),mdata = '';
		
		container.hoverSlider();

		if ($(".media-data",this).length) mdata = $(".media-data",this);
		if ($(".gallery-description",this).length) mdata = $(".gallery-description",this);
		
		$("img",preview).each(function() {
			var img = $(this);
			img.css({"visibility":"hidden","display":"block"});	
			img.css("top",parseInt((preview.height() - img.attr("height")) / 2) + "px");
			img.css({"visibility":"visible","display":"none"});	
		});		
		
		$("img:first",preview).addClass("active").show();
		if ($(".image-description",mdata).length) {
			$(".image-description:first").show();
		}
		if ($(".imgSource",mdata).length) {
			$(".imgSource:first").show();
		}		
		
		calculateNavWidth(preview,itemNav,0);
		
		//Slider click
		$("li img",container).click(function(event) {					
			var topOffset = $this.find(settings.offsetDIV).offset() || $this.parents(".content-borderBox").offset(),
				index = $("li img",container).index($(this)),
				curImg = $("img:eq(" + index + ")",preview);
			
			//Jump to the top
			$(document).scrollTop(topOffset.top);
			//Change image count
			if (count.length) count.text(index+1);			
			//Active new item			
			$("img.active",preview).hide().removeClass("active");
			curImg.addClass("active").show();
			//Calculate navigation buttons' width			
			calculateNavWidth(preview,itemNav,index);			
			//Hide the first/last single navigation
			if (singleNav.length) {
				$(".single-next").show();
				$(".single-prev").show();
				if (index == $("img",preview).length - 1) $(".single-next").hide();
				if (index == 0) $(".single-prev").hide();
			}
			//Show/Hide the item description
			if ($(".image-description",mdata).length) {
				$(mdata)
					.find(".image-description")
					.hide()
					.end()
					.find(".image-description:eq("+index+")")
					.show();	
			}	
			if ($(".imgSource",mdata).length) {
				$(mdata)
					.find(".imgSource")
					.hide()
					.end()
					.find(".imgSource:eq("+index+")")
					.show();	
			}	
			event.preventDefault();
		});	
		
		//Remove preview navigation for only one photo 
		if ($("img",preview).length < 2) singleNav.remove();		
				
		//Item/Single navigation click
		if (itemNav.length || singleNav.length) {
			var isNav = itemNav.length ? $("div",itemNav) : $("span",singleNav);
			
			isNav.click(function() {
				if (itemNav.length) {
					var isPrev = $(this).parent().hasClass("prev") ? true : false,
						isNext = $(this).parent().hasClass("next") ? true : false;
				} else {
					var isPrev = $(this).parent().hasClass("single-prev") ? true : false,
						isNext = $(this).parent().hasClass("single-next") ? true : false;
				}				
					
				var poz = $("img",preview).index($("img.active",preview)),
					imgCount = $("img",preview).length;
				
				
				if (isPrev) {
					poz--;
					if (poz < 0) poz = imgCount - 1;
				}
				if (isNext) {
					poz++;				
					if (poz >= imgCount) poz = 0;				
				}			
				$("li:eq("+poz+") img",container).trigger("click");
			});
		}	
	});	
}

/**
	Bar rating
*/	
$.fn.rating = function(options) {
	var settings = $.extend({},{url : ''}, options);
		
	return this.each(function() {
		var $this = $(this),contWidth = $this.find(".bar").width(),bar = $this.find(".hover"),avg = $this.find(".default"),barInner = $this.find(".bar-inner"),outerOffset = $this.find(".bar").offset(),text = $("#vote-msg"),rel = barInner.attr("rel").split("|");
		
		barInner.hover(
			function() {				
				var ePos = 0;
				$(this).mousemove(function(e) {					
					if (e.pageX != ePos) {
						ePos = e.pageX;	
						bLength = e.pageX - outerOffset.left;	
						bar.width(bLength);
						
						$(this).click(function(ee) {
							var value = Math.floor( (bLength * 100) / contWidth );
							
							if (settings.url != '') {
								var v1 = (rel[0])?rel[0]:'',
									v2 = (rel[1])?rel[1]:'';								
								$.post(settings.url,{vot:value,table:v1,uid:v2}, function(a) {
									var a = JSON.parse(a);
									
									if (a.response == "success") {		
										text.html(a.text);
										bar.width(0);
										avg.width( (a.avg * contWidth) / 100 );			
										barInner.unbind();
									} else {
										text.html("<span class='red'>" + a.text + "</span>");
									}								
								});
							} else barInner.unbind();
							
							ee.stopImmediatePropagation();
						});
					}					
				});
			},
			function() {bar.width(0);}
		);
	});
}

/**
	Autoclear inputs' default value
*/	
$.fn.inputAutoClear = function() {	
	return this.each(function() {
		var $this = $(this),alt = $this.attr("alt"),val = $this.val() ? $this.val() : alt; 

		if (alt != '') {
			$this.val(val);
			$this.bind("focus",function() {
				if ($this.val() == alt) $this.val('');
			});
			$this.bind("blur",function() {
				if ($this.val() == '') $this.val(alt);
			});
		}
	});
}

/**
	Creates clickable tabbed content
*/
$.fn.tabs = function() {
	return this.each(function() {
		var $this = this,ul = $("ul.tabs-navigation",this),div = $("div.tabs-contentWrapper",this);
		
		ul.find("> li").each(function() {
			$(this).click(function() {
				ul.find("> li.active").removeAttr("class");
				$(this).addClass("active");
				div.find("> div.active").removeClass("active");				
				div.find("> div.tab-content:eq(" + ul.find("> li").index(this) + ")").addClass("active");
			});
		});
	});
}

/**
	Creates hoverable tabbed content
*/
$.fn.hoverTabs = function() {
	return this.each(function() {
		var $this = this,ul = $("ul.tabs-navigation",this),div = $("div.tabs-contentWrapper",this);
		
		ul.find("> li").each(function() {
			$(this).hover(
				function() {
					ul.find("> li.active").removeAttr("class");
					$(this).addClass("active");
					div.find("> div.active").removeClass("active");				
					div.find("> div.tab-content:eq(" + ul.find("> li").index(this) + ")").addClass("active");
				}),
				function() {/*do nothing*/}
		});
	});
}

/**
	Creates clickable tabbed ajax based content
*/
$.fn.ajaxTabs = function(options) {
	var settings = $.extend({},{onComplete: ''}, options);
	
	return this.each(function() {
		var $this = this,ul = $("ul.tabs-navigation",this),div = $("div.tabs-contentWrapper",this);
		
		ul.find("> li").each(function() {
			$(this).click(function(e) {				
				ul.find("> li.active").removeAttr("class");
				var selectedDiv = div.find("> div.tab-content:eq(" + ul.find("> li").index(this) + ")"),
					action = selectedDiv.attr('rel'),
					divEmpty = (selectedDiv.html().length)? false : true;
				
				$(this).addClass("active");
				div.find("> div.active").removeClass("active");				
				if (divEmpty) {
					selectedDiv.html("<p class='loader' />");
					selectedDiv.addClass("active");
					//var currentUrl = document.location.href;
					var currentUrl = 'http://www.libertatea.ro';
					if (currentUrl.indexOf('#') > 0) {
						currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
					}
					if(document.location.hostname!='www.libertatea.ro' && document.location.hostname!='libertatea.ro') {
						var currentUrlInfo = currentUrl.split('www.libertatea.ro'); 
						if(currentUrlInfo.length >1) {
							currentUrlParts = currentUrlInfo[1].split('%2F');
							currentUrl = currentUrlParts.join('/');
							currentUrl = 'http://www.libertatea.ro' + currentUrl;
						}
					}
					if(currentUrl.indexOf('?')!=-1)
						currentUrl += "&"+settings.data + action;
					else 
						currentUrl += "?"+settings.data + action;
					$.ajax({
						url: currentUrl,
						cache: true,
						type: "GET",
						success: function(html){
							selectedDiv.html(html);		
							if ($.isFunction(settings.onComplete)) {
								settings.onComplete.call(this);
							}		
						}
					});				
				}
				else {
					selectedDiv.addClass("active");
				}
				e.preventDefault();				
			});
		});
		if (settings.trigger == 1) {
		$("li:first",this).trigger('click');
		} else {
			$("li:first",this).addClass('active');
			$('.tab-content:first',div).addClass('active');
		}
	});
}

/**
	Adds/removes a large preloder
	
	loaderPos : the position of the animated loader image within the container - top or auto (default)
*/
var preloader = {	
	preloaderWrapper: "preloader-wrapper",
	preloaderLoader: "preloader",
	preloaderHtml: "<div class='preloader-wrapper'></div><span class='preloader'></span>",
	add : function() {
                if (arguments.length) {
                    element = arguments[0];
                    if(typeof arguments[1] !== 'undefined') loaderPos = arguments[1];
                        else loaderPos = "";                    
                }
                var element = $(element),
                    elementDim = {
                                height: element.height() + parseInt(element.css("padding-top")) + parseInt(element.css("padding-bottom")),
                                width: element.width() + parseInt(element.css("padding-left")) + parseInt(element.css("padding-right"))
                        };
                element.append(this.preloaderHtml);
                
				var loader = element.find("." + this.preloaderLoader),
                    loaderCenter = {
                            left: parseInt((elementDim.width - loader.width()) / 2),
                            top: parseInt((elementDim.height - loader.height()) / 2)
                    };                
                
                element
                        .find("." + this.preloaderWrapper)
                        .css({
                                opacity: 0.8,
                                height: elementDim.height,
                                width: elementDim.width
                        });

                switch (loaderPos) {
                        case "top":
                                loader.css({
                                        top: "20px",
                                        left: loaderCenter.left + "px"
                                });
                                break;
                        case "auto":
                        default:
                                loader.css({
                                        top: loaderCenter.top + "px",
                                        left: loaderCenter.left + "px"
                                });
                                break;
                }
	},
	remove : function(element) {
		$(element).find("." + this.preloaderWrapper).remove();
		$(element).find("." + this.preloaderLoader).remove();
	}
}

/**
	File upload in popups
*/

popFileUpload = {
	v: new Array(),
	ajaxLoader: function(id) {
		$("#fileButton-" + id).after("<span class='loader'></span>");	
	},
	removeAjaxLoader: function() {
		$(".loader").remove();
	},
	msgDisplay: function(type,text,id) {
		if (type == 'error') {
			if (!$("#file-msg-"+id).length) $(".uploaded").before("<p id='file-msg-"+id+"'></p>"); 		
			$("#file-msg-"+id).attr("class",type).html("<span>" + text + "</span>");
			if (type == 'error') {
				setTimeout(function() { $("#file-msg-"+id+" span").fadeOut(function() {$("#file-msg-"+id).remove();resizeFancyBox(1);})}, 4000);
			} else {
				//setTimeout(function() { $("#file-msg-"+id+" span").fadeOut(function() {$("#file-msg-"+id).remove();resizeFancyBox(1);})}, 1000);
			}
		}
	},
	msgRemove: function(id) {
		$("#file-msg-"+id+" span").remove();
	},
	fileUpload: function(options) {
		var allowed = options.allowed_ext;
		
		this.v[options.id] = new AjaxUpload(options.button, {
			action: options.action,
			name: options.input_name,
			data: options.data,
			onSubmit : function(file, ext){
				popFileUpload.msgRemove(options.id);
				popFileUpload.ajaxLoader(options.id);			
				this.disable();
				if (allowed) {
					if (!ext || !allowed.test(ext)){
						popFileUpload.msgDisplay("error",options.error_ext_text,options.id);
						popFileUpload.removeAjaxLoader();
						return false;
					}
				}				
			},
			onComplete: function(file, response){				
				var r = json_parse(response),				
				status = r.response;
				this.enable();
				popFileUpload.removeAjaxLoader();				
				if (status == 'success') {				
					if ($.isFunction(options.whenSuccess)) options.whenSuccess.call(this,r);
				}

				if (status == 'failure') {						
					if (r.message && $.isFunction(options.whenError)) {
						options.whenError.call(this,r);
					}
				}
			}
		});	
	}
};
/*****/
$(document).ready(function() {
	fixArticleVideo();
	listlastitem();	
	/*breakingNews();*/
	/*homeSlider();*/
	topicPageFotoSlider();		
	articleSlider();
	articleRelatedSlider();
	articleHeaderNews();    
	fixFooter();	
	load_votes();	
	
	/*Change font size*/
	$(".article .font a").click(function() {fontSize();});
	$("#signDetails .font a").click(function() {fontSize("#signDetails .text .content");});
	$(".compatibility-text .font a").click(function() {fontSize(".compatibility-text .text p:not('.article-infoBox p')");});
	
	/*Music player vertical align*/
	if ($("#home #musicplayer").length) {
		var mp = $("#home #musicplayer"),mpe = $("#home #musicplayer embed");					
		mpe.css({"margin-top": function() {return Math.round((mp.height() - mpe.height()) / 2) + "px";}});
	}
	
	/*Channel menu*/
	$("#channel-menu li:not('.empty')").hover(
		function() {						
			if ($.browser.msie && $.browser.version <= 6) {
				var cl = $(this).attr("class").replace(" active","") + "-hover";				
				$(this).addClass(cl);								
			} else {
				$(this).addClass("hover");
			}
		},
		function() {
			if ($.browser.msie && $.browser.version <= 6) {				
				var cl = $(this).attr("class").split(" "),
					cla = ""; 
				
				for (var i in cl) {
					if (cl[i].indexOf("hover") != -1) {cla = cl[i];}
				}
				$(this).removeClass(cla);
			} else {
				$(this).removeClass("hover");
			}	
		}
	);
	
	/*Media sliders*/
	var offsetDIV = ($("#article").length) ? ".media-item" : ".media-single";
	$(".media-single").mediaSlider({offsetDIV: offsetDIV});
	
	/*Archive cover Fancybox*/
	$(".archive-coverList a.fancyBox").fancybox({
		'enableEscapeButton': true,
		'showNavArrows': true,
		'hideOnContentClick': true,
		'hideOnOverlayClick': true,
		'centerOnScroll': true,
		'cyclic': true,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic'
	});
	
	/*Article image gallery Fancybox*/
	$(".article-image a").each(function() {
		var zis = $(this);
		
		zis.fancybox({
			'enableEscapeButton': true,
			'showNavArrows': true,
			'hideOnContentClick': true,
			'hideOnOverlayClick': true,
			'centerOnScroll': true,
			'cyclic': true,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'titleShow' : true,
			'titlePosition': 'inside',
			'description': $("img",zis).attr("alt"),
			'author': zis.parent("li").find(".imgSource").text()
		});
	});		
	
	/*Iframe Fancybox*/
	if ($("a.pop-up").length) {
		$("a.pop-up").each(function() {
			var rel = $(this).attr("rel").split("|"),
				puHeight = 10,
				onCompleteCallback = resizeFancyBox;
			
			if (rel[0] && rel[1]) {
				//For Newsletter set bigger height
				if ($(this).parent().hasClass("newsletter")) {
					puHeight = 420;
					onCompleteCallback = function() {return true;};
				}	
				
				$(this).fancybox({
					'scrolling'	: 'no',		
					'titleShow'	: false,
					'href' : 'index.php?id=' + parseInt(rel[0]) + '&type=' + parseInt(rel[1]),
					'type' : 'iframe',
					'width': 590,
					'height' : puHeight,
					'onComplete' : onCompleteCallback, 
					'centerOnScroll' : true,
					'showNavArrows' : false
				});				
			}
		});
	}
			
	/*Autoclear inputs*/
	initializeAutoClear();
	
	/*Styled forms*/
	$("form.jNice").jNice();
	//$("#sidebar-vremea .jNice").jNice();	
	
	/*Initialize tabs*/
	if ($(".tabs:not('.noInline')").length) $(".tabs:not('.noInline')").tabs();	
	$("#sidebar-top-news").ajaxTabs({data:"type=8005&tx_ttnews[action]=",onComplete:listlastitem,trigger:0});
	$("#sidebar-top-gallery").ajaxTabs({data:"type=6695&tx_gallery_pi1[topCat]="+$("#sidebar-top-gallery .ajax-tabs ul li:first a").attr('rel')+"&tx_gallery_pi1[action]=",onComplete:listlastitem,trigger:1});
	$("#sidebar-top-video").ajaxTabs({"data":"type=3695&tx_lsuvideo_pi1[topCat]="+$("#sidebar-top-video .ajax-tabs ul li:first a").attr('rel')+"&tx_lsuvideo_pi1[action]=",onComplete:listlastitem,trigger:1});	
	
	/*Reader story*/
	if ($(".trimite-readerStory").length) {
		fancyBoxHref = $(".trimite-readerStory a").attr('href');
		$(".trimite-readerStory a").fancybox({
				'scrolling'	: 'no',
				'titleShow'	: false,
				'href' : fancyBoxHref,
				'type' : 'iframe',
				'width': 850,
				'height' : 10,
				'onComplete' : resizeFancyBox, 
				'centerOnScroll' : true
			});	
	}
	/*Reader pont*/
	if ($(".trimite-readerPont").length) {
		fancyBoxHref = $(".trimite-readerPont a").attr('href');
		$(".trimite-readerPont a").fancybox({
				'scrolling'	: 'no',
				'titleShow'	: false,
				'href' : fancyBoxHref,
				'type' : 'iframe',
				'width': 850,
				'height' : 10,
				'onComplete' : resizeFancyBox, 
				'centerOnScroll' : true
			});	
	}
	
	/*My account*/
	if ($("#my-account").length) {
		fancyBoxHref = $("#my-account").attr('href');
		$("#my-account").fancybox({
				'scrolling'	: 'no',
				'titleShow'	: false,
				'href' : fancyBoxHref,
				'type' : 'iframe',
				'width': 630,
				'height' : 10,
				'onComplete' : resizeFancyBox, 
				'centerOnScroll' : true
			});	
	}
	
	/*Members pages*/	
	if ($("#members").length || $(".popup-register").length) {
		var regCont = $("#members").length ? $("#members") : $(".popup-register");
		/*Style file buttons*/
		$("input[type=file]",regCont).filestyle({image:"/fileadmin/images/upload-button.gif",imageheight:27,imagewidth:96,width:151});
		/*Registration + Account*/ 
		$(".input-submit",regCont).click(function() {
			if ($(".select-combo",regCont).length) {
				var day = $(".select-combo select:eq(0) .selected",regCont).attr("value"),
					month = $(".select-combo select:eq(1) .selected",regCont).attr("value"),
					year = $(".select-combo select:eq(2) .selected",regCont).attr("value");
				$("#date_of_birth").val(day+"-"+month+"-"+year);
			}
		});				
	}				
	
	/*Pagina5 pages - birthday add to a hidden input*/	
	if ($("#popup-pagina5-register").length) {
		$("#popup-pagina5-register #submit").click(function() {
			if ($("#popup-pagina5-register .select-combo").length) {
				var day = $("#popup-pagina5-register .select-combo select:eq(0) .selected").attr("value"),
					month = $("#popup-pagina5-register .select-combo select:eq(1) .selected").attr("value"),
					year = $("#popup-pagina5-register .select-combo select:eq(2) .selected").attr("value");
				$("#data_nasterii").val(day+"-"+month+"-"+year);				
			}
		});				
	}		
	/*Sidebar partnerbox - add class*/
	if ($(".sidebar-partnerBox li").length) $(".sidebar-partnerBox li:odd").addClass("odd");
	
	/*Vremea - add wrapper id*/
	if ($("#vremea").length) {
		$("#vremea .tx-weatheraccu-pi1").has(".cities-wrapper").attr("id","cities");				
	}
	
	/*Fix iFrame height used for Weather*/
	if ($("#weatherIframe").length) {	   		
		initIFrame();
	}
	
	/*Page topic column height*/
	if ($(".page-topic .content-2Column .left").length) {
		var ptoLeft = $(".page-topic .content-2Column .left").height(),
			ptoRight = $(".page-topic .content-2Column .right");
		
		if (ptoRight.height() < ptoLeft) ptoRight.height(ptoLeft);	
	}
	
	/*Horoscop - column height*/
	if ($("#horoscop").length) {
		if (!$("#horoscop .compatibility-text").length) {
			var horLeft = $(".content-2Column .left"),
				horRight = $(".content-2Column .right").height();
				
			if (horLeft.height() < horRight) horLeft.height(horRight);	
		}	
		
		if ($("#horoscop .compatibility-text").length) {
			var compText = $("#horoscop .compatibility-text"),
				compRight = $("#horoscop .content-2Column .right").height();
			
			if (compText.height() < compRight) compText.height(compRight);
		}
	}
	
	/*Preview titles - adjust height*/
	if ($(".preview-titles").length) {
		$(".preview-titles").each(function() {
			var pt = $(this);
			
			if (pt.find(".left ul").length && pt.find(".right ul").length) {
				pt.find("ul").height(function() {
					var left = pt.find(".left ul").height(),
						right = pt.find(".right ul").height();
						
					return Math.max(left,right);	
				});
			}	
		});
	}
	
	/*TV program - add classes to the list*/
	if ($("#tv-program #tv-channels > li .program li").length) {
		$("#tv-program #tv-channels > li:not(':last'):nth-child(4n)").after("<li class='li-clear'></li>");
		$("#tv-program #tv-channels > li .program").each(function() {
			$(this)
				.find("li:first").addClass("first")
				.end()
				.find("li:last").addClass("last")
				.end()
				.find("li:odd").addClass("odd");
		});		
	}
	
	/*TV program page - add classes to the list*/
	if ($("#tv-programs").length) {
		$("#tv-programs .content").jScrollPane({reinitialiseOnImageLoad:true,showArrows:true,arrowSize:10});
		$("#tv-programs > li:eq(0)")
			.add("#tv-programs > li:eq(1)")
			.add("#tv-programs > li:eq(2)")
			.addClass("first");
		$("#tv-programs > li:nth-child(3n)")
			.addClass("row-last");
		$("#tv-programs > li .program").each(function() {
			$(this).find("li:odd").addClass("odd");
		})
	}	
	
	/*Weather pages - add classes and adjust height of forecast boxes*/
	if ($("#vremea .forecast-wrapLine .forecast-box").length) {
		$("#vremea .forecast-wrapLine .forecast-box:nth-child(3n)").addClass("last");
		$("#vremea .forecast-wrapLine").each(function() {
			var h = 0;
			$(".forecast-box",this).each(function() {
				if ($(this).height() > h) h = $(this).height();
			});
			$(".forecast-box",this).height(h);
		});
	}
	
	/*OL style - style ordered lists*/
	if ($(".article-content ol, .text ol").length) {
		$(".article-content ol li, .text ol li").each(function() {
			$(this).html("<span>" + $(this).html() + "</span>");
		});
	}
	
	/*Media list - add classes to video/photo list*/
	if ($(".page-multimediaGallery .list").length) {
		$("#photoGallery-list .list").find(".item:nth-child(4n), .item:last").addClass("last");			
		$("#videoGallery-list .list").find(".item:nth-child(2n), .item:last").addClass("last");			
	}
		
	/*Feminin channel - Add class .last-preview for 3columns divs*/
	$('#skin-feminin #content .preview-3Column:last').addClass('last-preview');
	
	/*Lazy load images*/
	/* var lazyContentImages = $("#content img:not('.box-title img'):not('.commentIcon'):not('.article-image img'):not('.related_articles .slider img')"),
            lazyPromptImages = $("#sidebar img:not('.box-title img'):not('.commentIcon')").add(".related_articles .slider img");
		
	lazyContentImages.lazyload({placeholder:"/fileadmin/images/lazydot.gif",event:"scroll",threshold:200});
	lazyPromptImages.lazyload({placeholder:"/fileadmin/images/lazydot.gif",event:"promptLazy"});
	$(window).bind("load", function() { 
		var timeout = setTimeout(function() {lazyPromptImages.trigger("promptLazy")}, 1);
	});
	*/
	/*IE6 fixes*/
	if (ie(6)) {	
		/*In ie6 height:100% will not work unless the parent element has height defined*/		
		/*Topic page - video*/
		if ($(".page-topic .video div a").length)	{
			$(".page-topic .video div").height($(".page-topic .video img").height());
		}	
		/*PNGfix for png source img*/
		pngFix();
		
		/*PNGfix for png background img*/                
		DD_belatedPNG.fix('#home-slider .slider-wrapper .slider-navigation, .corner, .shareTwitter .retweet, .shareFacebook a, .article-infoBox .send span a, .search_results-box .facebook a, #sidebar-evz .header, #sidebar-capital .header, #sidebar-bravo .header, .like p a, .page-multimediaGallery .header .search .text-wrap, .jNiceSelectOpen, #vremea #percentage-box .button, #footer #footer-bottom .text-wrap, .commentIcon');
		
		DD_belatedPNG.fix('.skin .page-mainTitle ul, .comments .comment-box .reply, #home-slider .slider-wrapper li .text-side, #videoGallery-list .list .img-side a span, .page-topic .right .video div a, #members .tips-list li, #vremea .picture, #horoscop .sings-small li a, #horoscop .compatibility-preview .image, #tv-programs .header, #tv-programs .header div, #tv-program .content, #tv-program .content-wrapper .tv-wrap-topbottom, #tv-program .content-inner, #tv-program #tv-channels li .header, #tv-program #tv-channels li .footer, #tipafriendlayout .close i, #home-slider .img-overlay, .tvicon, .vremea-sidebarIcon, .skin-pagina5 .member-wrapper .data .data-comments .icon, #content .article .article-imageSlider .slider-navigation, .single-navigation span, .single-navigation i');
	}	
	/*end*/	
	
	/*Facebook widget*/
	if ($('#fb-root').length) {
		var e = document.createElement('script');
		e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	}	
});
/*****/

/**
	iFrame auto height
*/
function initIFrame() { 
  var iframe = null; 
  iframe = document.getElementById("weatherIframe"); 
  iframe.onload = checkLoaded; 
  iframe.onreadystatechange = checkLoaded; 
  if (!$.browser.mozilla) resizeFrame(iframe); 
} 

function checkLoaded() { 
   if((document.all && this.readyState == "complete") || !document.all) resizeFrame(this); 
} 

function resizeFrame(obj) { 
   var fHeight = 0; 
   if(window.frames['weatherIframe'].document.body) {
		window.frames['weatherIframe'].document.body.style.margin="0";
		if(window.frames['weatherIframe'].document.body.scrollHeight) {
			fHeight = window.frames['weatherIframe'].document.body.scrollHeight; 
			obj.style.height = fHeight + "px"; 
			return true;
		}	
   } else if(obj.contentDocument && obj.contentDocument.body) {
		if (obj.contentDocument && obj.contentDocument.body.offsetHeight) {
			fHeight = obj.contentDocument.body.offsetHeight;    
			obj.style.height = fHeight + "px"; 
			return true;
		}	 
   }
}

/**
	Check if IE
*/
function ie(ieVersion) {
	if ($.browser.msie && $.browser.version == ieVersion) return true;
	return false;
}

/**
	Resizes the fancybox after the content is loaded
*/
function resizeFancyBox() {				
	if (typeof arguments[0] == 'number') {			
		resizeFancyBoxInside();
	} else {		
		$('#fancybox-frame').load(function() {							
			resizeFancyBoxOutside();			
		});	
	}		
}

function resizeFancyBoxInside() {
	var iHeight = document.body.scrollHeight,iWidth = document.body.scrollWidth;
	
	var outer = parent.document.getElementById('fancybox-wrap'),
		inner = parent.document.getElementById('fancybox-content'),
		paddingTotal = 20;			
	
	if (iHeight > 0 && iWidth > 0) {				
		outer.style.width = iWidth + paddingTotal + "px";
		outer.style.height = iHeight + paddingTotal + "px";

		inner.style.width = iWidth + "px";	
		inner.style.height = iHeight + "px";
		
		window.top.eval('fb_resize('+iWidth+','+iHeight+')');
	}		
}

function resizeFancyBoxOutside() {	
	var iFrameContentHeight = document.getElementById('fancybox-frame').contentWindow.document.body.scrollHeight,
	    iFrameContentWidth = document.getElementById('fancybox-frame').contentWindow.document.body.scrollWidth,
		outer = $('#fancybox-wrap'),inner = $('#fancybox-content'),paddingTotal = 20;
	
	if(iFrameContentHeight > 0 && iFrameContentWidth > 0){				
			outer.css({
				 height: iFrameContentHeight + paddingTotal,
				 width: iFrameContentWidth + paddingTotal
			});
			inner.css({
				 height: iFrameContentHeight,
				 width: iFrameContentWidth	
			});
			parent.$.fancybox.center();			
			var oh = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
			$("#fancybox-overlay").height(oh);				
	}
}

function fb_resize(w, h) {
  $('#fancybox-content').css({ width: w+"px"});
  $('#fancybox-content').css({ height: h+"px"});
  $.fancybox.resize();
  var oh = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
  $("#fancybox-overlay").height(oh);				
}

/**
	Initializes the rating system on the Weather page
*/
function vremeaRating() {
    if ($("#bar-rating:not('.disabled')").length) {		
		if ($("#bar-rating").parent().hasClass("contentBox")) $("#bar-rating").unwrap();
        $("#bar-rating").rating({
                'url': 'typo3conf/ext/voting/res/barRating.php'
        });
    }
}

function load_votes() {
	if ($("#ajaxWeatherVote").length) {
		var currentUrl = document.location.href;
		if (currentUrl.indexOf('#') > 0) {
			currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
		}
		if(document.location.hostname!='www.libertatea.ro' || document.location.hostname!='libertatea.ro') {
			var currentUrlInfo = currentUrl.split('www.libertatea.ro'); 
			if(currentUrlInfo.length >1) {
				currentUrlParts = currentUrlInfo[1].split('%2F');
				currentUrl = currentUrlParts.join('/');
				currentUrl = 'http://www.libertatea.ro' + currentUrl;
			}
		}
		if(currentUrl.indexOf('?')!=-1)
			currentUrl += "&tx_weatheraccu_pi1[load_votes]=1&type=43&no_cache=1";
		else 
			currentUrl += "?tx_weatheraccu_pi1[load_votes]=1&type=43&no_cache=1";
								
		$.ajax({
			url: currentUrl,
			cache: true,
			type: "GET",
			dataType: "html",
			success: function(html){			
				$("#ajaxWeatherVote").html(html);			
				vremeaRating();
			}
		});
	}	
}

/**
	PNG fix in ie6
*/
function fixpng(element) {
    if ($.browser.msie && $.browser.version == 6) {
            DD_belatedPNG.fixPng(element);
    }
}

function pngFix() {
 $('img[src$=.png]').each(function(i) {		  
   if (!this.complete) {
	 this.onload = function() { fixThis(this) };
   } else {
	 fixThis(this);
   }
 });
}

function fixThis(png) {
   var blank = new Image(),src = png.src;
	   
   blank.src = '/fileadmin/images/blank.gif';	   
   if (!png.style.width) { png.style.width = $(png).width(); }
   if (!png.style.height) { png.style.height = $(png).height(); }
   png.onload = function() { };
   png.src = blank.src;
   png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
 }

/**
	Autoclear input
*/
function initializeAutoClear() {
    if ($(".autoclear").length) $(".autoclear").inputAutoClear();
}

/**
	Change font size
*/
var defaultFontSize = 1;
function fontSize(box) {
    var size = ['100%','112.5%','125%', '137.5%', '150%'];

    if (defaultFontSize == 4) defaultFontSize = 0;
    if (defaultFontSize < 4) {
            if (!box || box == "") box = ".article";
            $(box).css({
				"font-size":size[defaultFontSize],
				"line-height":"130%"
			});
            defaultFontSize++;
    }
}

/**
	Article page - Related articles slider
*/
function articleRelatedSlider() {
    if ($(".article .related_articles").length) {
            $(".article .related_articles").slider({size:4, scroll:4});

            var h = $(".article .related_articles").height() +
                        parseInt($(".article .related_articles").css("padding-top")) +
                        parseInt($(".article .related_articles").css("padding-bottom"));

            $(".article .related_articles .slider-navigation").css("top",parseInt((h - 23) / 2));
    }
}

/**
	Article page - Image slider
*/
function articleSlider() {
    if ($("#article").length && $("#article .article-content ul.article-image li").length > 1) {
            var h = 0;

            $("#article .article-content ul.article-image")
                    .addClass("slider")
                    .wrap("<div class='article-imageSlider' />")
                    .parent()
					.prepend("<div class='slider-navigation-wrapper' />")
					.find(".slider-navigation-wrapper")
                    .prepend("<div class='slider-navigation next next-inactive' />")
                    .prepend("<div class='slider-navigation prev prev-inactive' />")
					.end()
                    .find("ul")
                    .wrap("<div class='slider-inner' />")
                    .end()
                    .slider()
                .find(".hidden")
                    .removeClass("hidden")
                    .end()
				.find("li:hidden")
					.css("display","block")
					.end()						
                .find("li img")
                    .each(function() {
                            if ($(this).height() > h) h = $(this).height();
                            $(this).parent().width($(this).width());
                    })
                    .end()
                    .find("li")
                    .each(function() {
                            var hi = $("img",$(this)).height();
                            $(this)
                                    .height(h)
                                    .find("a")
                                    .css("top",function() {
                                            if (hi < h) return parseInt((h - hi) / 2) + "px";
                                                    else return "0";
                                    });
                    });

            var h = $(".article div.article-imageSlider").height() +
                        parseInt($(".article div.article-imageSlider").css("padding-top")) +
                            parseInt($(".article div.article-imageSlider").css("padding-bottom"));
            $(".article div.article-imageSlider .slider-navigation").css("top",parseInt((h - 53) / 2));
    } else {
		if (ie(6) && $("#article").length && $("#article .article-content ul.article-image li").length == 1) {		
			$("#article .article-content ul.article-image li").css("float","none");
		}
	}
}

/*
	Article page - News in the header
*/
function articleHeaderNews() {
    var menu = $("#article #main-menu > ul"),preview = $("#article #header-news > ul"),liCount = menu.find("> li").size(),bodyClass = "";
		
	if (preview.length) {
		$("#article #header-news").prepend("<p class='close'><a href='javascript:;' onclick='articleHeaderNewsClose()'>x</a></p>");
		
		for (var i=1;i<liCount;i++) preview.append("<li></li>");
		preview
				.find("> li:first").addClass("hover")
				.end()
				.find("> li:not('.hover')").css("opacity","0");

		menu.find("> li a:not(:first)").hover(
				function() {
						//Check if there is an active menuitem and save its position
						menu
							.find(".active")
							.removeClass("active")
							.attr("rel","active");

						if ($("#header-news").is(":hidden")) {									
								$("#header-news").slideDown("medium");
								menu.find("> li:eq(1) a").addClass("hover").trigger("mouseover");
						}

						menu.find("> li").removeClass('hover');
						$(this).parent().addClass('hover');
						var index = menu.find("> li a").index($(this)) - 1,
								selected = preview.find("> li:eq(" +  index + ")"),
								active = preview.find("> li.hover");

						//The first menu is the Home link
						if (index > -1) {
								if (selected.html().length) {
										active.removeClass("hover");
										preview
											.find("> li:not(:eq(" +  index + "))")
											.css("opacity","0");
										selected
											.addClass("hover")
											.animate({opacity:1},200);
								} else {
										preloader.add(active,"");
										var currentUrl = document.location.href;
										if (currentUrl.indexOf('#') > 0) {
											currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
										}
										if(document.location.hostname!='www.libertatea.ro' || document.location.hostname!='libertatea.ro') {
											var currentUrlInfo = currentUrl.split('www.libertatea.ro'); 
											if(currentUrlInfo.length >1) {
												currentUrlParts = currentUrlInfo[1].split('%2F');
												currentUrl = currentUrlParts.join('/');
												currentUrl = 'http://www.libertatea.ro' + currentUrl;
											}
										}
										if(currentUrl.indexOf('?')!=-1)
											currentUrl += "&type=8003&tx_ttnews[cat_shortcut]=" + $(this).attr('rel') + "&tx_ttnews[tt_content_uid]=" + $('#header-news').attr('rel');
										else 
											currentUrl += "?type=8003&tx_ttnews[cat_shortcut]=" + $(this).attr('rel') + "&tx_ttnews[tt_content_uid]=" + $('#header-news').attr('rel');
										$.ajax({
												url: currentUrl,
												cache: true,
												type: "GET",
												success: function(html) {
														preloader.remove(active);
														active.removeClass("hover");
														preview
															.find("> li:not(:eq(" +  index + "))")
															.css("opacity","0");
														selected
															.html(html)
															.addClass("hover")
															.animate({opacity:1},200);
										  }
										});
								}
						}
				},
				function() {/*do nothing on hover out*/}
		);
	}	
}

function articleHeaderNewsClose() {
    $("#header-news").slideUp("medium",function() {
		//Remove the hover class from the expanded menu	
		$("#article #main-menu > ul li.hover")
			.removeAttr("class");
			
		//Put back the saved active class
		$("#article #main-menu > ul li[rel=active]")
			.removeAttr("rel")
			.addClass("active");				
	});	
}

/**
	Put wmode = transparent videos in article
*/
function fixArticleVideo() {
	if ($(".article-content").length) {	
		if ($.browser.msie) fixArticleVideoIE();
			else fixArticleVideoOther();
		fixIframeYoutube();		
	}	
}

function fixIframeYoutube() {	
	//Replace IFrame to a regular object/embed
	var ythtml = '<object width="###width###" height="###height###"><param name="movie" value="###url###"></param><param name="allowFullScreen" value="true"></param><param name="wmode" value="transparent"></param><param name="allowscriptaccess" value="always"></param><embed src="###url###" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="###width###" height="###height###" wmode="transparent"></embed></object>';
	
	if ($(".article-content iframe").length) {
		$(".article-content iframe").each(function() {
			var regex = /http\:\/\/www\.youtube\.com\/embed\/([^>"']{11})/gim;				
			yt = $(this).attr("src") ? $(this).attr("src").match(regex) : 0;
				
			if (yt) {
				yt = yt[0].replace(/http\:\/\/www\.youtube\.com\/embed\//gim,"");
				if (yt) {
					var width = $(this).attr("width"),
						height = $(this).attr("height");
					
					newvideo = 	ythtml
									.replace(/###width###/ig,width)
									.replace(/###height###/ig,height)
									.replace(/###url###/ig,"http://www.youtube.com/v/" + yt);
					
					$(this).replaceWith(newvideo);				
				}
			}
		});
	}	
}

function fixArticleVideoIE() {
    // loop through every embed tag on the site
    var embeds = document.getElementById("content").getElementsByTagName('embed');
    for(i=0; i<embeds.length; i++)  {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if(embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if(html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i,"wmode='transparent'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i,"<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin',new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if(!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase()=='window')
                new_embed.setAttribute('wmode','transparent');
            embed.parentNode.replaceChild(new_embed,embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementById("content").getElementsByTagName('object');
    for(i=0; i<objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if(object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if(html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i,"<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i,"<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for(j=0; j<children.length; j++) {
				if (children[j] && children[j].getAttribute('name')) {
					if(children[j].getAttribute('name').match(/flashvars/i)) {
						new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i,"<param name='flashvars' value='"+children[j].getAttribute('value')+"' />");
					}
				}	
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin',new_object);
            object.parentNode.removeChild(object);
        }
    }
}
function fixArticleVideoOther() {
	var newObject,newEmbed;
	//Object
	$(".article-content object:not('.wmoded')").each(function() {							
		if ($("param[name*='wmode']",this).length) $("param[name*='wmode']",this).attr("value","transparent");
		else $(this).prepend("<param name='wmode' value='transparent' />");
		
		newObject = $(this).clone(true);		
		
		newObject
			.addClass("wmoded")			
			.find("embed")
			.attr("wmode","transparent")
			.addClass("wmoded-embed");
		$(this).replaceWith(newObject);	
	});	

	//Embed
	$(".article-content embed:not('.wmoded-embed')").each(function() {						
		newEmbed = $(this).clone(true);
		
		newEmbed
			.addClass("wmoded-embed")
			.attr("wmode","transparent");
		$(this).replaceWith(newEmbed);				
	});	
}

/**
	Foto slider on the topic page
*/
function topicPageFotoSlider() {
    if ($(".page-topic .foto").length) {
        $(".page-topic .foto").slider({});
    }
}

/**
	Breaking news
*/
function breakingNews() {	
    if ($("#breaking_news").length) {
            var list = $("#breaking_news .list"),preview = $("#breaking_news .preview");

            //fix width of table cells
            list.find("td").width(function() {
                return Math.round( 100 / list.find("td").length) + "%";
            });

            //fix height of content
            var cMaxH = 0;
            list.find(".content").each(function() {
                var thisH = $(this).height();
                if (thisH > cMaxH) cMaxH = thisH;
            });
            list.find(".content").height(cMaxH);

            preview.find("li:not('.active')").css("opacity","0");

            $(".content a",list).click(function(event) {
                    var index = $(".content a",list).index($(this));
                    if (!index) index = 0;
                    var selected = preview.find("li:eq(" +  index + ")");

                    list.find("td.active").removeClass("active");
                    $(this).parents("td").addClass("active");

                    if (!selected.html().length) {
                            var prev = preview.find("li.active");

                            prev
								.html(prev.html() + "<div class='slider-preloader'></div><span class='slider-preloaderi'></span>")
								.find(".slider-preloader")
								.css("opacity","0.8");

                            //don't show list if there is only one item
                            if ($(".content a",list).length == 1) list.remove();
							var currentUrl = document.location.href;
							if (currentUrl.indexOf('#') > 0) {
								currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
							}
							if(document.location.hostname!='www.libertatea.ro' || document.location.hostname!='libertatea.ro') {
								var currentUrlInfo = currentUrl.split('www.libertatea.ro'); 
								if(currentUrlInfo.length >1) {
									currentUrlParts = currentUrlInfo[1].split('%2F');
									currentUrl = currentUrlParts.join('/');
									currentUrl = 'http://www.libertatea.ro' + currentUrl;
								}
							}
							if(currentUrl.indexOf('?')!=-1)
								currentUrl += "&type=8001&tx_ttnews[tt_content_uid]=" + $("#breaking_news").attr('rel') + "&tx_ttnews[tt_news]=" + $(this).attr('rel');
							else 
								currentUrl += "?type=8001&tx_ttnews[tt_content_uid]=" + $("#breaking_news").attr('rel') + "&tx_ttnews[tt_news]=" + $(this).attr('rel');
                            $.ajax({
								url: currentUrl,
								cache: true,
								type: "GET",
								success: function(html){
										selected.html(html);
										prev
												.removeClass("active")
												.css("opacity","0")
												.find(".slider-preloader, .slider-preloaderi").remove();
										selected
												.addClass("active")
												.animate({opacity:1},200);
                              }
                            });
                    }
                    else {
                            preview
								.find("li.active").removeClass("active")
								.end()
								.find("li:not(:eq(" +  index + "))").css("opacity","0")
								.end()
								.find("li:eq(" +  index + ")").addClass("active").animate({opacity:1},200);
                    }
                    event.preventDefault();
            });
            list.find(".first .content a",list).trigger('click');
            }	
}

/**
	Home slider
*/
function slideShow(slider,hsNext) {
    var slider = $(slider);
    slider.find("li:eq(" + hsNext + ")").trigger('click');
}
function homeSlider() {
    if ($("#home-slider .slider").length) {
            var preview = $("#home-slider .preview").html("<ul></ul>"),
                slider = $("#home-slider .slider"),
                liCount = $("#home-slider .slider > li").size(),
                time = 6000,
                settings = {
                        size : 4,
						//On slider navigation the slideshow stops
                        rightArrowCallback : function() {if (typeof c != 'undefined') clearTimeout(c);},
                        leftArrowCallback: function() {if (typeof c != 'undefined') clearTimeout(c);}
                };

            $("li:first",slider).addClass("active");
            for (var i=1;i<=liCount;i++) $("ul",preview).append("<li></li>");
            preview
				.find("li:first").addClass("active")
				.end()
				.find("li:not('.active')").css("opacity","0");

            $("li",slider).click(function(e) {
                    var index = slider.find("> li").index($(this));
                    if (!index) index = 0;
                    var selected = preview.find("li:eq(" +  index + ")"),
                            hsNext = (index == liCount-1) ? 0 : index + 1;
					
					//At the end of the slider it starts over
                    if (index == 0) {
						$("#home-slider .slider-wrapper").slider(settings);
					}	
                    if (index % settings.size == 0 && index > 0) {						
						$.slider.moveForward($("#home-slider .slider-wrapper"),{size:4,scroll:4,direction:'left'});
					}	

                    //On slider click the slideShow stops
                    if (typeof c != 'undefined') clearTimeout(c);

                    //On preview hover the slideShow stops
                    selected.mouseover(function(ev) {
                        if (typeof c != 'undefined') clearTimeout(c);
                        ev.stopPropagation();
						return false;	
                    });
					//On preview mouseout the slideShow continues
					selected.mouseout(function(ev) {
						if (typeof c != 'undefined') clearTimeout(c);
						c = setTimeout("slideShow('#home-slider .slider','" + hsNext + "')",time);
						ev.stopPropagation();
						return false;
					});

                    slider.find("li.active").removeClass("active");
                    $(this).addClass("active");
					//Load the content
                    if (selected.text() == "") {
                            var prev = preview.find("li.active");
                            prev
                                    .html(prev.html() + "<div class='slider-preloader'></div><span class='slider-preloaderi'></span>")
                                    .find(".slider-preloader")
                                    .css("opacity","0.8");
							var currentUrl = document.location.href;
							if (currentUrl.indexOf('#') > 0) {
								currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
							}
							if(document.location.hostname!='www.libertatea.ro' || document.location.hostname!='libertatea.ro') {
								var currentUrlInfo = currentUrl.split('www.libertatea.ro'); 
								if(currentUrlInfo.length >1) {
									currentUrlParts = currentUrlInfo[1].split('%2F');
									currentUrl = currentUrlParts.join('/');
									currentUrl = 'http://www.libertatea.ro' + currentUrl;
								}
							}
							if(currentUrl.indexOf('?')!=-1) {
								currentUrl += "&type=8002&tx_ttnews[tt_content_uid]=" + $("#home-slider").attr('rel') + "&tx_ttnews[tt_news]=" + $(this).find('a').attr('rel');
							} else {
								currentUrl += "?type=8002&tx_ttnews[tt_content_uid]=" + $("#home-slider").attr('rel') + "&tx_ttnews[tt_news]=" + $(this).find('a').attr('rel');
							}	
                            $.ajax({
                                    url: currentUrl,
                                    cache: true,
                                    type: "GET",
                                    success: function(html){
                                            selected.html(html);
                                            prev
                                                    .removeClass("active")
                                                    .css("opacity","0")
                                                    .find(".slider-preloader, .slider-preloaderi").remove();
                                            selected
                                                    .addClass("active")
                                                    .animate({opacity:1},200);
                                            //At the end of item load we set the slideshow timing
                                            c = setTimeout("slideShow('#home-slider .slider','" + hsNext + "')",time);
                              }
                            });
                    } else {
                            preview
                                    .find("li.active").removeClass("active")
                                    .find(".img-overlay").removeAttr("id")
                                    .end().end()
                                    .find("li:not(:eq(" +  index + "))").css("opacity","0")
                                    .end()
                                    .find("li:eq(" +  index + ")").addClass("active").animate({opacity:1},200)
                                    .find(".img-overlay").attr("id","hsCurrent");
                            //Fix transparency in IE6
                            fixpng(document.getElementById("hsCurrent"));
                            //At the end of the item load we set the slideshow timing
                            c = setTimeout("slideShow('#home-slider .slider','" + hsNext + "')",time);
                    }
                    e.preventDefault();
            });
            //Loads the first item
            slider.find("li:first").trigger('click');
    }
}

/**
	Tell a friend
*/
function tipform(table,uid, typenum){
	currentUrl = document.location.href;
	if (currentUrl.indexOf('#') > 0) {
		currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
	}
    $.ajax({
            url:currentUrl,
            cache:false,
            type:"POST",
            data: 'parenttable=' + table + '&parentid=' + uid + '&type='+typenum+'&tx_dptellafriend_pi1[displayForm]=1',
            success:function(html){
                    var scroll=$(window).scrollTop()-250;
                    var top=(parseInt($(window).height())/2)+scroll;
                    $("#tipafriendlayout").html(html).css('top',top);
                    $("#tipafriendlayout").fadeIn();
                    $("#bigOverlay").css('display','block').css('opacity',0).fadeTo('fast',0.8,function() {
                            if ($.browser.msie && $.browser.version < 7)
                                    $(".comments .header .filter select").fadeOut("fast");
                    });
                    if($.browser.msie&&$.browser.version<7){
                            $("#bigOverlay").height(document.body.clientHeight);
                    }
                    initializeAutoClear();
            }
    });
}
function submitFormTellAFriend(){
    var name=$('#name').attr('value'),email=$('#email').attr('value'),recipient=$('#recipient').attr('value'),message=$('#message').attr('value'),parentid=$('#parentid').attr('value'),parenttable=$('#parenttable').attr('value'),typenum=$('#typenum').attr('value');
	
	currentUrl = document.location.href;
	if (currentUrl.indexOf('#') > 0) {
		currentUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
	}
	
    $.ajax({
            url:currentUrl,
            cache:false,
            type:"POST",
            data:"name="+name+"&email="+email+"&recipient="+recipient+"&type="+typenum+"&message="+message+"&tipUrl=1&sendTip=1&parenttable=" + parenttable +"&parentid="+parentid,
            success:function(html){
                    $("#tipafriendlayout").html(html);
            }
    });
}
		
function hideForm(){
    $("#tipafriendlayout .tx-dptellafriend-pi1, #bigOverlay").fadeOut(function() {
            $("#tipafriendlayout").removeAttr("style");
            if ($.browser.msie && $.browser.version < 7) $(".comments .header .filter select").fadeIn("fast");
    });
}

/**
	Print
*/
function printLink(url) {
    var print = window.open(url,'PrintPage','scrollbars=1,width=810,height=500');
    print.focus();
    print.print();
}

/**
	Voting system
*/
function registerVote(url,data,value,operation,obj) {
    var dataArray = data.split(':'),
        uid = parseInt(dataArray[1]),
        table = dataArray[0],
	    cookieName = 'tx_voting_pi1' + '_vote_' + table + '_' + uid;
	
	wrapper = obj.parentNode.parentNode;    
		
    if (!$.cookie(cookieName)) {
		obj.style.opacity = "0.4";
        $.ajax({
            url:url,
            cache:false,
            type:"POST",
            data:'tx_voting_pi1[data]='+data,
            success:function(html){
				obj.style.opacity = "1";
                $(".positive", wrapper)
					.addClass('positive-voted')
					.removeClass('positive');
                $(".negative", wrapper)
					.addClass('negative-voted')
					.removeClass('negative');
				value++;
                if (operation == 1) {
					$(".positive-voted span", wrapper).html('+' + value);
                } else	{
					$(".negative-voted span", wrapper).html('-' + value);
				}
            }
        })
    }
}

/*
	Footer - Split the link list into smaller lists that fit in the row
*/
function fixFooter() {
	var fw = $("#footer").width(),lw = new Array(),tw = 0,rowNr = 1;
	
	if ($("#footer-top ul").length) {
		//calculate the width of the list
		$("#footer-top ul li").each(function(i) {
			lw[i]= $(this).width() + parseInt($(this).css("padding-right")) + parseInt($(this).css("margin-right"));
		});
		
		//if the width of the list is greater than the width of the footer split the list
		if (arraySum(lw) > fw) {									
			$("#footer-top").append("<div><ul class='row' id='row-" + rowNr + "'></ul></div>");
			$("#footer-top ul:not('.row') li").each(function(i) {
				tw += lw[i];				
				if (tw > fw) {					
					$("#footer-top #row-" + rowNr + " li:last").addClass("last");
					rowNr++;
					tw = lw[i];
					$("#footer-top").append("<div><ul class='row' id='row-" + rowNr + "'></ul></div>");
				}	
				$(this).appendTo($("#footer-top #row-" + rowNr));
			});
			$("#footer-top ul:not('.row')").remove();
		}	
	}
}

function arraySum(arr) {
	var s = 0;
	for (var i = 0; i < arr.length; i++) {
	  s += (typeof arr[i] == 'number') ? arr[i] : 0;
	}
	return s;
}

/*
	Add class="last" to the last item of a list
*/
function listlastitem() {
    $(".content-sideNewsBox")
        .add(".content-mainNewsBox")
		.add(".news-smallBox")
		.add(".slider-inner")
		.add("#footer-top")
        .each(function() {
            $("li:last",this).addClass("last");
        });
	$(".preview-3Column .content")
		.each(function() {
			$(".news-item:last",this).addClass("last");
		})
    $(".category-list").each(function() {
        $(".simple-listBox:last",this).addClass("last");
    });
}

/*
	Fix the height issue on single gallery (bottom)
*/
function singlePhotoFix() {
	if ($(".page-multimedia #content").length) {
		var cont = $(".page-multimedia #content"),
			newsW = $(".news-smallBox",cont).length ? $(".news-smallBox",cont) : $("#sidebar",cont),
			newsH = newsW.height(),
			commH = $("#listCommentsWrap",cont).height(),			
			formW = $("#bottomForm",cont),
			formH = formW.removeAttr("style").height(),
			maxHeight = Math.max(newsH,commH + formH);
			
		if (newsH > 0 && commH > 0) {
			if (newsH > commH + formH) formW.height(maxHeight - commH); 			
		}	
	}
}

function clearIfAlreadyVoted(tablesArray) {
	for(var i in tablesArray) {
		$('div[id^="voteLink_'+tablesArray[i]+'_"]').each(function() {
			var id = parseInt($(this).attr("id").replace("voteLink_"+tablesArray[i]+"_",""));
			if ($.cookie("tx_voting_pi1_vote_"+tablesArray[i]+"_" + id)) {
				$("p",this).each(function() {
					var cl = $(this).attr("class");
					
					if (cl.indexOf("-voted") == -1) {					
						$(this)
							.removeAttr("class")
							.attr("class",cl + "-voted")
							.find("a")
							.removeAttr("onclick");
					}	
				});
			}
		});
	}
}

function modifySearchFrm(form) {
	var realurl = new Array();

	realurl["tx_evzsearch_pi1[sword]"] = '/cuvant/';
	realurl["tx_evzsearch_pi1[fromDay]"] = '/incepand/';
	realurl["tx_evzsearch_pi1[fromMonth]"] = '/';
	realurl["tx_evzsearch_pi1[fromYear]"] = '/';
	realurl["tx_evzsearch_pi1[toDay]"] = '/pana/';
	realurl["tx_evzsearch_pi1[toMonth]"] = '/';
	realurl["tx_evzsearch_pi1[toYear]"] = '/';
	realurl["tx_evzsearch_pi1[submit]"] = '/cauta/';
	realurl["tx_evzsearch_pi1[orderBy]"] = '/ordonare/';
	realurl["tx_evzsearch_pi1[category]"] = '/categorii-rezultate/';
	realurl["tx_evzsearch_pi1[autor]"] = '/articol-autor/';
	

	var action = $('#siteUrl').val() + $(form).attr('action').replace('.html','').substr(1,$(form).attr('action').length);
	var action_no_maping = '';

	$('input, select',form).each(function(index, value) {
			if (($(this).is("input[type='text']")) || ($(this).is("input[type='hidden']")) || ($(this).is("select"))) {
			if (($(this).attr('name').length) && ($(this).val().length) && ($(this).attr('name') != 'tx_evzsearch_pi1[submit]'))
			{
				if (realurl[$(this).attr('name')] != undefined)
					action += realurl[$(this).attr('name')] + $(this).val().replace(' ','-');
				else
				{
					if (action_no_maping.length == 0)
						action_no_maping += $(this).attr('name') + '=' + $(this).val().replace(' ','-');
					else
						action_no_maping += '&' + $(this).attr('name') + '=' + $(this).val().replace(' ','-');
				}
			}
		}
		if (parseInt($('input, select',form).length - 1) == index)
			action += ".html";		
	});
	if (action_no_maping.length != 0)
		action += '?' + action_no_maping;
	$(window.location).attr('href', action);
}
