//majd ide jon az onload esemenyek
$(function() {
	initAjaxDelete();
});

function stripHTML(str){


	if( typeof( rel ) != 'string' ){
		return str;
	}
    

    var re = /(<([^>]+)>)/gi;
/*
	for (i=0; i < arguments.length; i++) {
		arguments[i] = arguments[i].replace(re, "");
		//arguments[i].value=arguments[i].value.replace(re, "");
	}
	return arguments;
*/
		  
	if ( str.length > 0 ) {
    	var str = str.replace(re, "");
		return str;
	}

}

function parseScript(_source) {
	var source = _source;
	var scripts = new Array();

	// Strip out tags
	while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
		var s = source.indexOf("<script");
		var s_e = source.indexOf(">", s);
		var e = source.indexOf("</script", s);
		var e_e = source.indexOf(">", e);

		// Add to scripts array
		scripts.push(source.substring(s_e+1, e));
		// Strip from source
		source = source.substring(0, s) + source.substring(e_e+1);
	}

	// Loop through every script collected and eval it
	for(var i=0; i<scripts.length; i++) {
		try {
			eval(scripts[i]);
		}
		catch(ex) {
			// do what you want here when a script fails
		}
	}

	// Return the cleaned source
	return source;
}


function callAjax(name, method, contextId, params, event, fnName, respType, fnToExec) {
	if(document.getElementById('adminMessage')) animatedcollapse.toggle('adminMessage');

	if (params === undefined) return ;

	var paramsdata = new String();
	var event = event || false;
	var respType = respType || "htmla";
	var fnName = fnName || false;
	var fnToExec = fnToExec || false;

	if (params.length > 0) {
		for (var n = 0; n < params.length; n++)	{
			paramsdata += "&params[]=" + stripHTML(params[n]);
		}
	}
	if (!testObj(contextId)) contextId = $(contextId);

	return jQuery.ajax({
	    url: "/ajax",
	    type: "POST",
	    data: "name=" + name + "&method=" + method + "&resp=" + respType + paramsdata,
	    context: $(contextId),
   	    success: function(resp) {
	        if (event != false) { //eventre felprogramozott, akkor fut be ide
				if (resp == true) {
					$(this).parent().parent().parent().remove();
				} else if (resp == false) {
				    console.log('false');
				} else {
					alert(resp);
				}

	        } else { //nem event, ha van fnName azt futtatjuk, ha nincs, akkor append
				resp = resp.replace(/(\r\n|\n|\r)/gm, "");
				resp = resp.replace(/"/g, '\"');
		        if (fnName != false) {
			    		setTimeout(fnName + "('" + resp + "')", 5000);
			    } else {
					if (respType == "htmla") {
						$(contextId).append(resp);
					} else if (respType == "htmli") {
					    document.getElementById(contextId.substring(1)).innerHTML = parseScript(resp);  // IE miatt :(
                        
					    if(fnToExec != false) setTimeout(fnToExec + "()", 1);
						//$(contextId).html(resp);
					} else if (respType == "json") { //jsonra kell fnName, amivel json obj-ot feldolgozzuk
						//alert("json hivas, fnName missed!");
					}
				}
			}
			if(document.getElementById('adminMessage')) animatedcollapse.toggle('adminMessage');
	    }
	});
}

function testObj(obj) {
	var type = typeof obj;
	if (type == 'object') {
		if (obj.getDate) return 'Date';
		if (obj.split) return 'String';
	}
	return type;
}

function jsCalAdd(name, trigger, showTime, dFormat) {
	if(showTime && showTime == true) {
		timeformat = " %H:%M";
	} else {
		timeformat = "";
	}
	if (dFormat == undefined) {
		dFormat = "%Y-%m-%d";
	}

	var varname = name + "Calendar";
	var trigger = trigger || name;
	var varname = Calendar.setup({
    	inputField : name,
    	trigger    : trigger,
		showTime   : showTime,
		dateFormat : dFormat+timeformat,
		hideOnOverlayClick : true,
    	onSelect   : function() { this.hide() }
	});
}

function initAjaxDelete() {
	$('img[ev*=delete]').click(function() {
		var confQ = confirm("Are you sure?");
		if (confQ == true) {
		    var eventStr = this.getAttribute("ev");
		    if (eventStr != "") {
		    	var eventA = eventStr.split(" ");

				params = new Array();
				for (var n = 2; n < eventA.length; n++)	{
					params.push(eventA[n]);
				}
		    	res = callAjax(eventA[0], eventA[1], this, params, params, 'event');
		    }
		    return false;
		} else return false;
		});
}

function delegateAsAjaxEvent(selector) {
	html.on("click", function(ev) {
		this.ajaxEvent()('click', [ev], selector);
	}.bind(this));
}

function ajaxEvent() {
	var handler = this;
	return function(event) {
		var src = Event.element(event);
		var params = src.getAttribute("event").split(" ");
		return handler.apply(src, [params[0], params[1], params.slice(2)]);
	}
}


//rating begin

var newRateValue = '';
var showIndicator = false;

function setRateValue(value, prefix, decimal){
	if(value < 0) {
		value = value * -1;
	} else {
		if(newRateValue != '')
			value = newRateValue;
			decimal = value.substr(2,1);
	}

	orig_value = value;
	value = Math.floor(value);

	if (decimal=='') {
		bgPos = -16*10+"px";
		from = value + 1;
	} else {
		bgPos = -16*decimal+"px";
		from = value + 2;
	}

	next = value+1;

	for (i=1;i<=next;i++) {
		if (i==next)
			$('#rating_star_'+i).css('background-position', '0 '+bgPos);
		else
			$('#rating_star_'+i).css('background-position', '0 -160px');
	}
	
	for (j=from;j<=5;j++) {
		$('#rating_star_'+j).css('background-position', '0 0');
	}

	if (showIndicator) {
		$('#'+prefix+'_rating_value').html('<img src="/images/ajax-loader.png" alt="" id="'+prefix+'_rating_process_indicator" />');
	} else {
		$('#'+prefix+'_rating_value').html('<span class="cufon">'+orig_value+'</span>'+'<img src="/images/ajax-loader.png" alt="" id="'+prefix+'_rating_process_indicator" />');
		Cufon.replace('#'+prefix+'_rating_value span');
	
		$('#'+prefix+'_rating_process_indicator').css('display', 'none');
	}
}

function postRate(value, prefix){
	$('#'+prefix+'_rating_value').html('<img src="/images/ajax-loader.png" alt="" id="'+prefix+'_rating_process_indicator" />');

	$('#'+prefix+'_rating_process_indicator').css('display', 'block');

	showIndicator = true;

	callAjax("rating", "setRating", this, [value, prefix], false, "parseRateResponse", "json");
}

function parseRateResponse(data){
	if(data){
		var obj = jQuery.parseJSON(data);

		value = obj.value+"";
		newRateValue = value.substr(0,3);

		decimal = value.substr(2,1);

		showIndicator = false;

		setRateValue(value, obj.prefix, decimal);
	}
}

//rating end


function setReminder(id, timestamp){
	$('#loader_indicator_'+id).css('display', 'block');
	$('#reminder_icon_'+id).css('display', 'none');

    //getObj('loader_indicator_'+id).style.display = 'block';
	//getObj('reminder_icon_'+id).style.display = 'none';
	callAjax("reminder", "addReminder", '#reminder_section_'+id, [id, timestamp], false, "", "htmli");
}

function unsetReminder(id, timestamp){
	$('#loader_indicator_'+id).css('display', 'block');
	$('#reminder_icon_'+id).css('display', 'none');

    //getObj('loader_indicator_'+id).style.display = 'block';
	//getObj('reminder_icon_'+id).style.display = 'none';
	callAjax("reminder", "removeReminder", '#reminder_section_'+id, [id, timestamp], false, "", "htmli");
}

/*function unsetReminder(id, response){

	if(response == undefined || response != 'no' ){
	    getObj('loader_indicator_'+id).style.display = 'block';
		callAjax("reminder", "removeReminder", '#reminder_section_'+id, [id, timestamp], false, "", "htmli");
	} else {
        callAjax("reminder", "removeReminder", '', [id, timestamp], false, "", "json");
	}
}
*/




function getObj(id){
	return document.getElementById(id);
}


function setFancyHref(obj){

    browserWidth = pageHeight();

	if(browserWidth > 900)
	    sizeId = '960';
    else if(browserWidth > 700)
	    sizeId = '768';
	else
	    sizeId = '600';


    filename = obj.href.substring(0, obj.href.length - 4);
	ext = obj.href.substring(obj.href.length - 4, obj.href.length);

	obj.href = filename.split("_-_")[0]+"_-_"+sizeId+ext;
}

function setFancyHref2(id){

	obj= document.getElementById(id);

    browserWidth = pageHeight();

	if(browserWidth > 900)
	    sizeId = '960';
    else if(browserWidth > 700)
	    sizeId = '768';
	else
	    sizeId = '600';


    filename = obj.href.substring(0, obj.href.length - 4);
	ext = obj.href.substring(obj.href.length - 4, obj.href.length);

	obj.href = filename.split("_-_")[0]+"_-_"+sizeId+ext;
}


function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;}
function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;}
function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}


function showCommentReply(id){
	$('#comment_reply_'+id).css('display', 'block');
	//document.getElementById("comment_reply_"+id).style.display="block";
}
function hideCommentReply(id){
	$('#comment_reply_'+id).css('display', 'none');
	//document.getElementById("comment_reply_"+id).style.display="none";
}
function hideNewComment(){
	$('#comment_new').css('display', 'none');
    //document.getElementById("comment_new").style.display="none";
}

function clearTextarea(id, defaultMsg) {
    if($('#'+id).val() == defaultMsg) {
        $('#'+id).val('');
    }
}
function resetTextarea(id, defaultMsg) {
    if($.trim($('#'+id).val()) == '') {
		$('#'+id).val(defaultMsg);
        //document.getElementById(id).value = defaultMsg;
    }
}
function setTextarea(id, defaultMsg) {
	$('#'+id).val(defaultMsg);
    //document.getElementById(id).value = defaultMsg;
}

function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength)
}

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;







//QUIZ

	function toggleQuizRules(){
	    if($('#quiz_rules').css('display') == 'none'){
	        $('#quiz_rules').show();
	    } else {
	        $('#quiz_rules').hide();
	    }
	}



	// HEADER STUFF
	ie5 = (document.all && document.getElementById);
	ns6 = (!document.all && document.getElementById);
	opacIn = 0;

	function fadeIn(divName) {

		id = document.getElementById(divName);

		if(opacIn!= 100){
			opacIn++;
			if(ie5) id.filters.alpha.opacity = opacIn;
			if(ns6) id.style.MozOpacity = opacIn/100;
			setTimeout('fadeIn("'+divName+'")', 10);
		}
	}


	function showLoginBox(){
		toggleLoginBox();
	}

	function showLanguageSelector(){
	    $('#available_language_header_container').css("display", "block");
	}
	function hideLanguageSelector(){
	    $('#available_language_header_container').css("display", "none");
	}

	function hideLoginBox(){
		$('#login_box').css({display: 'none'});
		hideOverflow();
		opacIn = 0;
	}

	function showOverflow(){
		$('#overlay').css({display: 'block'});
		$('#overlay').height($('body').height());
		$('#overlay').width($(document).width());
	}

	function hideOverflow(){
		$('#overlay').height(0);
	}






function strtruncate(string, leng) {

    needPoints = false;

    if(string.length > leng) needPoints = true;

	string = string.substr(0,leng);

	if(needPoints == true) string += "...";

	return string;

}




function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}


function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}


var setScheduleAdd_inProgress = false;
function setScheduleAdd(){
	if(setScheduleAdd_inProgress == false){
		$("#schedule_add_response").html('<img style="margin:0px" src="/images/site/ajax-cust-loader.gif" />');
		id = $("#schedule_add_id").html();
	    timestamp = $("#schedule_add_date").html();
		setScheduleAdd_inProgress = true;
	    callAjax("schedule", "setScheduleAdd", "#schedule_add_response", [id, timestamp], false, "", "htmli", "resetCustProgressVar");
	}
}

function resetCustProgressVar(){
	setScheduleAdd_inProgress = false;
}

function setScheduleRemove(id){
	$('#delete_indicator_'+id).css({display: 'inline'});
    callAjax("schedule", "setScheduleRemove", "", [id], false, "hideCustomScheduleEvent", "json");
}

function hideCustomScheduleEvent(data){

	id = data.substr(1,data.length-2);
    $('#'+ id).toggle('hide');
    return false;
}

function initAnimatedcollapse(){

	animatedcollapse.init();
}

function headerSearchSubmit(defaultText){
	if(document.getElementById('header_search_keyword').value!=defaultText && document.getElementById('header_search_keyword').value.length > 2){
	    document.headersearch.submit();
	}
}

$(function() {
 
	$("#more_onair_dates").click(function(){
		$("#hidden_onairs").toggle();
	})


});

function setSubMenu(content, item, id, type) {

	$('.movie_right_content').css('display', 'none');

	$('#'+content).css('display', 'block');

	if (type=="articles")
		$(".serie_article_font_size_box").css("display", "none");

	$('.anchor').removeClass('yellow');

	if (id!=false)
		$("#"+id).addClass('yellow');
	else
		$(item).addClass('yellow');

	Cufon.replace('.anchor');

	if ( $(".pageLeft").height() > $("#"+content).height() ) {
 		$("#"+content).height($(".pageLeft").height());
	}
}

function leaveAttachedContent(id, type) {
	$("#"+id).css("display", "none");
	$("#serie_main_content").css("display", "block");

	$.each( $(".serie_attached_menu>span.yellow"), function() {
		$(this).removeClass('yellow');
	});

	if(type == "articles")
		$(".serie_article_font_size_box").css("display", "block");

	Cufon.replace('.anchor');
}

function jumpTo(id) {
	var new_position = $("#"+id).offset();

	if($.browser.safari) bodyelem = $("body")
	else bodyelem = $("html")

	bodyelem.animate({scrollTop : new_position.top-30}, 700);

	return false;
}

function callUrl(url) {
	window.location.href = url;
}

function addToFavourites(itemid, itemtype){
	callAjax("favourites", "addFavourite", this, [itemid, itemtype], false, "", "json");

	$('#'+itemtype+'_'+itemid).css('display', 'none');
	$('#go_fav_'+itemtype+'_'+itemid).css('display', 'block');
}


