String.prototype.startsWith = function(str) {return this.substr(0, str.length) == str;}
String.prototype.endsWith = function(str) {return this.substr(this.length - str.length) == str;}

function callPopup(id, url, params) {
  if (!id) return;  
  var p = [];
  var target = 'x' + new Date().getTime();
  var ps = '';
  if (id==2){
    target="fragsterpopA";
    ps='width=966,height=610';
  }
  else if (id==3){
    target="fragsterpopB";
    ps='width=1010,height=720';
  }
  if (params) {
    var t = params.split(',');
    for(var i = 0; i < t.length; i++) {
      var e = t[i].split('=');
      if (e.length == 2) {
        if (e[0] == 'target') {
          target = e[1];
        }
        else {
          p[p.length] = e;
        }
      }
    }
    for(var i = 0; i < p.length; i++) {
      var e = p[i];
      if (i > 0) ps += ',';
      ps += e[0] + '=' + e[1];
    }
  }
  if (!url) return;  
  var w = window.open(url, target, ps);
  w.focus();
}

function doSearch(frm) {
  var v = frm.itwsearch.value;
  if (v.length == 0) return false;
  if (v.length < 2 || v == 'Suchbegriff eingeben') {
    try { frm.itwsearch.style.color='#ff0000'; } catch (ex) {}
    return false;
  }
  try { frm.itwsearch.style.color='#000000'; } catch (ex) {}
  frm.submit();
  return false;
}

function ji(x, y) {
  var sub='/'+new Date().getTime();
  if(sub=='/')return;
  if(!window.jis)window.jis=[];
  var i=window.jis.length;
  window.jis[i]=new Image();
  
  if (y) {
    window.jis[i].src=y + '/j'+'i/'+x+sub+'/ji.gif';
  }
  else {
    window.jis[i].src='/j'+'i/'+x+sub+'/ji.gif';
  }
}

/* ensure a dom element is visible (vertical) */
function ensureVisible(ele) {
  var tWin = $(document).scrollTop();
  var hWin = $(window).height();
  var tEle = ele.offset().top;
  var hEle = ele.outerHeight();
  if (tEle <= tWin) $(document).scrollTop(tEle - 20); // scroll up
  else if (tEle + hEle >= tWin + hWin) $(document).scrollTop(tEle + hEle - hWin + 20); // scroll down
}

// jump 2 comments
function jump2Comments() {
  var eComments = $('#comments');
  ensureVisible(eComments);
}
// load comments
function loadComments(page, noEnsureVisible) {
  var eComments = $('.comments');
  if (eComments.length == 0) return;
  var id = eComments.attr('id').substring('comments'.length)
  var cType = eComments.attr('class').indexOf('commentsArt') ? 'article' : 'other';
  var loc = location.href;
  if (loc.indexOf('#') != -1) loc = loc.substring(0,loc.indexOf('#'));
  var url = '/v2/cmy/rpcdata/itw.rpc.getCommentsRPC/id='+id+'&page='+page+'&burl='+encodeURIComponent(encodeURIComponent(loc))+'/';
  url = getAjaxUrl(url);
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function(o){
      if (o) {
        if (o.status == 'refresh') {
          location.reload();
        }
        else if (o.status == 'forward') {
          location.href = o.url;
        }
        else {
          if (o.status == 'error') {
            // NOP
          }
          else if (o.status == 'invalid_base_url') {
            // NOP
          }
          eComments.html(o.markup);
          if (typeof(noEnsureVisible) == 'undefined' || noEnsureVisible === false) {
            ensureVisible(eComments);
          }
          else if (noEnsureVisible == 'top') {
            $(document).scrollTop(eComments.offset().top - 20);
          }
          loadCommentBox();
        }
      }
    }
  });
}
// box for commenting
function loadCommentBox(commentId) {
  var eComments = $('.comments');
  var id = eComments.attr('id').substring('comments'.length)
  var cType = eComments.attr('class').indexOf('commentsArt') != -1 ? 'article' : 'other';
  var eBox = $('.commentBox');
  var url = '/v2/cmy/rpcdata/itw.rpc.getWriteCommentBoxRPC/id='+id+'&action='+(commentId?('edit&commentID='+commentId):'write')+'&ctype='+cType+'/';
  url = getAjaxUrl(url);
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function(o){
      if (o) {
        if (o.status == 'refresh') {
          location.reload();
        }
        else if (o.status == 'forward') {
          location.href = o.url;
        }
        else {
          if (o.status == 'error') {
            // NOP
          }
          eBox.html(o.markup);
          if (commentId) {
            ensureVisible(eBox);          
          }
          var frm = eBox.find('form');
          if (frm) {
            frm.attr('onSubmit', '');
            frm.submit(function(e){
              e.preventDefault();
              e.stopPropagation();
              doWriteComment(frm,id,commentId,cType);
              return false;
            });
          }  
        }
      }
    }
  });
}
// submit box
function doWriteComment(frm,id,commentId,cType) {
  var eBox = $('.commentBox');
  var url = '/v2/cmy/rpcdata/itw.rpc.getWriteCommentBoxRPC/id='+id+'&action='+(commentId?('edit&commentID='+commentId):'write')+'&ctype='+cType+'/';
  url = getAjaxUrl(url);
  $.ajax({
    url: url,
    type: 'POST',
    data: frm.serialize(),
    dataType: 'json',
    success: doWriteCommentSuccess
  });
  return false;
}
function doWriteCommentSuccess(o) {
  var eBox = $('.commentBox');
  if (o.status == 'success') {
    var l = location.href;
    var pos = l.indexOf('#');
    if (pos != -1) {
      l = l.substring(0, pos);
    }
    location.href = l + '#page_last';
    loadComments('last');
  }
  else {
    if (o.status == 'not_logged_in') {
    }
    else if (o.status == 'invalid_id') {
    }
    else if (o.status == 'invalid_comment_id') {
    }
    else if (o.status == 'too_fast') {
    } 
    else if (o.status == 'duplicate') {
    } 
    else if (o.status == 'no_text') {
    } 
    else if (o.status == 'not_permitted') {
    } 
    else if (o.status == 'error') {
    } 
    eBox.html(o.markup);
  }
}

function getIdFromClass(ref) {
  var id = null;
  var s = ref.attr('class');
  var idx = s.indexOf('resid');
  if (idx > -1) {
    var idx2 = s.indexOf(' ');
    if (idx2 > -1) {
      id = s.substring(idx + 'resid'.length, idx2);
    }
    else {
      id = s.substring(idx + 'resid'.length);
    }
  }
  return id;
}

/* rating: auto load ratings */
//$(document).ready(initRatings);
function initRatings() {
  var esRating = $('.rating');
  if (esRating.length > 0) {
    var map = {};
    esRating.each(function(idx){
      var id = getIdFromClass($(this));
      if (id != null) {
        map[id] = true;
      }
    });
    var ids = '';
    for (var id in map) {
      if (ids.length > 0) { ids += ','; }
      ids += id;
    }
    if (ids.length > 0) {
      loadRatings(ids);
    }
  }
};
function loadRatings(ids) {
  var url = '/v2/cmy/rpcdata/itw.rpc.getRatingCountRPC/idlist=[' + ids + ']/';
  url = getAjaxUrl(url);
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function(data){
      for (var id in data) {
        $('.'+id).each(function(idx){
          var eR = $(this);
          var clss = eR.attr('class').split(' ');
          // remove old rating
          for (var i = 0; i < clss.length; i++) {
            var c = clss[i];
            if (c != 'rating' && c.substring(0,3) != 'res') eR.removeClass(c);
          }
          // add new rating
          var d = data[id];
          if (d[0] > 0) {
            var tit = '';
            var num = (Math.round(d[0] / 2) / 10);
            tit += (num == 1 ? '1 Stern' : num + ' Sterne');
            tit += ' (' + (d[2] == 1 ? '1 Bewertung' : d[2] + ' Bewertungen') + ')';
            num = Math.round(d[0] / 10) * 10;
            eR.addClass('rating' + num);
            eR.attr('title', tit);
          }
        });
      }
    }
  });        
}

/* commentscount: auto load comments count */
$(document).ready(initCommentscnt);
function initCommentscnt() {
  var esCommcnt = $('.commcnt');
  if (esCommcnt.length > 0) {
    var map = {};
    esCommcnt.each(function(idx){
      var id = getIdFromClass($(this));
      if (id != null) {
        map[id] = true;
      }
    });
    loadCommentsCnt(map);
  }
};
function loadCommentsCnt(map) {
  var ids = '';
  for (var id in map) {
    if (ids.length > 0) { ids += ','; }
    ids += id;
  }
  if (ids.length == 0) return; // don't load
  ids = '[' + ids + ']';
  var url = '/v2/cmy/rpcdata/itw.rpc.getContentCommentCountRPC/viaPOST=True/';
  url = getAjaxUrl(url);
  $.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    data: {idlist:ids},
    success: function(data){
      for (var id in data) {
        $('.'+id).each(function(idx){
          var c = data[id];
          var h = '(' + c + ($(this).hasClass('commcntL') ? (' Kommentar' + (c != 1 ? 'e' : '')) : '') + ')';
          $(this).html(h);
        });
        delete map[id.substring(5)];
      }
      for (var id in map) {
        $('.resid'+id).each(function(idx){
          $(this).html('(0)');
        });
      }
    }
  });        
}

// load comments?
$(document).ready(function(){
  var h = location.hash;
  if (h.startsWith('#comments')) {
    loadComments(1);
  }
  else if (h.startsWith('#firstcomment')) {
    loadComments(1, 'top');
  }
  else if (h.startsWith('#page_')) {
    loadComments(h.substring(6));
  }
  else if (location.href.indexOf('#') != -1) {
    loadComments(1);
  }
  else {
    if ($('.commentsArt').length > 0) {
      loadComments(1, true);
    }
    else if ($('.commentsDia').length > 0) {
      loadComments(1, true);
    }
  }
});

function getAjaxUrl(url) {
  var n = location.hostname;
  if (n != 'www.fragster.de' && n != 'itwtemp.fragster.de') {
    url = '/de/ajaxproxy.html?url=' + encodeURIComponent(url.replace(/\/v2\//,'/'));
  }
  return url;
}
