function RemoveConsecutiveValues(strString, strConValue){
	while (strString.indexOf(strConValue + strConValue) >= 0)
		strString = strString.replace(strConValue + strConValue, strConValue);
	return strString;
}	

function post_show_hide_all(id, obj) {
        if($('toggle_replies_'+id).src.indexOf('hide_all_replies.png')>0){
        	
                $('toggle_replies_'+id).src = "/phpf/debatt/images/default_article_small_show_all_replies.png";
                
                $$('#debatt_innlegg .hidden_'+id).each(Element.hide);
                $$('#innleggHolder_'+id+' .pil').each(function(el){

                        el.src = el.src.replace(/svar_pil_ned.png/, "svar_pil.png");

                });
        }
        else {
                $('toggle_replies_'+id).src = "/phpf/debatt/images/default_article_small_hide_all_replies.png";

                $$('#debatt_innlegg .hidden_'+id).each(Element.show);
                $$('#innleggHolder_'+id+' .pil').each(function(el){

                        el.src = el.src.replace(/svar_pil.png/, "svar_pil_ned.png");
                });
        }
}

function posts_show_hide_all(rtopics) {


        if($('toggle_replies').src.indexOf('hide_all_replies.png')>0){

                $('toggle_replies').src = "/phpf/debatt/images/default_article_small_show_all_replies.png";

                $$('.pil').each(function(el){

                        el.src = el.src.replace(/svar_pil_ned.png/, "svar_pil.png");
                        el.src = el.src.replace(/\/pil_ned.png/, "/pil.png");

                });

                $$('.innleggButton').each(function(el) {
                        el.innerHTML = el.innerHTML.replace(/Skjul alle svar/g, "Vis alle svar")
                        el.innerHTML = el.innerHTML.replace(/\/pil_ned.png/, "/pil.png")
                });

                for(i = 0;i< rtopics.length;i++){
                        $$('#debatt_innlegg .hidden_'+rtopics[i]).each(Element.hide);



                }

        }
        else{
                $('toggle_replies').src = "/phpf/debatt/images/default_article_small_hide_all_replies.png";
                $$('.pil').each(function(el){

                        el.src = el.src.replace(/svar_pil.png/, "svar_pil_ned.png");
                        el.src = el.src.replace(/\/pil.png/, "/pil_ned.png");


                });

                $$('.innleggButton').each(function(el) {
                        el.innerHTML = el.innerHTML.replace(/Vis alle svar/g, "Skjul alle svar")
                        el.innerHTML = el.innerHTML.replace(/\/pil.png/, "/pil_ned.png")

                });

                for(i = 0;i< rtopics.length;i++){

                        $$('#debatt_innlegg .hidden_'+rtopics[i]).each(Element.show);


                }
        }

}


function post_show_hide(nr, obj) {

        if (obj.innerHTML.indexOf('svar_pil_ned.png')>0) {
                $('svar_'+nr).hide();
                obj.innerHTML = '<img class="pil" src="/phpf/debatt/images/svar_pil.png" alt="reply_arrow" />';
        } else {
                $('svar_'+nr).show();
                obj.innerHTML = '<img class="pil" src="/phpf/debatt/images/svar_pil_ned.png" alt="reply_arrow" />';
        }


}

function post_show_hide_p(nr, obj) {

        obj = document.getElementById(obj);

        if (obj.innerHTML.indexOf('svar_pil_ned.png')>0) {
                $('svar_'+nr).hide();
                obj.innerHTML = '<img class="pil" src="/phpf/debatt/images/svar_pil.png" alt="reply_arrow" />';
        } else {
                $('svar_'+nr).show();
                obj.innerHTML = '<img class="pil" src="/phpf/debatt/images/svar_pil_ned.png" alt="reply_arrow" />';
        }


}
function closeReplyOrphan(){
       	$$('#debatt_innlegg .confinedRelative').each(function(el){
                el.style['height'] = "0px";
        });
	$$('#debatt_innlegg .nonConfined').each(function(el){
		el.style['top'] = "0px";
		el.innerHTML = '';
                el.hide();
        });        
	if($('debatt_ad2')){
		$('debatt_ad2').style['display']	 = 'block';
	}        
}

function post_reply(nr,title, id,poster_name,post_date) {

	if($('debatt_ad2')){
		$('debatt_ad2').style['display']	 = 'none';
	}
	$$('#debatt_innlegg .nonConfined').each(function(el){
		el.innerHTML = '';	
                el.hide();
        });
        $$('#debatt_innlegg .confinedRelative').each(function(el){
		el.innerHTML = '';
                el.hide();
        });
	$('confinedAnchor_'+id).show();

	var clearString = '<div class="clear"></div>';
        $('replyChild_'+id).innerHTML =  $('displacementHolder').innerHTML + clearString;

        $('reply-to').value = id;
        $('post_title_reply').value = title;
//	Removed SV
//        $('post_title_reply').value = 'SV: '+title;        
        $('replyChild_'+id).style['height'] = "270px";
        if(nr != 0){
        	
	        $('svar_'+nr).show();
		$('a_phide_'+id).innerHTML = '<img class="pil" src="/phpf/debatt/images/svar_pil_ned.png" alt="reply_arrow" />';
		$('confinedAnchor_'+id).style['height'] = ( 40 + $('replyChild_'+id).getHeight() ) + 'px';
	        $('replyChild_'+id).style['top'] = ( 52 + $('svar_'+nr).getHeight() ) + 'px';	
        }
        else{
	        $('replyChild_'+id).style['top'] = ( 87 + $('post_id_'+id).getHeight() ) + 'px';	
	        $('confinedAnchor_'+id).style['height'] = '290px';

	        
        }

	
        

        $('replyChild_'+id).show();


	
	
	$('post_reply_reply').value = '';
	

	$('post_reply_reply').focus();
	$('post_reply_reply').style['border']	= "2px solid black";
       	setTimeout('observeFormReply()', 1000);
       	setTimeout('observeShowLogin()', 1000);       	
        ///return(true);
        
}

function post_abuse(id) {
        var text = 'Hvorfor du mener innlegget er støtende (minst fire tegn)';
        var mesage = window.prompt("Rapporter støtende eller upassende innlegg",text);

        if (mesage.length>5 && mesage!=text) {
                url = "/phpf/debatt/abuse.php?id="+id+"&m="+encodeURIComponent(mesage);
                new Ajax.Request(url, {
                        onSuccess: function(transport) {
                                eval(transport.responseText);
                        }
                });
        }
        return(false);
}

function debatt_order_turn() {
        if (debatt_order == "desc") debatt_order = "asc";
        else debatt_order = "desc";
        post_populate();
        return (false);
}

var all;
var tdata;      

function fetchDebateData(callback){
	if(number_of_posts > 0){
                url = "/phpf/debatt/view_article-topic.js.php?aid="+debatt_aid+"&order="+debatt_order+"&total="+number_of_posts;
        }
        else{
                url = "/phpf/debatt/view_article-topic.js.php?aid="+debatt_aid+"&order="+debatt_order;
        }
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			tdata = transport.responseText;
			callback(tdata);
		}
	});
}

function initDebate(action){
	var processData = function(tdata){
		eval(tdata);
		if (topic_count<1) {
	                $("debatt_top").hide();
			$('debatt_innlegg').hide();	        	
	                
	
	        }
	        else if (topic_count == 0){
			$('debatt_innlegg').hide();
	                $("debatt_legginn_header").hide();
	        
	        }
		else {
			$('debatt_innlegg').show();
	                $('debatt_top').show();

	                
	                if(action> 0){
	        		
	        		
	                	page_start = findPage(action);
	        		
	        		populatePage(page_start);    
	        	}
	        	else{
	        		populatePage(0);    
	        	}
	                
	        }
		
	}
	fetchDebateData(processData);
}



function populatePage(start){	
	//Lagt til try catch her for at det ikke skal bli feil ved første innlegg
	try {
		if($('toggle_replies').src.indexOf('hide_all_replies.png')>0){
			$('toggle_replies').src = "/phpf/debatt/images/default_article_small_show_all_replies.png";
		}
	} catch (err) {
		//Error handling		
	}
		
        level = 0;
        all = 1;
        var html = [];                
        var page_size;
        var page_size_end;
        
	if(start>0){
		next = start + 20;
		y = start-1;
		prev = start - 20;
		page_size = next;
		if(start < 20){
			y = 0;
			page_size = 20;
			prev = 0;
		}				
	}
	else{
		page_size = 20;
		start = 1;
		y = 0;
		next = 20;
		prev = 0;
	}
	
        parent_first = 0;
        x = 0;
        n = 0;
        while(y<page_size && (typeof topic_parent[y] != 'undefined')) {
        	
		if(topic_parent[y+1] != 0){
	        	page_size_end = page_size;
			page_size++;		        	
	        }
	        else{
	        	page_size = next;
	        }
	        
		topic_level[y] = parseInt(topic_level[y]);
		

                if (level>=topic_level[y]) {

                        for(i=level;i>=topic_level[y];i--) {

                        }
                }
                
                
                if (topic_level[y]<2){                	
                	if(parent_first == 0){
                		x = y + 1;
                	}
                	parent_first++;
                        post_id = topic_pid[y];
                        html.push('	<div class="innlegg" id="innleggHolder_'+topic_pid[y]+'">');
                        html.push('		<div class="inner">');
                        html.push('			<a name="innlegg_'+ topic_pid[y] +'"></a>'+"\n");
                        html.push('			<div class="postHeader">'+"\n");                        			
                        if(topic_poster_avatar[y]){
                                html.push('			<div class="posterAvatar">'+"\n");                        			                                
                                html.push('				<a href="/phpf/debatt/index.php?showuser='+topic_author_id[y]+'">');
                                html.push('					<img src="'+ topic_poster_avatar[y] +'" alt="Avatar" class="debatt_avatar"/>');
                                html.push('				</a>');
	                        html.push('			</div>'+"\n");                                      
                        }
                                html.push('			<div class="postTitle">'+"\n");                        			                                
                                html.push('            	 		<h2>'+topic_title[y]+'</h2>'+"\n");
                                html.push('             		<h3>');
                                html.push('					av');
                                html.push('					<strong>');
                        
                        if(topic_email[y]){
                                html.push('  						<a href="mailto:' + topic_email[y] + '">');
                        }

                        html.push(stripslashes(stripslashes(topic_author[y])));
                        if(topic_email[y]){
                                html.push('             		        	</a>');
                        }
                        
                        html.push('                   				</strong> ');
                        html.push('					</h3>'+"\n");
                        html.push('					<div class="postOptions">'+"\n");                          
                        html.push('						<a class="klag" href="#innlegg_'+ topic_pid[y] +'" title="Link til dette innlegget" onclick="window.location.href=\'#innlegg_'+ topic_pid[y] +'\';focus_post('+ topic_pid[y] +');">');
                        html.push('							lagt inn ' + time2str(topic_date[y])+' ');
                        html.push('						</a>&nbsp;&nbsp;');                        
                        html.push('						<a class="klage" href="#" onclick="post_abuse('+topic_pid[y]+');return false;">');
                        html.push('							varsle');
                        html.push('						</a>');                      
	                html.push('					</div>'+"\n");                                                  
                        html.push('				</div>'+"\n");                          
                        html.push('			</div>'+"\n");                        
                        html.push('                	<div id="post_id_'+post_id+'" class="post post_'+post_id+'">'+topic_post[y]+'</div>'+"\n");
                        html.push('                	<div class="innleggButtons">'+"\n");
                        if(topic_state == 'open'){
	                        html.push('                     	<a onmouseout="" href="javascript:;" title="skriv et svar til innlegget" onclick="post_reply(0,\''+topic_title[y]+'\','+topic_pid[y]+',\''+topic_author[y]+'\',\''+(topic_date[y])+'\')">');
	                        html.push('					<img src="/phpf/debatt/images/default_article_small_reply_to_post.png" alt="Svar på innlegg '+topic_pid[y]+'">');
	                        html.push('				</a>'+"\n");
	                }
                        if (topic_repl[y]>0) {
                                
                                html.push('			<a href="javascript:;" onclick="post_show_hide_all('+topic_pid[y]+', this);">');
                                html.push('				<img id="toggle_replies_'+ topic_pid[y] +'" src="/phpf/debatt/images/default_article_small_show_all_replies.png" alt="Vis alle svar"/>');
                                html.push('			</a>');
                                html.push('		</div>'+"\n");
                        } 
			else {
                                html.push('             </div>'+"\n");                                
                        }
	                html.push('			<div id="confinedAnchor_'+topic_pid[y] +'"  class="confinedRelative"></div><div id="replyChild_'+ topic_pid[y] +'" class="nonConfined "></div>');                        
	                html.push('</div></div>');
                } 
                else{
                	if(parent_first != 0){                		
	                        all++;
	                        html.push('	<div class="svar">');
	                        html.push('		<div id="replyContainer_'+ topic_pid[y] +'" class="reply_level_' + topic_level[y] + '">');
	                        html.push('			<a name="innlegg_'+ topic_pid[y] +'"></a>'+"\n");
	                        html.push('                     	<div class="header">');
	                        if(topic_state == 'open'){
			                html.push('					<div class="innleggButtons" style="float:right; background-color:#efefef;margin-right:-8px; margin-top:0px; z-index:10; position:relative;">');
			                html.push('						<div class="innleggButtonSvar">');
			                html.push('							<div class="inner">');
			                html.push('								<a href="javascript:;" title="skriv et svar til innlegget" onclick="post_reply('+ y +',\''+topic_title[y]+'\','+topic_pid[y]+',\''+stripslashes(topic_author[y])+'\',\''+(topic_date[y])+'\')">');
			                html.push('									<img src="/phpf/debatt/images/svar.png" alt="Svar på innlegg '+ topic_pid[y] +'"/>');
			                html.push('								</a>');
					html.push('	                        			</div>');
					html.push('						</div>');
					html.push('					</div>'+"\n");	                        
	                        }

	                        html.push('                             	<a href="#" id="a_phide_'+topic_pid[y]+'" onclick="post_show_hide('+y+', this);return(false);" title="Les dette svaret">');
	                        html.push('						<img id="pil_'+all+'" class="pil svarpil" src="/phpf/debatt/images/svar_pil.png" alt="reply_arrow" />');
	                        html.push('					</a>'+"\n");
                                html.push('			<div class="posterAvatar"');
                                if(topic_poster_avatar[y] == ''){
	                                html.push(' style="width:1px;"');                                
                                }

                                html.push('>'+"\n");                        			                                	                        
	                        if(topic_poster_avatar[y] != ''){

	                                html.push('				<a href="/phpf/debatt/index.php?showuser='+topic_author_id[y]+'">');
	                                html.push('					<img src="'+ topic_poster_avatar[y] +'" alt="Avatar" class="debatt_avatar_small"/>');
	                                html.push('				</a>');
                                
	                        }
	                        html.push('			</div>'+"\n");		                        
                                html.push('			<div class="postTitle">'+"\n");	                        
	                        html.push('                                	<h2 style="cursor:pointer; z-index:1;overflow:hidden;" onclick="post_show_hide_p('+y+',\'a_phide_'+topic_pid[y]+'\');return(false);">SV:&nbsp;'+topic_title[y].replace(/ /g, "&nbsp;").substr(0,200) );
	                        if(topic_title[y].length > 200){
	                        	html.push('...');
	                        }
	                        html.push('					</h2>'+"\n");// placeholder, for absolute title position
	                        html.push('                                	<h3 style="cursor:default;" >');
	                        html.push('						av ');
				html.push('	                        		<strong>');
	                        if(topic_email[y]){
	                                html.push('                                     	<a href="mailto:' + topic_email[y] + '">');
	                        }
	
	                        html.push( stripslashes(stripslashes(topic_author[y])));
	                        if(topic_email[y]){
	                                html.push('                                     	</a>');
	                        }
	                        html.push('                                     	</strong> ');
	                        html.push('					</h3>'+"\n");
	                        html.push('					<div class="postOptions" style="margin-left:-2px; margin-top:1px; float:left;">'+"\n");                          	                        
	                        html.push('						<a href="#innlegg_'+ topic_pid[y] +'" class="klag" title="Link til dette innlegget" onclick="window.location.href=\'#innlegg_'+ topic_pid[y] +'\';focus_post('+ topic_pid[y] +');">');	                        
	                        html.push(time2str(topic_date[y])+' ');
	                        html.push('						</a>');	                        
	                        html.push('						&nbsp;&nbsp;');
	                        html.push('						<a class="klage" href="#" onclick="post_abuse('+topic_pid[y]+');return false;">');
	                        html.push('							varsle');
	                        html.push('						</a>&nbsp;');	                        
		                html.push('					</div>'+"\n");		             	                        
		   
             html.push('			</div>'+"\n");		                        
html.push('<div style="clear:both; height:1px;"></div>');
	                        html.push('                        	</div>'+"\n");
	                        html.push('                        	<div class="hidden_'+post_id+' post post_'+topic_pid[y]+'" id="svar_'+y+'" style="display:none">'+topic_post[y]+'</div>'+"\n");	                        
				html.push('				<div id="confinedAnchor_'+topic_pid[y] +'" class="confinedRelative"></div><div id="replyChild_'+ topic_pid[y] +'" class="nonConfined "></div>');
		                html.push('</div></div>');
                	}
                }

                level = topic_level[y];                
                y++;		
        }        

        if (level >= topic_level[y] && topic_level[y] == 1) {
                for(i = level; i >= topic_level[y]; i--) {

                }
        }

        last_page = total_topic_count - (total_topic_count %  20);
        
        total_pages = Math.ceil(total_topic_count / 20 );
        
        
        
        num_page1 = Math.ceil(start / 20) ;
        num_page2 = Math.ceil(start / 20) +1;
        num_page3 = Math.ceil(next / 20) +1;
        pagemenu = '<div class="debatePageMenu" ';
                if(total_pages == 1){
                	pagemenu	+= 'style="height:0px;padding:0px;margin:0px; border:0px;"';
                }
        pagemenu += '>';

        if(total_pages != 1){
		pagemenu += '			<div class="debatePageInfo">';
		pagemenu += '				Viser innlegg ' + x + '-&gt;';
		pagemenu += '			</div>';
        }
        
        if(total_pages != 1){
	        pagemenu += '			<div class="debatePageLinks">';
	        if(start != 1){
	        	pagemenu += '				<a style="font-weight:bold;" href="#debattfelt" onclick="populatePage(' + prev + ');" title="'+ prev +'"><img style="margin-bottom:-1px;" src="/phpf/debatt/images/pil_venstre.png" alt=""/>&nbsp;Forrige side</a>';        
	        	
	        	pagemenu += '				<a href="#debattfelt" onclick="populatePage();">F&oslash;rste side</a> ';
	        	
	        	if(num_page1 >= 1){
	        		pagemenu += '<a href="#debattfelt" onclick="populatePage(' + prev + ');" title="'+ prev +'">'+num_page1+'</a> ';	
	       		}
	        } 
	        else{
	        	pagemenu += '				<a class="disabledPageLink" style="cursor:default;color: #e9e9e9;border:1px solid #e9e9e9;" href="#debattfelt">Forrige side</a>';        
	        	pagemenu += '				<a class="disabledPageLink" style="cursor:default;color: #e9e9e9;border:1px solid #e9e9e9;" href="#debattfelt">F&oslash;rste side</a> ';
	        }      
	        
	        if((num_page2) >= 1){
	        	if(start == 1){
	        		num_page2 = 1;
	        	}
	        	pagemenu += '<a href="#debattfelt" class="markedPage" style="font-weight:bold;color:white;">'+num_page2+'</a> ';
	        }
	        
	        
	        
	        if(start != last_page){
	        	if(num_page3 > 0){
		        	pagemenu += '<a href="#debattfelt" onclick="populatePage('+ next +');" title="'+ next +'">'+num_page3+'</a> ';
	        	}
	        	pagemenu += '				<a href="#debattfelt" onclick="populatePage('+ last_page +');" title="'+ last_page +'">Siste side ('+(total_pages)+')</a>';        
	        	
	        	pagemenu += '				<a style="font-weight:bold;" href="#debattfelt" onclick="populatePage('+ next +');" title="'+ next +'">Neste side&nbsp;<img style="margin-bottom:-1px;" src="/phpf/debatt/images/pil_hoyre.png" alt=""/></a>';
	        }
	        else{
	       		pagemenu += '				<a class="disabledPageLink" style="cursor:default;color: #e9e9e9;border:1px solid #e9e9e9;" href="#debattfelt">Siste side</a>';        
	        	pagemenu += '				<a class="disabledPageLink" style="cursor:default;color: #e9e9e9;border:1px solid #e9e9e9;" href="#debattfelt">Neste side</a>';
	        }
	        pagemenu += '			</div>';
        }
        pagemenu += '</div>';
        
	$('debatt_innlegg').innerHTML = '';	
	var debateNetboardElement = '<div id="debatt_ad2" class="netboardArea noprint hide" style="height:auto; display:none;border:0px;">' + $("debatt_ad1").innerHTML + '</div>';
        $('debatt_innlegg').innerHTML = pagemenu + debateNetboardElement + html.join('') + pagemenu;     
	$("debatt_ad2").style['display']	 = 'inline';
	$("debatt_ad1").hide();
	setTimeout('focus_post(innlegg_id)',2000);							
}

function post_populate(start) {


	if(start){
		populatePage(start);		
	}
	else{
		initDebate(0);			
	}	
}

function initSearch(pid){
	initDebate(pid);
}

function findPage(pid){
	notfound 	= 0;
	n 		= 0;
	start_page	= 0;
	while(notfound != 1 && n < total_topic_count){
	
		if(topic_pid[n] == pid){
			start_page = n;
			notfound = 1;
		}
		n++;		
	}
	start_page = start_page - (start_page %  20);
	return start_page;
}
function stripslashes(str) {

	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Ates Goral (http://magnetiq.com)
	// +      fixed by: Mick@el
	// +   improved by: marrtins
	// +   bugfixed by: Onno Marsman
	// +   improved by: rezna
	// +   input by: Rick Waldron
	// +   reimplemented by: Brett Zamir (http://brett-zamir.me)
	// *     example 1: stripslashes('Kevin\'s code');
	// *     returns 1: "Kevin's code"
	// *     example 2: stripslashes('Kevin\\\'s code');
	// *     returns 2: "Kevin\'s code"
	return (str+'').replace(/\\(.?)/g, function (s, n1) {
		switch(n1) {
		    case '\\':
			return '\\';
		    case '0':
			return '\0';
		    case '':
			return '';
		    default:
			return n1;
		}
	});

}
function focus_post(innlegg_id){

	if ($('replyContainer_'+innlegg_id) !== null) {
		$('replyContainer_'+innlegg_id).style['padding'] = '10px';
		$('replyContainer_'+innlegg_id).style['background'] = '#ffffa3';
		$$('.post_'+innlegg_id).each(function(el){
			el.style['display']	= 'block';
		});
	}
	else{
		$('innleggHolder_'+innlegg_id).style['padding'] = '10px';
		$('innleggHolder_'+innlegg_id).style['background'] = '#ffffa3';
	}
}
