/**
* NOTE: This javascript file is shared between tjek, direkte and general commentary so make sure to test all these!
*/
if(!window.$p)
window.$p = jQuery.noConflict();
var commentHelper = new function(){
/*customization*/
this.defaultSettings={	maxCommentLength:400,
itemsPerPage:5,
maxCommentsPerDay:5,
currentPage:0,
seeAll:false,
showSeeAllButton:false,
submitOnce:false,
showSubmitForm:true,
sortings:
[
{title:'ÆLDSTE FØRST',
isDefault:true,
evenSortFunction:function(post1, post2){return (-1) * commentHelper.compareNums(post2.id, post1.id);},
oddSortFunction:function(post1, post2){return (-1) * commentHelper.compareNums(post2.id, post1.id);}},
{title:'NYESTE FØRST ',
isDefault:false,
evenSortFunction:function(post1, post2){return (-1) * commentHelper.compareNums(post1.id, post2.id);},
oddSortFunction:function(post1, post2){return (-1) * commentHelper.compareNums(post1.id, post2.id);}},
{title:'ANBEFALINGER',
isDefault:false,
evenSortFunction:function(post1, post2){return (-1) * commentHelper.compareNums(post1.rec, post2.rec);},
oddSortFunction:function(post1, post2){return (-1) * commentHelper.compareNums(post1.rec, post2.rec);}}
],
getPagerItemHtml:function(post, isLast) {
var r = " ";
if (post.ra){
if (typeof ratingSym != 'undefined'){
var imgUrl = "<img src='/grafik/ibyen/userrating/"+post.ra+ratingSym+"_display.gif'/>";
r = commentHelper.useRatingsSort? imgUrl : '';
}
else{
r = commentHelper.useRatingsSort? "<img class='m-top5' src='/grafik/tjek/rating/Lille_Gul_"+ post.ra +".gif' />" : ''; 
}
}
return '<div class="comments-tools">' + ((postingRecommender.canRecommend(post.id))? '<a href="javascript:void(0)" class="com-thumb" onclick="postingRecommender.recommend(this, ' + post.id + ');">Anbefal&nbsp;(' + post.rec + ')</a>': '<a href="javascript:void(0)" class="com-thumb" onclick="alert(\'Du har allerede anbefalet denne kommentar.\');">Anbefal&nbsp;(' + post.rec + ')</a>') + 
((postingRecommender.canComplain(post.id))? '<a href="javascript:void(0);" onclick="postingRecommender.complain(this, ' + post.id + ');" class="com-comple">Klag</a>': '') +
'</div><div class="af-line">Af <span>' + post.fn + ' ' + post.ln + ', ' + post.ci + '</span> ' + post.time.substring(0, post.time.length - 3).toUpperCase() + '<br/>' + r + '</div><p>' + post.bo + '</p>';},
getPagerHeaderHtml:function(){ 
var c = commentHelper.getVisiblePostings().length, f = 1, t = c;
if(c == 0) return '';
if(!commentHelper.settings.seeAll){
f = commentHelper.settings.itemsPerPage * commentHelper.settings.currentPage + 1;
t = commentHelper.settings.itemsPerPage * (commentHelper.settings.currentPage + 1);
t = (t > c)? c: t;}
return '' + f + '-' + t + '/' + c;}, 
saveCustomInfo:function(info){
if($p('#cbSaveInfo:checked').size() > 0){ 
info.name = $p('#fmCommentForm [name=fn]').val();
info.surname = $p('#fmCommentForm [name=ln]').val();
info.city = $p('#fmCommentForm [name=ci]').val();
info.email = $p('#fmCommentForm [name=em]').val();
info.address = $p('#fmCommentForm [name=ad]').val();
info.phone = $p('#fmCommentForm [name=ph]').val();
info.rating = $p('#fmCommentForm [name=ra]').val();
}},
loadCustomInfo:function(info){ 
if(info.name) $p('#fmCommentForm [name=fn]').val(info.name);
if(info.surname) $p('#fmCommentForm [name=ln]').val(info.surname);
if(info.city) $p('#fmCommentForm [name=ci]').val(info.city);
if(info.email) $p('#fmCommentForm [name=em]').val(info.email);
if(info.address) $p('#fmCommentForm [name=ad]').val(info.address);
if(info.phone) $p('#fmCommentForm [name=ph]').val(info.phone);
if(info.rating) $p('#fmCommentForm [name=ra]').val(info.rating);
if(info.name || info.surname || info.email || info.city)
$p('#cbSaveInfo').attr('checked', 'checked');},
preSubmitAction:function() {
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=ti]').val($p('#fmCommentForm [name=bo]').val().substring(0, 70) + '...');
if(commentHelper.isAnonRatingEnabled()) {
if($p('#fmCommentForm [name=bo]').val() == commentHelper.commentText) {
$p('#fmCommentForm [name=bo]').val("");
$p('#fmCommentForm [name=fn]').val("");
$p('#fmCommentForm [name=ci]').val("");
$p('#fmCommentForm [name=em]').val("");
}
}
},
validateInput:function() {
var isValid = true;
var errColor = 'red';
if($p('#fmCommentForm [name=ra]').val() >= 0 && commentHelper.isAnonRatingEnabled()) {
return true;
}
if( !$p.trim($p('#fmCommentForm [name=bo]').val()) || $p('#fmCommentForm [name=bo]').val() == commentHelper.commentText) {
$p('#fmCommentForm [name=bo]').css('border-color', errColor);
isValid = false;}
else $p('#fmCommentForm [name=bo]').css('border-color', '');
if($p('#fmCommentForm [name=fn]').val() == 'Fornavn' || $p('#fmCommentForm [name=fn]').val() == 'Navn'){
$p('#fmCommentForm [name=fn]').css('border-color', errColor);
isValid = false;}
else $p('#fmCommentForm [name=fn]').css('border-color', '');
if($p('#fmCommentForm [name=ln]').val() == 'Efternavn*'){
$p('#fmCommentForm [name=ln]').css('border-color', errColor);
isValid = false;}
else $p('#fmCommentForm [name=ln]').css('border-color', '');
if($p('#fmCommentForm [name=ci]').val() == 'By'){
$p('#fmCommentForm [name=ci]').css('border-color', errColor);
isValid = false;}
else $p('#fmCommentForm [name=ci]').css('border-color', '');
var emailReg = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = $p('#fmCommentForm [name=em]').val();	
if ((!email) || (!emailReg.test(email))){
$p('#fmCommentForm [name=em]').css('border-color', errColor);
isValid = false;}
else $p('#fmCommentForm [name=em]').css('border-color', '');
return isValid;
}
}; 
/*variables*/ 
this.settings;
this.postings;
this.pages; 
this.wasSubmit = false;
this.useRatingsSort = false;
this.commentText = "Skriv vurdering";
/*functions*/
this.addRatingsSort = function() {
var ch = this;
this.defaultSettings.sortings.push({title:'KARAKTER',
isDefault:false,
evenSortFunction:function(post1, post2){return (-1) * ch.compareNums(post1.ra, post2.ra);},
oddSortFunction:function(post1, post2){return (-1) * ch.compareNums(post1.ra, post2.ra);}}
);
ch.useRatingsSort = true;
}
this.isAnonRatingEnabled = function() {
return this.useRatingsSort;
}
this.isPostingRated = function(posting) {
return parseInt(posting.ra) >= 0;
}
this.getAverageUserRating = function() {
var count = 0, ratings = 0;
var rated = this.getRatedPostings();
for(p in rated) {
r = parseInt(rated[p].ra);
count++;
ratings += r;
}
return (ratings > 0 && count > 0)? {count:count, avg:Math.round(ratings / count)} : {count:0, avg:-1};
}
this.getCurrentUserRating = function() {
var info = this.loadInfo();
return parseInt(info && info.ratings[this.getCurrentArticleId()]? info.ratings[this.getCurrentArticleId()] : -1);
}
this.hasCurrentUserCommented = function() {
var info = this.loadInfo();
return info? info.eids.indexOf(this.getCurrentArticleId()) > -1 : false;
}
this.getCurrentArticleId = function() {
return $p('#fmCommentForm :hidden[name=eid]').val();
}
this.compareNums = function(a, b)
{
var n1 = parseInt(a,10);
var n2 = parseInt(b,10);
if(isNaN(n1)) n1 = 0;
if(isNaN(n2)) n2 = 0; 
if(n1 > n2) return 1;
if(n1 < n2) return -1; 
return 0;
};
this.checkCommentCount = function(artid){
var commentCount = this.getCommentCount(artid);
var str = "(Du har nu " + (5-commentCount) + (5-commentCount == 1 ? ' kommentar' : ' kommentarer') + " tilbage for dette indlæg i dag.)";
if(commentCount === 5){
$p('.com-fields').each(function(){
$p(this).attr('disabled','disabled');
});
$p('#commentSubmit, #commentlen').hide();
$p('#combox').val('Du kan højst skrive fem kommentarer pr. indlæg om dagen. Tak for dine bidrag til debatten.').attr('disabled','disabled');
}else{
if(commentCount>0 && $p('#commentsLeft').length>0){
$p('#commentsLeft').text(str).show();
}
}
}
this.getCommentCount = function(artid){
var now = new Date().getTime();
//24 hours ago
var then = now-(1000*60*60*24);
//do we accept cookies
if($p.cookies.test()){
var polcomments = $p.cookies.get('polcomments');
//if the user commented within the last year
if(polcomments){
//existing array
//var pc = $p.secureEvalJSON(polcomments);
var pc = $p.parseJSON(polcomments);
//new array to put non-expired comment-counts in
var new_arr = {};
var aid;
//clean out all expired article-comments
$p.each(pc,function(key,val){
aid=key;
$p.each(pc[key],function(key,time){
if(time<then){
pc[aid].splice(key,1);
}
});
if(this.length){
new_arr[key] = this;
}
});
//write down the new, trimmed array
$p.cookies.set('polcomments', $p.compactJSON(new_arr), {hoursToLive: 8760});
if(new_arr[artid]){
return new_arr[artid].length;
}else{
return 0;
}
//the user has not commented at all within the last year
}else{
return 0;
}
}
}
this.saveCommentCount = function(artid){
var now = new Date().getTime();
//do we accept cookies
if($p.cookies.test()){
var polcomments = $p.cookies.get('polcomments');
//have the user commented within the last year
if(polcomments){
//var pc = $p.secureEvalJSON(polcomments);
var pc = $p.parseJSON(polcomments);
//if user already has commented on this article
if(pc[artid]){
pc[artid].push(now);
}else{
pc[artid] = [now];
}
//the user has not commented within the last year
}else{
var pc={};
pc[artid] = [now];
}
//write the cookie back
$p.cookies.set('polcomments', $p.compactJSON(pc), {hoursToLive: 8760});
}
}
this.init = function(postings, settings){
if(checkComments){
this.checkCommentCount(this.getCurrentArticleId());
}
if(typeof rockymode != 'undefined' && rockymode){
this.defaultSettings.sortings[1].isDefault=true;
this.defaultSettings.sortings[1].title='Nyeste';
this.defaultSettings.sortings[2].title='Anbefalede';
this.defaultSettings.sortings.splice(0,1);
this.defaultSettings.sortings.splice(2,1);
}
if(settings.commentText){
this.commentText = settings.commentText;
}
this.postings = postings;
this.settings = $p.extend(this.defaultSettings, settings || {});
if(postings)
this.pages = parseInt(this.getVisiblePostings().length / this.settings.itemsPerPage) + ((postings.length % this.settings.itemsPerPage == 0)? 0: 1);
else
this.pages = 0;
/*prepare comment form */
$p('#cbSaveInfo').removeAttr('checked');
var eid = $p('#fmCommentForm :hidden[name=eid]').val(); 
var info = this.loadInfo();
if(((!info) || ((info) && (info.eids.indexOf(eid) < 0)) || (!this.settings.submitOnce)) && this.settings.showSubmitForm)
{
$p('#commentSubmit').click(function(){ $p('#fmCommentForm').submit(); return false;});
$p('#commentBox').show(); 
$p('#fmCommentForm').submit(function(){
if(commentHelper.wasSubmit) return false;
commentHelper.wasSubmit = true;
if(!commentHelper.settings.validateInput())
{
commentHelper.wasSubmit = false;
return commentHelper.wasSubmit;
}
commentHelper.settings.preSubmitAction(); 
commentHelper.saveInfo();
}); 
if(info)
this.settings.loadCustomInfo(info); 
$p('#fmCommentForm [name=bo]').keyup(this.countSymbols).change(this.countSymbols); 
$p('#fmCommentForm [name=bo]').change(); 
}
/*prepare comment list*/
if((!this.postings) || (this.getVisiblePostings().length == 0))
return; 
/*sorting items*/
$p('#hdrPanel').empty(); 
if(this.settings.sortings && this.settings.sortings.length > 0)
{
/* $p('<li><div>SORTER EFTER</div></li>').appendTo('#hdrPanel'); */
$p.each(this.settings.sortings, function(){
var odd = this.oddSortFunction;
var even = this.evenSortFunction;
var sort = $p('<li><a href="#"></a></li>').find('a')
.html(this.title)
.toggle(function(){commentHelper.postings.sort(odd); commentHelper.renderContent(); $p('#hdrPanel .sec-color').removeClass('sec-color'); $p(this).addClass('sec-color'); return false;}, function(){commentHelper.postings.sort(even); commentHelper.renderContent(); $p('#hdrPanel .sec-color').removeClass('sec-color'); $p(this).addClass('sec-color'); return false;})
.end().appendTo('#hdrPanel');
if(this.isDefault)
sort.children('a').click(); 
});
}
/*see all item*/
if(this.pages > 1 && this.settings.showSeeAllButton){
$p('<li class="last"><a href="#">VIS ALLE PA EN SIDE</a></li>').find('a')
.toggle(function(){commentHelper.settings.seeAll = true; commentHelper.renderContent();}, function(){commentHelper.settings.seeAll = false; commentHelper.settings.currentPage = 0; commentHelper.renderContent(); return false;})
.end().appendTo('#hdrPanel');
}
/*pager*/
if(this.pages < 2)
$p('#pagerButtons').hide();
else
{
$p('#pagerButtons li a:first').unbind().click(function(){
if(commentHelper.settings.currentPage > 0)
{
--commentHelper.settings.currentPage;
commentHelper.renderContent();
}
//return false;
});
$p('#pagerButtons li a:last').unbind().click(function(){
if(commentHelper.settings.currentPage < commentHelper.pages - 1)
{
++commentHelper.settings.currentPage;
commentHelper.renderContent();
}
//return false;
}); 
} 
/*render and show*/
this.renderContent(); 
$p('#commentsListBox').show();
};
this.isPostingVisible = function(posting) {
return posting.text || (posting.bo != "" && posting.bo != this.commentText); 
}
this.getVisiblePostings = function() {
return $p.grep(this.postings, this.isPostingVisible);
}
this.getRatedPostings = function() {
return $p.grep(this.postings, this.isPostingRated);
}
this.renderContent = function() {
var vp = this.getVisiblePostings();
var startIdx = (this.settings.seeAll)? 0: this.settings.currentPage * this.settings.itemsPerPage;
var endIdx = (this.settings.seeAll)? vp.length: (this.settings.currentPage + 1) * this.settings.itemsPerPage - 1;
if(startIdx < 0) startIdx = 0;
if(endIdx > vp.length - 1) endIdx = vp.length - 1;
var html = ''; 
for(var i = startIdx; i <= endIdx; i++) {
var posting = vp[i];
html+= this.settings.getPagerItemHtml(posting, (i == endIdx),i);
}
$p('#pagerContent').html(html); 
$p('#commentsNum').html(this.settings.getPagerHeaderHtml()); 
if(!this.settings.seeAll)
{
this.renderNavigation();
$p('#pagerNavigation').show();
}
else
$p('#pagerNavigation').hide(); 
};
this.countSymbols = function() {
var text = this.value == commentHelper.commentText? "" : this.value; 
var max = commentHelper.settings.maxCommentLength; 
if(text.length > max)
{
text = text.substring(0, max);
this.value = text;
}
$p('#commentlen').html((max - text.length) + ' tegn tilbage'); 
};
this.renderNavigation = function()
{
$p('#pagerPages li:not(:first-child)').remove();
for(var i = 0; i < this.pages; i++)
if(this.settings.currentPage == i)
$p('<li class="selected">' + (i + 1) + '</li>').appendTo('#pagerPages');
else
$p('<li><a href="#">' + (i + 1) + '</a></li>').find('a')
.bind('click', i, function(event){commentHelper.settings.currentPage = event.data; commentHelper.renderContent(); return false;})
.end().appendTo('#pagerPages');
};
this.loadInfo = function() {
if($p.cookies.test()) {
var infoJson = $p.cookies.get('posting');
if(infoJson) { 
//var info = $p.secureEvalJSON(infoJson);
var info = $p.parseJSON(infoJson);
if(info)
return info;
}
}
return null;
};
this.saveInfo = function() {
if($p.cookies.test()) {
var info = this.loadInfo(), eids = '', eid = this.getCurrentArticleId();
var rating = parseInt($p("#fmCommentForm :hidden[name=ra]").val());
var ratings = {};
if(info) {
eids = info.eids;
if(info.eids.indexOf(eid) == -1) {
eids = eids + ',' + eid;
}
if(info.ratings) {
ratings = info.ratings;
}
} else {
eids = eid;
}
info = {};
info.eids = eids;
if(rating >= 0) {
ratings[eid] = rating;
}
info.ratings = ratings;
this.settings.saveCustomInfo(info);
if(checkComments){
this.saveCommentCount(this.getCurrentArticleId());
}
$p.cookies.set('posting', $p.compactJSON(info), {hoursToLive: 8760});
}
}
};

