/**
 * Centering of site
 */

var windowCenter = {
	contentWidth:960,
	running:true,
	leftBannerWidth:0,
	rightBannerWidth:0,
	currwidth:0,
	isTopMonsterPositioned:false,
	init : function() {
		var self = this;
		self.docenter();
		$p(window).resize(function(){
				if(windowCenter.currwidth != $p(window).width()){
					windowCenter.log("resizing");
					windowCenter.centerAll(true);
					windowCenter.currwidth = $p(window).width();
				}
		});
	},
	docenter : function() {
		this.log("centeringFull");
		shift = ($p(window).width() - this.contentWidth) / 2;
		windowCenter.fullOffset = this.contentWidth + Math.ceil(Math.abs(shift));
		this.log("offset" + this.fullOffset);
		if($p("#top-monster").length >0){
			windowCenter.positionTopMonster();
		}
		if (($p("#leftBanner").length == 0) && ($p("#rightBanner").length == 0)&& this.running) {
			this.timeOutId=window.setTimeout(function(){windowCenter.docenter();},200);
			return;
		}
		window.clearTimeout(this.timeOutId);
		windowCenter.centerAll();
	},
	stop : function() {
		windowCenter.running=false;
		windowCenter.positionTopMonster();
		//windowCenter.currwidth = 0; /*force to center after loading*/
		windowCenter.centerAll(true);
		windowCenter.isTopMonsterPositioned=true;
	},
	centerAll : function(isResize) {
		leftBannerWidth = $p("#leftBanner").width();
		$p("#leftBanner object").each(function(){
	        if ($p(this).width() > leftBannerWidth)
	        	leftBannerWidth = $p(this).width();   
	    });
		$p("#leftBanner embed").each(function(){
			if ($p(this).width() > leftBannerWidth)
				leftBannerWidth = $p(this).width();   
		});
		rightBannerWidth = $p("#rightBanner").width();
		if(windowCenter.running){
			this.timeOutId=window.setTimeout(function(){windowCenter.centerAll();},200);	
		}else{
			window.clearTimeout(this.timeOutId);
		}
		if(!isResize && (windowCenter.currwidth == $p(window).width()) && (windowCenter.leftBannerWidth == leftBannerWidth) && (windowCenter.rightBannerWidth == rightBannerWidth)){
			return;
		}
		windowCenter.currwidth = $p(window).width();
		windowCenter.positionTopMonster();
		windowCenter.leftBannerWidth=leftBannerWidth;
		windowCenter.rightBannerWidth=rightBannerWidth;
		windowCenter.log("leftBanner:" + leftBannerWidth);
		windowCenter.log("rightBanner:" + rightBannerWidth);
		var shift = Math.ceil(($p(window).width() - this.contentWidth) / 2);
		if(Math.max(leftBannerWidth, rightBannerWidth)<shift){
			this.log("big, shift:" + shift);
			$p("#leftBanner").css("right",'');
			$p("#leftBanner").css("left", shift-leftBannerWidth);
			$p("#rightBanner").css("left", shift + windowCenter.contentWidth);
			if(isResize){
				this.setContentMarginLeft(shift);
			}
			return;
		}
		var pageWidth = $p(window).width();
		windowCenter.log("small, shift:" + shift);
		if(leftBannerWidth>shift){
			windowCenter.log("big left banner");
			pageWidth += (leftBannerWidth-shift);
			$p("#leftBanner").css("right",'');
			$p("#leftBanner").css("left", 0);
			contentMargin=leftBannerWidth - Math.ceil(windowCenter.getScrollbarWidth()/2);
		}else{
			windowCenter.log("small left banner");
			contentMargin=shift;
			pageWidth += shift;
		}
		if(rightBannerWidth>shift){
			windowCenter.log("big right banner");
			pageWidth += Math.round((rightBannerWidth-shift - Math.ceil(windowCenter.getScrollbarWidth()/2)));
		}else{
			windowCenter.log("small right banner");
			pageWidth += shift;
		}
		$p("#rightBanner").css("left", contentMargin + windowCenter.contentWidth + windowCenter.getScrollbarWidth()/2);
		$p('#page').width(pageWidth-windowCenter.getScrollbarWidth());
		this.setContentMarginLeft(contentMargin + Math.ceil((windowCenter.getScrollbarWidth()/2)));
		window.scrollTo(leftBannerWidth-shift, document.documentElement.scrollTop);
	},
	setContentMarginLeft : function(marginLeft){
		$p('#content').css("margin-left", marginLeft);
		$p('#polHeaderForPartner').css("margin-left", marginLeft);
		$p('#pol-align-partner').css("margin-left", marginLeft);
	},
	log : function(msg) {
		if (window.console) {
			window.console.log(msg);
		}
	},
	getScrollbarWidth : function() {
		if (windowCenter.scrollBarWidth) {
			return windowCenter.scrollBarWidth;
		}
		;
		var div, w1, w2;
		div = $p('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>');
		// Append our div, do our calculation and then remove it
		$p('body').append(div);
		w1 = $p('div', div).innerWidth();
		div.css('overflow-y', 'scroll');
		w2 = $p('div', div).innerWidth();
		$p(div).remove();
		windowCenter.scrollBarWidth = (w1 - w2);
		windowCenter.log("scrollBarWidth:" + windowCenter.scrollBarWidth);
		if (windowCenter.scrollBarWidth == 0) {
			windowCenter.scrollBarWidth = 16;
		}
		return windowCenter.scrollBarWidth;
	},
	positionTopMonster : function(){
		if(this.isTopMonsterPositioned){
			return;
		}
		var rightcontent = $p("#rightBanner *").length; 
		this.log(rightcontent);
		if(($p("#rightBanner object").length>0) || ($p("#rightBanner embed").length>0)){
			this.isTopMonsterPositioned=true;
			$p("#top-monster").addClass('pol-right');
			return;
		}
		if($p("#rightBanner img").length>0) {
			var imgtag = $p("#rightBanner img:first").attr('src');
			if (imgtag.indexOf("adtech") > 1 && imgtag.indexOf("1x1trans.gif") > 1) {
				this.isTopMonsterPositioned=true;
				$p("#top-monster").removeClass('pol-right');
				return;
			} else if (imgtag.indexOf("1x1trans.gif") < 1 ) {
			this.isTopMonsterPositioned=true;
			$p("#top-monster").addClass('pol-right');
		} else if (imgtag.indexOf("adtech") < 1) {
			this.isTopMonsterPositioned=true;
			$p("#top-monster").addClass('pol-right');
		}}
	}
};

windowCenter.init();
$p(window).load(windowCenter.stop);

/* common functions, needs know about jquery $p and general plugins */
function openPopup(url, width, height, left, top, opIsResizable, opIsScrolbars) {
	var resizable, scrollbars;
	resizable = (opIsResizable) ? 'yes' : 'no';
	scrollbars = (opIsScrolbars) ? 'yes' : 'no';
	window.open(url, '_blank',
			'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars='
					+ scrollbars + ', resizable=' + resizable
					+ ', copyhistory=no, width=' + width + ', height=' + height
					+ ', left=' + left + ', top=' + top);
}

/*load page from garnnogle select box */
function loadFromGarnnogle(el) {
	var url = $p(el).val();
	if (url != '')
		window.location.href = url;
}
/*toolbox staff (article view)*/
addthis_pub = 'politiken';
function saveResizing(size){
	if($p.cookies.test()) $p.cookies.set('textsize', size ,{hoursToLive:8760});		
}
function loadResizing(){
	if($p.cookies.test()){
		var size = $p.cookies.get('textsize', {hoursToLive:8760});
		if(size) $p('#tbSize' + size).click();
	}
}
function initResizingTool(){
	$p('#tbSize1').click( function() {
		saveResizing(1);
		$p("#art-body p:not([class]),#art-body,#art-body p.bl-elem").css({"font-size":"14px","line-height":"17px"});
		$p("#art-body li:not([class]),#art-body").css({"font-size":"14px","line-height":"17px"});
		$p("#tbSize1").removeClass("art-size-1").addClass("art-size-1_active");
		$p("#tbSize2").removeClass("art-size-2_active").addClass("art-size-2");
		$p("#tbSize3").removeClass("art-size-3_active").addClass("art-size-3");
		$p('#art-size').removeClass('c-c00');
	});
	$p('#tbSize2').click( function() {
		saveResizing(2);
		$p("#art-body p:not([class]),#art-body,#art-body p.bl-elem").css({"font-size":"16px","line-height":"19px"});
		$p("#art-body li:not([class]),#art-body").css({"font-size":"16px","line-height":"19px"});
		$p("#tbSize2").removeClass("art-size-2").addClass("art-size-2_active");
		$p("#tbSize1").removeClass("art-size-1_active").addClass("art-size-1");
		$p("#tbSize3").removeClass("art-size-3_active").addClass("art-size-3");
		$p('#art-size').removeClass('c-c00');
	});
	$p('#tbSize3').click( function() {
		saveResizing(3);
		$p("#art-body p:not([class]),#art-body,#art-body p.bl-elem").css({"font-size":"18px","line-height":"21px"});		
		$p("#art-body li:not([class]),#art-body").css({"font-size":"18px","line-height":"21px"});
		$p("#tbSize3").removeClass("art-size-3").addClass("art-size-3_active");
		$p("#tbSize1").removeClass("art-size-1_active").addClass("art-size-1");
		$p("#tbSize2").removeClass("art-size-2_active").addClass("art-size-2");
		$p('#art-size').removeClass('c-c00');
	});
	$p('#tbSize1,#tbSize2,#tbSize3').hover(function(){
		if(!$p(this).is('.art-size-1_active,.art-size-2_active,.art-size-3_active'))
			$p('#art-size').addClass('c-c00'); }, function(){$p('#art-size').removeClass('c-c00');});
	loadResizing();
}

function setCommentsCount() {
	var comCnt = (window.jsonThreadInfo) ? jsonThreadInfo.postings : 0;
	var comText = (comCnt == 0) ? 'Kommenter' : ((comCnt == 1) ? '1 kommentar'
			: comCnt + ' kommentarer');
	$p('#tbComment').html(comText);
}

/*send box*/
var sendBox = {
	articleUrl : '',
	rubric:'',
	init : function(url, rubric) {
		var obj = this;
		obj.articleUrl = url;
		obj.rubric = rubric;
			$p('#send_art').mouseover( function() {
				$p(this).css( {
					'color' : '#c00'
				})
			}).mouseout( function() {
				$p(this).css( {
					'color' : '#73756B'
				})
			}).click(function(){
					$p('#send-header').show();
					$p('#send-body').show();			
					$p('#conf-header').hide();
					$p('#conf-body').hide();
					$p('#tool-send').show();});

			$p('#send_close').click( function() {
				$p('#tool-send').hide();
			});

			$p('#sendBtn').click( function() {
				if (obj.validate())
					obj.send();
				return false;
			});	
	},
	validate : function() {
		var isValid = true, recips = $p('#sendRecipients').val(), sender = $p(
				'#sendSender').val();
		var emailReg = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var emailsReg = /^(([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)(,([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)*$/;

		$p('#sendRecipients').each( function() {
			$p(this).removeClass('er');
			if (!emailsReg.test($p(this).val().replace(/ /g, ''))) {
				$p(this).addClass('er');
				isValid = false;
			}
		});

		$p('#sendSender').each( function() {
			$p(this).removeClass('er');
			if (!emailReg.test($p(this).val())) {
				$p(this).addClass('er');
				isValid = false;
			}
		});

		return isValid;
	},
	send : function() {
		var obj = this;
		$p.ajax({contentType: "application/x-www-form-urlencoded;charset=utf-8", url:this.articleUrl, type:"POST", data:{service:'send', recipients:$p('#sendRecipients').val(), sender:$p('#sendSender').val(), message:$p('#sendMessage').val()}, success: function(data){
			var header = '', message = '';
			switch($p.trim(data)){
				case '0': header = 'Tak';
					message = '<p>Du har nu sendt <span class="c-333"><b>' + obj.rubric + '</b></span> til:</p><p>' + 
					$p('#sendRecipients').val().replace(',', '<br/>') + '</p>';
					break;
				case '1': header = 'Fejl';
					message = '<p>Indtast en gyldig email-adresse</p>';
					break;				
				default: header = 'Fejl';
					message = '<p>E-mailen blev ikke sendt</p>';				
			}
			
			$p('#send-header').hide();
			$p('#send-body').hide();			
			$p('#conf-header').html(header).show();
			$p('#conf-body').html(message).show();			
		}});			
	}
};

/* extentions for commentHelper (used for Direkte)*/
function preSubmitActionDirekte()
{ 
	if($p('#fmCommentForm [name=ad]').val() == 'Adresse')
	    $p('#fmCommentForm [name=ad]').val('');    
	if($p('#fmCommentForm [name=ph]').val() == 'Tlf')
	    $p('#fmCommentForm [name=ph]').val('');                   
	
	$p('#fmCommentForm [name=question]').val($p('#fmCommentForm [name=bo]').val());	
	$p('#fmCommentForm [name=name]').val($p('#fmCommentForm [name=fn]').val());
	$p('#fmCommentForm [name=lastname]').val($p('#fmCommentForm [name=ln]').val());
	$p('#fmCommentForm [name=city]').val($p('#fmCommentForm [name=ci]').val());
	$p('#fmCommentForm [name=address]').val($p('#fmCommentForm [name=ad]').val());
	$p('#fmCommentForm [name=email]').val($p('#fmCommentForm [name=em]').val());
	$p('#fmCommentForm [name=phone]').val($p('#fmCommentForm [name=ph]').val());
}

function getPagerItemHtmlDirekte(post, isLast)
{ 
	var html = '<div class="auth-line question-icon m-top15"><span class="qu-user">' +
		post.firstname + ((post.lastname != '')? ' ' + post.lastname: '') + ((post.city !='')? ', ' + post.city: '') + 
	    '</span><span class="date">&nbsp;' + getTimeStamp(post.date) + '</span></div>' + 
	    '<p class="no-border">' + post.text.replace(/\r\n/g, '<br/>') + '</p>';
	
	for(var j = 0; j < post.answers.length; j++)	
	    html += '<div class="auth-line attention-icon"><span class="an-user">' + post.answers[j].replier + '</span><span class="date">&nbsp;' + 
	    getTimeStamp(post.answers[j].date) + '</span></div><p>' + post.answers[j].text.replace(/\r\n/g, '<br/>') + '</p>';
	return html;
}

function getPagerHeaderHtmlDirekte()
{
	return '(' + commentHelper.postings.length + ')';
}

var monthsShort = ['JAN','FEB','MAR','APR','MAJ','JUN','JUL','AUG','SEP','OKT','NOV','DEC'];

function getTimeStamp(d)
{
	return d.substring(11, 16) + ' ' + parseInt(d.substring(0,2)) + '. ' + monthsShort[(parseInt(d.substring(3,5)) - 1)];
}

/* tjek zone kogebogen search */
function initTjekzoneSearch()
{
	$p('#tjek-zone form').submit(function(){
		var str =$p('#kogebogenSearchText').val();
		if(str && str != 'S\u00F8g p\u00E5 opskrift/ingredienser')
			return true;	
		return false;
	});	
	$p('#kogebogenSearchText').keypress(function(event){ 
		if(event.which == 13)
			$p('#tjek-zone form').submit();			
	}).blur(function(){
		if($p(this).val() == '') $p(this).val('S\u00F8g p\u00E5 opskrift/ingredienser');
	}).focus(function(){
		if($p(this).val() == 'S\u00F8g p\u00E5 opskrift/ingredienser') $p(this).val('');
	});
}

/* Blue book */
function initBlueBook()
{
	$p(function(){		
		$p('#blue-book a.tooltip').click(function(e){ 
			$p('#blue-book a.tooltip.active').removeClass('active');
			$p('#blue-book div.bluebook_content:visible').hide();
			$p('#' + $p(this).attr('id').replace('tooltip', 'bluebook')).show();			
			$p(this).addClass('active');
			e.stopPropagation();
		});
	});
}

/* extends comment functionality to support recommendations */
var postingRecommender = {
	recommended:{},
	complained:{},
	recurl:'',
	comurl:'',
	init: function(recurl,comurl){
		this.recurl = recurl;	
		this.comurl = comurl;
		if($p.cookies.test()){
	         var c = $p.cookies.get('recpostings');
	         if(c) this.recommended = $p.secureEvalJSON(c);
	         c = $p.cookies.get('compostings');
	         if(c) this.complained = $p.secureEvalJSON(c);
	    }
	},
	canRecommend:function(postId){
		return ($p.cookies.test() && ((this.recommended[postId])? false: true));
	},
	canComplain:function(postId){
		return ($p.cookies.test() && ((this.complained[postId])? false: true));
	},
	recommend:function(obj, postId){
		var o = this;
		$p.getScript(o.recurl + '?postid=' + postId, function(){
			  o.recommended[postId] = 1;
			  if($p.cookies.test())				  
                  $p.cookies.set('recpostings', $p.compactJSON(o.recommended), {hoursToLive: 8760});          
              		  
			  $p(obj).hide();
			  alert('Tak - anbefaling registreret.');
		});
	},
	complain: function(obj, postId){
		var o = this;
		$p.getScript(o.comurl + '?pid=' + postId + '&fid=0&eid=0' , function(){
			o.complained[postId] = 1;
			if($p.cookies.test())				  
               $p.cookies.set('compostings', $p.compactJSON(o.complained), {hoursToLive: 8760});          
            		  
			$p(obj).hide();	
			alert('Tak for din klage.\nVi tjekker den tekst, som du har klaget over.\nVenlig hilsen redaktionen p\xE5. Politiken.dk.');
		});
	
	}
}

function doSubscription(publicationUrl, sectionId){
	var value = $p("#mobileNumberBreaking").attr("value");
	if((value==null) || (!/^\d{8}$/.test(value))){
		$p("#mobileNumberBreaking").addClass("error");
		$p("#mobileNumberBreaking").attr("value","Indtast mobilnr.");
		return false;
	}
	$p("#breakingSmsNumber").html(value);
	
	$p.ajax({
		cache:false,
		url:(publicationUrl + "?service=post&handler=sms&sectionId=" + sectionId + "&mobileNumber="+value),
		dataType:"xml",
		success: function(msg){			
			if($p('result[handler=sms] output[code=200]',msg).size() != 0){
				$p("#breakingSubscribe").attr("style", "display:none");
				$p("#breakingSuccessMessage").attr("style", "display:inline");
			}else{
				$p("#mobileNumberBreaking").addClass("error");
				$p("#mobileNumberBreaking").attr("value","Indtast mobilnr.");
			}
  	},
  	error: function (XMLHttpRequest, textStatus, errorThrown) {
			$p("#mobileNumberBreaking").addClass("error");
			$p("#mobileNumberBreaking").attr("value","Indtast mobilnr.");
	  }
	})
}
/* ibyen search */
function initIbyenFreeSearch(id, defaultText)
{
	$p('#' + id + ' input[type=text]').focus(function(){
		if($p(this).val() == defaultText) $p(this).val('');
	}).blur(function(){
		if($p(this).val() == '') $p(this).val(defaultText); 
	});
	$p('#' + id).submit(function(){
		var s = $p('#' + id + ' input[type=text]').val();
		if(s && s.length >= 3 && s != defaultText)
			return true;		
		return false;
	});
}

function initIbyenCalendarSearch(id, url)
{
	searchUrl = url;
	$p('#' + id).click(function(){
		lcs(this);			
		return false;
	});
}

function searchRestaurantSelect(el) {
	var searchUrl = $p(el).val();
	if (searchUrl != '')
		window.location.href = searchUrl;
}

/* mobile box */
function submitMobileBox(sectionId){
	var handlers = [];	
	if($p('#mboxCh1').is(':checked')) handlers.push('smsmobile');
	if($p('#mboxCh2').is(':checked')) handlers.push('sms');;
	if(handlers.length == 0) return;
	
	var number = $p.trim($p('#mboxMobileNumber').val());
	if(!/^\d{8}$/.test(number)){
		alert('Indtast venligst et gyldigt mobilnummer');
		return;
	}
	
	var showAlert = function(){
		var msg = '';
	    switch(handlers.toString()){
	    case "sms": msg = 'Du er nu tilmeldt breaking news p\u00E5 sms';
	    	break;
	    case "smsmobile": msg = 'Vi har nu sendt et link til Politikens mobilsite';
	    	break;
	    case "smsmobile,sms": msg = 'Vi har nu sendt et link til Politikens mobilsite og tilmeldt dig breaking news p\u00E5 sms';
	    	break;		    
	    }
	    alert(msg);					
	};

	$p.ajax({
		cache:false,
		url:'?service=post&handler=' + handlers.toString() +'&sectionId=' + sectionId + '&mobileNumber=' + number,
		dataType:'xml',
		success: function(result){ 
		    /*var isOk = true;
		    $p.each(handlers, function(){
		    	isOk = isOk && ($p('result[handler=' + this + '] output[code=200]',result).size() != 0);		    	
		    });		    
		    if(!isOk) return;*/
		    showAlert();
  	},
  	error: function(XMLHttpRequest, textStatus, errorThrown) {
  		showAlert();
	}});	
}
function initMobileBox(sectionId){
	$p('#mboxMobileNumber').blur(function(){
		if($p(this).val()=='') $p(this).val('Indtast mobilnummer');
	}).focus(function(){
		if($p(this).val()=='Indtast mobilnummer') $p(this).val('');
	}).keypress(function(e){
		if(e.which == 13) submitMobileBox(sectionId);
	});	
	$p('#mboxMobileSend').click(function(){
		submitMobileBox(sectionId);
	});
}

/*it's a hot fix to remove hidden lines. Good solution is to restructure the layout avoiding having line-separator after last element in the group*/
$p(function(){
	$p('div.cover-line').each(function(){
		var el = $p(this).prev('div.m-line-ccc,div.solidline-ccc').andSelf();
		if(el.length == 2) el.remove();
	});
});
/*end*/
