// Initialize the checkboxes for selecting tags
var Tags = new Array("Generelt", "Begreper", "Sikkerhet", "Lagring", "Teknologi", "Strategi",
                     "Økonomi", "Leverandører", "Praksis", "Reguleringer"); // må hente denne listen automatisk!!
var MM_api;
var emptyPane = 0;
/* This is for the automatic line break of the accordion heading. */
var LIMIT = 640; var PADDING = 20; /* should get this from CSS */
var panesMap = new Array();
var dateMap = new Array(); //used to pick recently changed entries 
var genCommentCnt = 0;
var genComment = '/FAQ/cloud/comment'; //path for general comments
var $newComment = null;
var abonnent = false; //true if the user is a paying subscriber
var endringer = false; // used to flag that 'recent changes' (button) have been selected
var headerHeight = 32;
var lightCoffee = '#f9f4db';
var darkCoffee = '#bca77a';
var firstTime = 1;

function initCheckboxes() { 
  var labelLength = 0;
  for (var i = 0; i< Tags.length; i++) { // Create the checkboxes
      $('<li class="tagbox"><label for="'+Tags[i]+'"><input type="checkbox" name="'+Tags[i]+'" id="'+Tags[i]+'" value="'+Tags[i]+'" />'+Tags[i]+'</label></li>')
          .appendTo('#Acheckbox');
  }
  $('#Acheckbox').find(':checkbox').each(function() {
      var $this = $(this);
      $this.attr('checked', true); // Attach event handlers to each of them ...
      labelLength = Math.max(labelLength, $this.parent().parent().width()); // Find the widest label
      $this.click(function() {
          if (this.checked) {
              showTag($(this).attr('id'));
          } else {
              hideTag($(this).attr('id'));
          }
      });
  });
  // Add the all or nothing buttons and their event handlers
  $('&nbsp;<br><ul id="Acheckbutton"></ul>').insertAfter('#Acheckbox');
  $('<li class="tagbutton"><input class="button pushButton" type="button" name="alle" value="Vis alle" id="alle" /></li>').appendTo('#Acheckbutton');
  $('&nbsp;<li class="tagbutton"><input class="button pushButton" type="button" name="ingen" value="Skjul alle" id="ingen" /></li>').appendTo('#Acheckbutton');
  $('&nbsp;<li class="tagbutton"><input class="button pushButton" type="button" name="nye" value="Endringer" id="nye" /></li>').appendTo('#Acheckbutton');
  $('&nbsp;<li class="tagbutton"><input class="button pushButton bRight" type="button" name="om" value="Om tjenesten" id="om" title="Vis brukerinformasjon om denne tjenesten." /></li>').appendTo('#Acheckbutton');
  $('#alle').click(function() {
     $('#Acheckbox').find(':checkbox').attr('checked', true);
     showTag('Alle');
  });
  $('#ingen').click(function() {
     hideTag('Alle');
  });
  $('#nye').click(function () { visNye(); });
  $('#Acheckbox li').width(labelLength+1); // align the checkbox-labels
  $('#om').click(function () {
     $('#om').css({backgroundColor: lightCoffee, color: 'black'});
     $.get('/nettskysenteret/FAQ-info.html/getTextContent', function(data) {
        //alert('got data: '+data);
        $('<div id="WWtmp" style="left: -3000px; width:360px;"></div>').appendTo('body');
        $('#WWtmp').append(data).modal({
            position: ["20%", "25%"],
            containerCss: { backgroundColor: '#f3efe7', border: '2px solid #a0a0a0', minWidth: 360, padding: 10},
            closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
            onClose: function (dialog) {
              $('.modalCloseX').hide();
	      dialog.data.fadeOut('slow', function () {
                $('#om').css({backgroundColor: darkCoffee, color: 'white'});
		dialog.container.slideUp('slow', function () {
		    dialog.overlay.fadeOut('fast', function () {
			$.modal.close(); // must call this!
                        $('#WWtmp').remove();
		    });
		});
	      });
            },
            onOpen: function (dialog) {
              $('.modalCloseX').hide();
              dialog.container.show();
	      dialog.data.fadeIn('slow', function () {
                  $('.modalCloseX').show();
              });
            }
        });
     });
  });
  if (abonnent) {
     $('&nbsp;<li class="tagbutton"><input class="button bRight pushButton" type="button" name="vis" value="Vis kommentarer" id="vis" /></li>').appendTo('#Acheckbutton');
     $newComment=$('&nbsp;<li class="tagbutton"><input class="button bRight pushButton" type="button" name="ny" value="Ny kommentar" id="ny" /></li>').appendTo('#Acheckbutton').hide();
     $.get(genComment+'/getReplyCount', function(data) {
        //alert('got data: '+ data);
        genCommentCnt = data * 1;
        $('#vis').attr('value', 'Vis kommentarer ['+genCommentCnt+']');
     });
     $('#vis').click(function () { 
        hideTag('Alle');
        $('#Acheckbox :checkbox').attr('checked', false);
        showGenComments('button');
     });
     $('#ny').click(function(e) {
	e.preventDefault();
        contact.gcMode = true;
        localHref = '/FAQ/cloud/comment/';
        contact.gcClose = function() {
           if (didSubmit) { // update counter and button
              //alert('oppdaterer...');
              genCommentCnt++;
              $('#vis').attr('value', 'Vis kommentarer ['+genCommentCnt+']');
              showGenComments('new'); // always do this, the comments section is always open when new comments are being added
              didSubmit = false;
           }
           contact.gcMode = false;
        };
	// create a modal dialog with the data
	$(MM_formdata).modal({
		closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
		position: ["15%",],
		overlayId: 'contact-overlay',
		containerId: 'contact-container',
		onOpen: contact.open,
		onShow: contact.show,
		onClose: contact.close
	});

     });
  }
}

function showErr(msg) {
   // must turn this into a modal
   $.scrollTo($('#errMsg'), 600, {margin: true, offset: -40});
   $('#errMsg').empty().text(msg).fadeIn(400);
   return true;
}

jQuery.fn.toggleNext = function() {
  this.toggleClass('arrow-down')
    .next().slideToggle('fast');
};

//--------------------------------------------------------------------------------
$(document).ready(function(){
   var spacer = "";
   if ( $('#abonnent').length > 0 ) { abonnent = true; }
   initCheckboxes();
   MM_api = $("#accordion").tabs("#accordion div.pane", { 
      tabs: '.Aheader',  
      effect: 'mmdfaq',
      /*onClick: myClick,
      onBeforeClick: myBeforeClick,*/
      api: true
   });
   $('#accordion .Aheader').each( function(index) { // split the header sensibly if it is to long to fit on one line
       var head_w = $(this).find('h2').width();
       var $tag = $(this).find('ul');
       var $cont = $(this).next();
       var mod = new Array();
       mod = $tag.find('.Modified').text().split('-');
       dateMap[index] = new Date(parseInt(mod[2], 10), parseInt(mod[1], 10)-1, parseInt(mod[0].substr(mod[0].length-2,2), 10));
       //alert('Dato: '+dateMap[index] + mod[1]);
       //var tmp = $cont.find('.newsFooter').height();
       //IE7 only
       if ($.browser.version == 7.0) {
          if ($tag.height() > headerHeight) {
            // the width should be approx. 6 px per char
             $tag.width($tag.find('.TAG').text().length*6);
          }
       }
       if ( head_w + $tag.width() > LIMIT ) {
         $(this).find('h2').css('width', LIMIT - $tag.width() - PADDING);
         $(this).find('h2').css('margin-top', '0');
       };
       if ($cont.find('.newsFooter').height() > 40) { // 2 times padding for Firefox, Safari doesn't need that!
                                                      // Must add more for Comments
         $cont.css('height', $cont.find('.newsFooter').height() + 2*PADDING + $cont.find('.Atitle').height());
       }
   });
   if ($.browser.msie && $.browser.version < 7) {
      var warn = '<p><b>ADVARSEL: Denne tjenesten er ikke tilpasset eldre nettlesere som IE6. Bruk IE8, Firefox, Safari, Opera eller Chrome for full funksjonalitet og riktig utseende.</b>'
      $(warn).appendTo('#warningMsg');
      $('#warningMsg').addClass('boks');
   }
   if ($.browser.msie && $.browser.version < 8) {
      spacer = '&nbsp;';
   }
   MM_api.getPanes().each( function(index) { // Add a references section to each pane
      var currentPane =$(this);
      var id="ref"+index;
      var cont = "";
      var addClick = 0;
      panesMap[currentPane.find('.newsFooter').attr('id').substr(1,2)*1] = index;
      currentPane.find('a').not('.discussion-link').each(function(index) {
         var a = $(this);
         var hr = a.attr('href');    
         if ( hr.length == 3 ) { // this is an internal reference
            a.click(function (event) { 
               //alert('skal scrolle til '+hr);
               event.preventDefault(); 
               MM_api.click(panesMap[hr.substr(1,2)-0]);
               //$.scrollTo($('#'+hr).parent(), 800, {margin:true,offset:-50});
            });
            addClick++;
            cont += '<li>'+spacer+'<a href="#">Spørsmål '+hr+'</A></li>'; 
         } else {
            cont += '<li>'+spacer+'<a href="'+hr+'" target="newWin">'+a.html()+'</A></li>';
            a.attr('target', 'newWin'); 
         }
      });
      var ref=currentPane.find('.refHidden').html();
      if (ref) {
          var aref = ref.split(';;');
          for (var i = 0; i < aref.length; i++) {
             if (aref[i].length == 3) {
                 addClick++;
                 cont += '<li>'+spacer+'<a href="#">Spørsmål '+aref[i]+'</A></li>';
             } else { 
                 var pos = aref[i].indexOf(' ');
                 cont += '<li>'+spacer+'<a href="'+aref[i].slice(0,pos)+'" target="newWin">'+aref[i].slice(pos+1)+'</A></li>';
             }
          }
      }

      if (cont != "") {
         //alert(cont);
         $('<div id="r'+id+'" class="referanse"></div>')
            .prepend('<h3>Referanser</h3>')
            .append('<ul>'+cont+'</ul>')
            .prependTo(currentPane.find('.newsFooter')); 
         // Get other references if present...
         if (addClick > 0) {
            currentPane.find('.referanse li').each(function() {
               var hr = $(this).find('a').html();
               if (hr.substr(0, 8) == 'Spørsmål') {
                  $(this).click(function (event) { 
                     event.preventDefault(); 
                     MM_api.click(panesMap[hr.substr(10,2)-0]); 
                     //alert('jumping to '+hr.substr(9,3));
                     //$.scrollTo($('#'+hr.substr(9,3)).parent(), 800, {margin:true,offset:-50});
                  });
               }
            });
         }
      }
   });
   // add titles to all internal references
   $('.pane a:contains(X)').each(function(index) {
       var sText = $(this).text(); //NB: parseInt fungerer ikke pålitelig her!!!
       var sIndex = sText.substr(sText.indexOf('X')+1,2)*1;
       var ind = panesMap[sIndex];
       $(this).attr('title', MM_api.getPanes().eq(ind).siblings('.Aheader').find('h2').text());
   });
   if (!($.browser.msie && $.browser.version < 8)) {
      $('.referanse').corner();
   }

   $('.checkboxes').corner();
   $.ajaxSetup({cache: false}); //NB: denne er viktig for sanntids oppd. av .kommentarer ...
   /*$('.faq-discuss').each(function() { // denne skal flyttes til åpningen av en pane ... mer effektivt?
       addShowReplies($(this));
   });*/

   $('.referanse h3').click(function() {
      $(this).toggleNext();
   });
});
//------------------------------------------
function showTag(Tag) {
    var allClosed = 0;
    if (endringer) { hideTag('Alle'); }
    if (emptyPane > 0) { removeEmptyPane(); allClosed++;}
    //must delay this, otherwise it may not work ... removeEmtpyPane now takes time ...
    if ( Tag == 'Alle' ) {
       $('.FAQ').show(0);
       openFirst();
    } else {
       $('.TAG:contains('+Tag+')').parent().parent().parent().slideDown('slow');
       if (allClosed > 0) { openFirst(); }
    }
    resetChanges();
};
function resetChanges() {
    endringer = false;
    $('#nye').css({backgroundColor: darkCoffee, color: 'white'});
    $('#errMsg').fadeOut(500);
}
function hideTag(Tag) {
    if (Tag == 'Alle') { // close the current pane, hide all panes, add temporary pane for info
       if (emptyPane > 0 ) {return; }
       MM_api.getCurrentPane().slideUp("fast"); 
       $('.FAQ').hide(0);
       if (!endringer) {
          $('#Acheckbox :checkbox').attr('checked', false);
       }
       addEmptyPane();
    } else { 
       var $cur = $('.current').find('.TAG');
       if ($cur.text().indexOf(Tag) != -1 && !keepOpen($cur)) { // Close the current pane if it is about to be hidden
       //alert("current will be hidden!");
         MM_api.getCurrentPane().slideUp("fast"); 
    }
    // Hide all panes with this tag - except those with other tags that are open...
      /* $('.TAG:contains('+Tag+')').parent().parent().parent().hide('fast', function() {
            openFirst();
       });*/ // <-- Does not ,work - apparently the open comes too soon
       $('.TAG:contains('+Tag+')').each(function() {
          if (!keepOpen($(this))) {
             $(this).parent().parent().parent().hide('fast');
          }
       });
       wait = setInterval(function() { // must wait till the animation is finished
                                       // should use .queue() to accomplish this
          if (!$('.FAQ:last').is(":animated") ) {
            clearInterval(wait);
            openFirst();
          }
       }, 200);
       // if this was the last open tag, add the 'empty pane'
       if ( $('#Acheckbox :checked').length == 0) { addEmptyPane(); };
    }
    resetChanges();
};

function keepOpen(tg) {
  var tags = tg.text().substr(6).split(', ')
  //alert(tg.parent().text());
  var ret = false;
  $('#Acheckbox').find(':checkbox:checked').each(function() {
      var t = $(this).attr('id');
      for ( var i = 0; i < tags.length; i++) {
         if (tags[i] == t) { 
           //alert('keep '+t); 
           ret = true;
           return; 
         }
      }
  });
  return ret;
}



function visNye() {
  var now = new Date();
  var changeLimit = 18;
  var j = 0;
  var newPanes = new Array();
  hideTag('Alle');
  for ( var i = 0; i < dateMap.length; i++) {
    if (Math.round((now - dateMap[i])/(1000*60*60*24)) < changeLimit) {
       newPanes[j++] = i;
    }
  }
  if (j > 0) {
     removeEmptyPane();
     var $tabs = MM_api.getTabs();
     for (var k = 0; k< newPanes.length; k++) {
        $tabs.eq(newPanes[k]).parent().slideDown('slow');
     }
     openFirst();
     showErr('Viser innslag som er endret de siste '+changeLimit+' dagene.');
     $('#nye').css({backgroundColor: lightCoffee, color: 'black'});
     endringer = true;
  } else {
     // change the text in the empty pane
     showErr('Ingen endringer de siste '+changeLimit+' dagene.');
  }    
}
function addEmptyPane() { // Add a header indicating that everything has been deselected and therefore not visible.
   emptyPane++;
   $('.Xheader').addClass('Aheader');
   $('.Xheader h2:last').hide();
   $('.Xheader h2:first').show().css('margin-top', '12px');
   $('#temp').addClass('FAQ').show();
};

function removeEmptyPane() {
    emptyPane = 0;
    $('.Xheader').removeClass('Aheader');
    $('#temp').removeClass('FAQ').hide();
    $('#genComment').fadeOut(200);
    if ($newComment) { //defined only if 'abonnent'
       $newComment.fadeOut(100);
    }
};

function openFirst() { // open the first visible pane
    var index;
    obj = $('.FAQ:visible:first').children('.Aheader');
    index = MM_api.getTabs().index(obj);
    //alert("openFirst:"+index);
    if ( MM_api.getIndex() == index) { // The tool thinks this tab is already open, which it is not ...
       MM_api.getCurrentPane().slideDown();
    } else {
       MM_api.click(index);
    }
};
var tmpPaneOpen = false;
$.tools.addTabEffect("mmdfaq", function(tabIndex) { 
   var index = tabIndex;
   var offset = 90;
   var obj = this.getPanes().eq(index);
   var cur = this.getIndex();
   var cp = this.getCurrentPane();
   $('#errMsg').fadeOut(500);
   cp.slideUp('slow');
   if (tmpPaneOpen) { // cannot chain this to the slideUP - concurrency problems ... 
      //alert('closing temp pane');
      cp.parent().fadeOut(300); // need to queue this with the slideUp - otherwise it becomes invisible immediately
      tmpPaneOpen = false;
   } 
/*   $.scrollTo(obj, 800, {margin:true,offset:-90}); // denne virker ikke, men vi kan bruke onAfter opsjonen til scrollTo for å oppnå det vi vil.
   obj.queue(function() { obj.slideDown('slow'); obj.dequeue();});
 */
   if (obj.parent().css('display') == 'none') { // reference click to a pane that is hidden ...
                                                // change - to use jQuery methods instead...
      obj.parent().show();
      tmpPaneOpen = true; 
      //alert('tmpPaneOpen is true');
   } 
   // cannot chain these actions, the initial open gets lost (maybe because the initial slideUp has nothing to do)
   obj.slideDown('slow').queue(function() { 
      if (firstTime == 0) {
        if ( index < 4 ) { offset =$('.checkboxes').height() + 30+(index+1)*42; }; // blir feil når noen av headingene er skjult
        $.scrollTo(obj, 800, {margin:true,offset:-offset});
      }
      obj.dequeue();
      firstTime = 0;
   });
   var $backButton = obj.find('li :button[name=back]');
   if (cur != undefined && emptyPane == 0) {
     //$backButton.attr('title', String(cur));
     $backButton.unbind().show().click(function() {
       //alert('back button, index='+cur);
       MM_api.click(cur);
     });
   } else {
     $backButton.hide();
   }
});

function addShowReplies($here) {
       var hasReplies = $here.find('a').attr('alt'); 
       //alert("replies="+hasReplies);
       if (hasReplies == undefined ) { hasReplies = 0; }
       var xLabel = 'Vis kommentarer ['+hasReplies+']';
       if (hasReplies > 0) { 
         // does the button already exist? If yes, and it is not open, just update the count and exit.
         var $button = $here.find(':button[name^=show-comment]');
         if ($button.length > 0) {
             if ($button.attr('value').substr(0,4) == 'Vis ') {
                $here.find(':button[name^=show-comment]').attr('value', xLabel);
             } // otherwise the commenct div is open, and we should possibly update right here ...
             return;
         }
         // knappen finnes ikke, må opprettes.
         var comment_html = '<li class="tagbutton showbutton"><input class="button pushButton" type="button" name="show-comment" value="'+xLabel+'" /></li>';
         $(comment_html).insertBefore($here.find('ul [name^=xback]'));
         $here.find(':button[name^=show-comment]').click(function() { 
           var href = $here.find('a').attr('href'); // need a direct reference to the actual FAQ-entry
           var $comment = $here.find('.showComments');
           var $current = $(this);
           var label = $current.attr('value');
           if (label.substr(0,4) == "Vis ") { // Is closed, shall open...
              $comment.hide().load(href+'/getDiscussionTAL', function() { 
                 $comment.slideDown('slow'); 
                 $current.attr('value', 'Skjul kommentarer');
                 // must format the headings if they are long...
                 $comment.find('.discussionHeader').each( function() {
                    var $here = $(this);
                    var h3 = $here.find('h3');
                    var hw = $here.width();
                    if (h3.width() + $here.find('.newsAbout').width() > hw ) {
                          h3.width(hw - $here.find('.newsAbout').width() -20);
                          $here.height($here.height()*2); // double the hgiht of the containing DIV to make space.
                    }
                 });
                 // if one or more of the comments belong to this user, they have buttons for edit/delete
                 // This code is for the delete button
                 $comment.find(':button[value=slett]').each(function() {
                    var $obj = $(this);
                    $obj.click(function() {
                       var $parent =$obj.parent().parent().parent().parent(); // clumsy - use closest() instead!
                       confirm("Bekreft sletting:", function() {
                         $.get($obj.attr('name'), function(data) { 
                           ajaxStatus(data); // does not do anything at this time ...(nowhere to put the status)
                           //alert("delete executed, response: "+data); //should have better control that it actually happened
                           $parent.slideUp('slow', function() { 
                              var $counter=$here.find('a');
                              $parent.remove();
                              //alert('did delete, current counter is '+$counter.attr('alt')+', new counter: '+$counter.attr('alt')-1);
                              $counter.attr('alt', ($counter.attr('alt')*1-1)+'');
                              addShowReplies($here);
                           });
                         });
                       });
                     });
                 });
                 $comment.find(':button[value=edit]').each(function() {
                     var $obj = $(this);
                     $obj.click(function (e) {
                        e.preventDefault();
                        contact.$subject = $obj.closest('.discussionItem').find('h3');
                        contact.$message = $obj.closest('.commentBody').find('span');
                        contact.editMode = true;
                        //alert('edit: '+contact.message +'--'+contact.subject);
                        $(MM_formdata).modal({ //TODO: fix the modal code so that it finds the content.
                                               // Must initialize, so the data does not persist...
			   closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
			   position: ["15%",],
			   overlayId: 'contact-overlay',
			   containerId: 'contact-container',
			   onOpen: contact.open,
			   onShow: contact.show,
			   onClose: contact.close
		        });
                     });
                 });
              });
           } else {
              $comment.slideUp('slow').empty();
              $current.attr('value', 'Vis kommentar ['+$here.find('a').attr('alt')*1+']');
           };
           return false;
         });
       } else { // antall kommentarer er null, dersom knappen finnes, skal den bort.
         if ($here.find(':button[name^=show-comment]').length > 0 ) {
            $here.find('.showComments').hide(); // keep the tag for new comments ...
            $here.find(':button[name^=show-comment]').parent().remove(); // get the LI, not just the button ...
         }
       }
       return;
}

function showGenComments(from) {
     //alert('genCommentCnt: '+genCommentCnt);
     $('.tagbutton :button[name=ny]').parent().show(); // It's the LI that is hidden...
     $('.Xheader h2:first').hide();
     $('.Xheader h2:last').show().css('margin-top', '4px');
     if ( genCommentCnt > 0) { //this should always be true ...
        $('#general-wait').fadeIn(200);
        $.get(genComment+'/getDiscussionTAL', function(data) {
            var $gc = $('#genComment');
            $gc.empty(); 
            $(data).appendTo($gc);
            $gc.slideDown(400, function () {
              $('#general-wait').fadeOut(200);
            });
            //$.scrollTo($gc, 800, {margin:true,offset:0});
            // activate the edit/delete buttons if present
            $gc.find(':button[value=slett]').each(function() {
               var $obj = $(this);
               $obj.click(function() {
                  var $parent =$obj.parent().parent().parent().parent(); // clumsy - use closest() instead!
                  confirm("Bekreft sletting:", function() {
                     $.get($obj.attr('name'), function(data) { 
                       ajaxStatus(data); // does not do anything at this time ...(nowhere to put the status)
                       $parent.slideUp('slow', function() { 
                          $parent.remove(); 
                          if (--genCommentCnt == 0) { $gc.hide(); } 
                          // Update the button count, possibly scroll back to top 
                          $('#vis').attr('value', 'Vis kommentarer ['+genCommentCnt+']');
                       }); 
                     });
                  });
               });
            });
            $gc.find(':button[value=edit]').each(function() {
                var $obj = $(this);
                $obj.click(function (e) {
                    e.preventDefault();
                    contact.$subject = $obj.closest('.discussionItem').find('h3');
                    contact.$message = $obj.closest('.commentBody').find('span');
                    contact.editMode = true;
                    contact.gcMode = true;
                    contact.delButton = $obj.parent().parent().find(':button[value=slett]').attr('name');
                    contact.gcClose = function () {
                      if (didSubmit) { // update the comments section
                        //alert('updating comments');
                        showGenComments('internal');
                        didSubmit = false;
                      }
                      contact.gcMode = false;
                    };
                    $(MM_formdata).modal({ //TODO: fix the modal code so that it finds the content.
			   closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
			   position: ["15%",],
			   overlayId: 'contact-overlay',
			   containerId: 'contact-container',
			   onOpen: contact.open,
			   onShow: contact.show,
			   onClose: contact.close
		    });
                });
            });
        });
     } else {
        showErr('Ingen generelle kommentarer er tilgjengelige. Bruk "Ny kommentar" knappen for å legge inn ny kommentar.\n Egne kommentarer kan endres og slettes.');
     }
}
