var Forbrukerportalen = {
    loadplugins : Array(),
    // Called once the DOM is loaded
    initialize : function () {
      // Register mouse hover handlers.
      Forbrukerportalen.previewMouseHoverRegister();
      Forbrukerportalen.videoSetup();

      // Initialize plugins
      var plugins = Forbrukerportalen.loadplugins
      var length = plugins.length
      for (var i=0; i<length; i++) {
        plugins[i]();
      }
    },
    // Register plugins so that they may be run once the DOM is completed
    loadPluginOnDOMCompleted : function (pluginfunction) {
      var plugins = Forbrukerportalen.loadplugins;
      plugins[plugins.length] = pluginfunction;
    },

    // Verify that the flash plugin is at least version 8.
    hasRequiredFlashVersion : function () {
      return findflashversion()>=8;
    },

    videoSetup : function () {
      var videowindow = document.getElementById('videowindow');
      if (videowindow) {
        if (!Forbrukerportalen.hasRequiredFlashVersion()){
          parentnode = videowindow.parentNode;  
          parentnode.replaceChild(buildNotSupportedMessage(), videowindow);
        } else {
          // Work around eolas disabled activation.
          videowindow.innerHTML = videowindow.innerHTML;
        }
      }
    },

    // Better feedback when a user hovers the mouse cursor over a condensed view.
    previewMouseHoverRegister : function () {
      if (document.getElementById) {
        // Preview listings
        var element = document.getElementById('UtlistingMIngress');
        if (element) {
          var views = element.getElementsByTagName('div');
          for (var i=0;i<views.length; i++) {
            if (views[i].className=='preview') {
              var view = views[i]
              var headers = view.getElementsByTagName('h3');
              if (headers) {
                view.target_url = headers[0].firstChild.href;
                view.onclick = function (event) { window.location = this.target_url; };
                // Unfortunately modern browsers do not let us update the status bar for security reasons
                view.onmouseover = function (event) { window.status = this.target_url; this.className = 'highlightedpreview'; };
                view.onmouseout = function (event) { window.status = ''; this.className = 'preview'; };
              }
            }
          }
        }
        // Campaigns
        var element = document.getElementById('campaigncoloumn');
        if (element) {
          var campaigns = element.getElementsByTagName('div');
          for (var i=0; i<campaigns.length; i++) {
            var campaign = campaigns[i];
            var headers = campaign.getElementsByTagName('h2');
            if (campaign.className.substr('Kampanje')) {
                campaign.target_url = headers[0].firstChild.href;
                campaign.onclick = function (event) { window.location = this.target_url; return true; };
                // Unfortunately modern browsers do not let us update the status bar.
                campaign.onmouseover = function (event) { window.status = this.target_url; this.className += ' highlightedcampaign'; };
                campaign.onmouseout = function (event) { window.status = ''; this.className = this.className.replace(' highlightedcampaign', ''); }; 
            }
          }
        }
        // Hover on input elements in IE 6
        var elements = document.getElementsByTagName('input');
        if (elements) {
          for (var i=0; elements.lenght; i++) {
            element = elements[i];
            if (element.className == 'standardbutton') {
              element.onmouseover = function (event) { this.className += ' highlightedbutton'; };
              element.onmouseout = function (event) { this.className.replace(' highlightedbutton', ''); };
            }
          }
        }
      }
    }
}


function msdetect() {
  var flashversion = 0;
  for(var i=9; i>0; i--) {
    try {
      var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
      flashversion = i;
      return flashversion;
    }
    catch(e) {
    }
  }
  return flashversion;
}

function findflashversion() {
  var flashinstalled = 0;
  var flashversion = 0;
  MSDetect = "false";
  if (navigator.plugins && navigator.plugins.length) {
    x = navigator.plugins["Shockwave Flash"];
    if (x) {
      flashinstalled = 2;
      if (x.description) {
        y = x.description;
        flashversion = y.charAt(y.indexOf('.')-1);
      }
    }
    else {
      flashinstalled = 1;
    }
    if (navigator.plugins["Shockwave Flash 2.0"]) {
      flashinstalled = 2;
      flashversion = 2;
    }
  }
  else if (navigator.mimeTypes && navigator.mimeTypes.length)
  {
    x = navigator.mimeTypes['application/x-shockwave-flash'];
    if (x && x.enabledPlugin)
            flashinstalled = 2;
    else
            flashinstalled = 1;
  }
  else {
    MSDetect = "true";
  }
  
  // IE flash detection.
  if (MSDetect=="true") {
    flashversion = msdetect();
  }
  return flashversion;
}

function buildNotSupportedMessage(){
  var firsttext="Forbrukerportalen benytter Flash for å kunne spille av filmer på artikkelsider.";
	var secondtext="For å kunne se denne videoen kreves dessverre en ";
	var linktext="nyere versjon av flash-spilleren.";
	
  outerDiv = document.createElement('div');
  outerDiv.setAttribute('id', 'Hovedtemaboks')
	firstparagraph = document.createElement('p');
  firstparagraph.appendChild(document.createTextNode(firsttext));
	secondparagraph = document.createElement('p');
	secondparagraph.appendChild(document.createTextNode(secondtext));
  anchor = document.createElement('a');
  anchor.setAttribute('href', 'http://www.macromedia.com/go/getflashplayer');
  anchor.appendChild(document.createTextNode(linktext));
	secondparagraph.appendChild(anchor);
  outerDiv.appendChild(firstparagraph);  
  outerDiv.appendChild(secondparagraph);  
  return outerDiv
}

function open_video_window(winurl, size) {                   
    winparams = "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=1";
    sizes = size.split('x')
    width = '300';
    height = '200';
    if(sizes.length == 2){
      width = sizes[0];
      height = sizes[1];
    }          
    widthparam = ',width=';
    widthparam += width;
    
    heightparam = ',height=';
    heightparam += height;
    
    winparams += heightparam;
    winparams += widthparam;
    window.open(winurl,'', winparams);
    return false;
}

function increment(listid) {
  return changeImage(listid, 1);
}
function decrement(listid) {
  return changeImage(listid, -1);
}
function changeImage(listid, change) {
  if (document.getElementById) {
    // Update selectednumber
    slideshow = window.slideshows['list_'+listid];
    arraylength = slideshow.length/2;
    selected = window.slideshows['selected_'+listid];
    selected += change;
    if (selected<0) {
      selected = arraylength - 1;
    } else if (selected >= arraylength) {
      selected = 0
    }
    window.slideshows['selected_'+listid] = selected;

    slideshowelement = document.getElementById('slideshow_'+listid);
    if (slideshowelement) {
      // Update image
      image = document.getElementById('listimage_'+listid);
      if (image){
        image.src = slideshow[selected*2];
        // Update count
        span = document.getElementById('listcount_'+listid);
        if (span) {
          //XXX: InnherHTML is nonstandard
          span.innerHTML = (selected+1) + '/' + arraylength;

          // Update text
          textfield = document.getElementById('listtext_'+listid);
          if (textfield) {
            textfield.innerHTML = slideshow[ selected*2 + 1];
            return false;
          }
        }
      }
    }
  }
  return true;
}


// vim: et sts=2 ts=2 sw=2 encoding=utf8 fileencoding=utf8

// funksjon for å sette like høye kolonner for prosessvisningen
function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}


// funksjon for expand/collapse spm&svar
(function($){  
 $.fn.toggler= function(options) {      
  var defaults = {
     toggles: 'next'
  };      
  var options = $.extend(defaults, options);
  return this.each(function() {    
    var obj = $(this);
    var toggles = null;
    obj.next().hide();
    obj.addClass("collapsed")
    if (options.toggles == 'next'){
       toggles = obj.next()
    }  
    else{
       toggles = obj.prev()    
    } 
    obj.toggle(function(){
       obj.addClass('expanded'); 
       toggles.show().css({'margin-left':'15px'});       
    }
    ,function(){
       obj.removeClass('expanded');
       toggles.hide();       
    });
  });  
 };  
})(jQuery); 


$(document).ready(function(){  
    
  Forbrukerportalen.initialize();
    
  $('.toggles.nextElement').toggler();  

  $(".scrambled").each(function(){
      $this = $(this);
      var href = $this.attr("href");
      href = href.replace("_at_","@");
      $this.attr("href",href);
      email = href.replace("mailto:","");
      $this.html(email);
  });

    //setter kolonner for prosess til å være like høye
    equalHeight($(".equalheight"));
    equalHeight($(".fase>a"));
    equalHeight($(".prosessFase"));   
    
    
    // Figure out if we should enable the "show/hide children" controls in the
    // "ArtikkelNavigasjon"-table of contents.
    var enableShowHideChildrenControls = true;
    
    var isInKlageguiden = window.location.pathname.indexOf("/klageguide/") >= 0;
    if(isInKlageguiden) {
        // The "Klageguiden" articles should always show everyting expanded, so we
        // must skip the show/hide children stuff. 
        // The reason we do the check by the slightly hackish way of checking the
        // path is that the viewtemplates are overridden for several of the klageguidenarticles,
        // (i.e. the viewtemplate is placed in the database, as a OFS-child of each article).
        // It would therefore not be trivial to do this the "correct" way (by for instance
        // making the view-template put some marker in the html)
        enableShowHideChildrenControls = false;
    }
    

    var artikkelNavigasjon = $("div#ArtikkelNavigasjon");
    
    // if the "show all" link has been selected, all subheadings are displayed.
    var isShowingAll = artikkelNavigasjon.children("p:first").children("a:first").hasClass("selected");
    
    function onShowHideChildrenLinkClicked(event,show){
        var subHeadingLink = $(event.target);
        var subHeading = subHeadingLink.parent();
        var showChildrenLink = subHeading.children("a.showchildren");
        var hideChildrenLink = subHeading.children("a.hidechildren");
        
        subHeading.children("ul").toggle(show);
        showChildrenLink.toggle(!show);
        hideChildrenLink.toggle(show);

        event.preventDefault();
        return false;
    }
   
    function onHideChildrenLinkClicked(event){
        return onShowHideChildrenLinkClicked(event,false);
    }
    function onShowChildrenLinkClicked(event){
        return onShowHideChildrenLinkClicked(event,true);
    }
   
    var headingList = $("ul:first",artikkelNavigasjon);
    $("li",headingList).each(function(index,subHeading){
        subHeading = $(subHeading);
        var hasChildren = $("ul",subHeading).length>0;
        if(hasChildren && enableShowHideChildrenControls ){
            var showChildrenLink = subHeading.children("a.showchildren");
            var hideChildrenLink = subHeading.children("a.hidechildren");
             
            // hide the children, unless any of the children have been selected.             
            var selectedChildren = $(".selected",subHeading);
            
            if( isShowingAll || (selectedChildren.length > 0) ) {
                hideChildrenLink.show();
            } else {
                subHeading.children("ul").hide();
                showChildrenLink.show();
            }
             
            showChildrenLink.click(onShowChildrenLinkClicked);
            hideChildrenLink.click(onHideChildrenLinkClicked);
        } else {
            // There are no children or the show/hide functionality has been disabled, so show the "nochildren" dummy link.
            var noChildrenLink   = subHeading.children("span.nochildren");
            noChildrenLink.show();
        }
    });
    //expand the selected nodes
    $("li.selected .showchildren:visible").trigger('click');
});


 

