Element.addMethods({
  'visibleExtended': function(element) {
    return element.visible() && (element.getStyle('display') !== 'none');
  }
});

var HoverObserver = Class.create({
  initialize: function(elementSelector,options) {
    this.options = Object.extend({
      'className':      'hover',
      'startEvent':      'mouseenter',
      'stopEvent':      'mouseleave',
      'startDelay':      250,
      'stopDelay':      100
    },options || {});

    $$(elementSelector).each(function(element){
      element.observe(this.options.startEvent, this.onStart.bindAsEventListener(this,element));
      element.observe(this.options.stopEvent, this.onStop.bindAsEventListener(this,element));
    },this);
  },
  debug: function(str) {
    this.debugWindow.document.write(str+"<br>");
  },
  onStart: function(event,element) {
    if (element.timeout != null) { clearTimeout(element.timeout); }
    element.timeout = setTimeout(this.onStartDelayed.bind(this,element),this.options.startDelay);
  },
  onStop: function(event,element) {
    if (element.timeout != null) { clearTimeout(element.timeout); }
    element.timeout = setTimeout(this.onStopDelayed.bind(this,element),this.options.stopDelay);
  },
  onStartDelayed: function(element) { element.addClassName(this.options.className); },
  onStopDelayed: function(element) { element.removeClassName(this.options.className); }

});

var FoldObserver = Class.create({
  initialize: function(parentElementSelector,actionElementSelector,options) {
    this.parentElementSelector = parentElementSelector;
    this.options = Object.extend({
    },options||{});
    $$(actionElementSelector).each(function(actionElement){
      actionElement.observe('click',this.onClick.bindAsEventListener(this,actionElement));
    },this);
  },
  onClick: function(event,element) {
    element.up(this.parentElementSelector).toggleClassName('unfolded');
    Event.stop(event);
  }
});

var PopupWindow = Class.create({
  initialize: function(element,options) {
    this.options = Object.extend({
    },options||{});

    var tmpElement;
    tmpElement = new Element('DIV');
    tmpElement.addClassName('popup_wrapper');
    element.wrap(tmpElement);

    this.container = new Element('DIV');
    this.container.addClassName('popup_container');
    tmpElement.wrap(this.container);

    tmpElement = new Element('DIV');
    tmpElement.addClassName('popup_top');
    this.container.insert({'top':tmpElement});

    tmpElement = new Element('DIV');
    tmpElement.addClassName('popup_bottom');
    this.container.insert({'bottom':tmpElement});
  }
});

var PopupObserver = Class.create({
  initialize: function(selector,options) {
    this.options = Object.extend({
    },options||{});
    $$(selector).each(function(element){
      new PopupWindow(element,options);
    });
  }
});

var TabObserver = Class.create({
  initialize: function(containerElement,options) {
    this.options = Object.extend({
      'linkSelector':  'A',
      'tabSelector':  '.infobox_header LI',
      'tabParentSelector': 'LI',
      'bodySelector':  '.infobox_body',
      'bodyIdSuffix':  '_body'
    },options||{});

    // TODO: Consider click delegation
    this.bodyElements = containerElement.select(this.options.bodySelector);
    this.tabElements = containerElement.select(this.options.tabSelector);
    this.tabElements.each(function(tabElement){
      tabElement.select(this.options.linkSelector).each(function(linkElement){
        var bodyId = linkElement.id+this.options.bodyIdSuffix;
        var bodyElement = $(bodyId);
        if (bodyElement === null) {
          return;
        }
        tabElement.observe('click',this.onClick.bindAsEventListener(this,tabElement,bodyElement));
        if (tabElement.hasClassName('selected')) {
          this.viewTab(tabElement,bodyElement);
        }
      },this);
    },this);
  },
  viewTab: function(tabElement,bodyElement) {
    // Hide others
    this.tabElements.invoke('removeClassName','selected');
    this.bodyElements.invoke('removeClassName','unfolded');
    // Show selected
    tabElement.addClassName('selected');
    bodyElement.addClassName('unfolded');
  },
  onClick: function(event,tabElement,bodyElement) {
    Event.stop(event);
    this.viewTab(tabElement,bodyElement);
  }
});

var DoubleSearchSet = Class.create({
  initialize: function(containerElement,url,callback) {
    this.containerElement = $(containerElement);
    this.url = url;
    this.valid = false;
    this.callback = callback;
  },
  isValid: function() {
    return this.valid;
  },
  _callback: function() {
    if (this.callback !== undefined) {
      this.callback(this);
    }
  },
  search: function(str) {
    this._showWorking();
    
    // Initialize
    this.pageCount = undefined;
    this.pageNumber = undefined;
    this.searchString = str;
    this.pageNumber = 0;

    // Get number of pages
    new Ajax.Request(this.url,{
      'method': 'get',
      'parameters': {
        'SearchName': this.searchString,
        'PageCount': 1,
        'Page': 1,
        'ForcePages': 'true',
        'EmployeeFilter': 'all'
      },
      'onFailure': this._showError.bind(this),
      'onSuccess': this._onPageCountReceived.bind(this)
    });
  },
  getPageCount: function() {
    return this.pageCount;
  },
  moreResultsAvailable: function() {
    return this.valid && (this.pageNumber < this.pageCount);
  },
  appendNextPage: function() {
    // Within page limits?
    if (!this.moreResultsAvailable()) {
      return;    
    }
    // Load page
    this.pageNumber++;
    new Ajax.Request(this.url,{
      'method': 'get',
      'parameters': {
        'SearchName': this.searchString,
        'PageCount': 0,
        'Page': this.pageNumber,
        'ForcePages': 'true',
        'EmployeeFilter': 'all'
      },
      'onFailure': this._showError.bind(this),
      'onSuccess': this._onResultReceived.bind(this)
    });  
  },
  _onPageCountReceived: function(transport) {
      var n = transport.responseText;
      if (n.match(/^[0-9]+$/) === null) {
        this._showError();
      }
      this.valid = true;
      this.pageCount = n;
    
      if (this.pageCount>0) {
        // Show first page
        this.appendNextPage();
      } else {
        // No results
        this._clearContainerElement();
        this.callback(this);
      }
  },
  _clearContainerElement: function() {
    this.containerElement.update('');
  },
  _onResultReceived: function(transport) {
    var result = transport.responseText;
    // First time?
    if (this.pageNumber==1) {
      this._clearContainerElement();
    }
    // Append to containerElement
    this.containerElement.insert({'bottom':result});
    this._callback();
  },
  _showWorking: function() {
    this.valid = false;
    this.containerElement.update('<div class="searchstatus working">Et øjeblik..</div>');
  },
  _showEmpty: function() {
    this.containerElement.update('<div class="searchstatus empty">Din søgning gav intet resultat.</div>');
  },
  _showError: function() {
    this.containerElement.update('<div class="searchstatus error">Søgningen fejlede.</div>');
    this.valid = false;
    this._callback();
  }
});

var DoubleSearch = Class.create({
  initialize: function(containerElement,options) {
    this.options = Object.extend({
    },options||{});
    this.containerElement = containerElement;
    //this.containerElement
    //  .down('INPUT[type=submit]')
    //  .observe('click',this._onSubmit.bindAsEventListener(this));
    this.inputElement = this.containerElement.down('INPUT[type=text]');
    
    this.search1 = new DoubleSearchSet('doublesearchform_result1','/umbraco/AjaxContentResult.aspx',this._onSearchCompleted.bind(this));
    this.search2 = new DoubleSearchSet('doublesearchform_result2','/umbraco/AjaxEmployeeResult.aspx',this._onSearchCompleted.bind(this));
  
    this.showMoreButton = $('doublesearchform_showmore');
    if (this.showMoreButton) {
      this.showMoreButton.observe('click',this._onShowMoreClicked.bindAsEventListener(this));
    }
    
    // Do initial search?
    var regexp = new RegExp(/[?&]q=([^&#]+)/);
    var results = regexp.exec(document.location.search);
    if (results) {
        var str = decodeURIComponent(results[1].replace(/\+/g, " "));
        //var str = unescape(results[1].replace(/\+/g, " "));
      this.inputElement.setValue(str);
      this._doSearches(str);
    }
  },
  _onShowMoreClicked: function(evt) {
    Event.stop(evt);
    this.searchesCompleted = 0;
    this.search1.appendNextPage();
    this.search2.appendNextPage();
    if (this.showMoreButton) { this.showMoreButton.hide(); }    
  },
  // Called once per completed search(!)
  _onSearchCompleted: function(search) {
    this.searchesCompleted++;
    if (this.searchesCompleted == 2) {
      var webResults = this.search1.getPageCount();
      var empResults = this.search2.getPageCount();
      this._updateSummary(
        'Din søgning på "' + this.searchString + 
        ((webResults == 0 && empResults == 0) ? '" gav ingen resultater' : '" gav følgende resultater')
        
        
        //'Din søgning på "'+this.searchString+'" gav '+
        //(webResults ? webResults : 'ingen')+' side'+(webResults==1?'':'r')+' med websider og '+
        //(empResults ? empResults : 'ingen')+' side'+(empResults==1?'':'r')+' med medarbejdere.'
      ); 
    }
    
    if (search.isValid() && search.moreResultsAvailable()) {
      if (this.showMoreButton) { this.showMoreButton.show(); }
    }
    Cufon.refresh(".header5");
  },
  _onSubmit: function(evt){
    Event.stop(evt);
    this._doSearches(this.inputElement.getValue());
  },
  _updateSummary: function(str) {
    if ($('doublesearchform_summary')) {
        $('doublesearchform_summary').update(str);
    }
  },
  _doSearches: function(str) {
    this.searchString = str;
    if (this.showMoreButton) { this.showMoreButton.hide(); }
    this._updateSummary('');
    this.searchesCompleted = 0;
    this.search1.search(str);
    this.search2.search(str);
  }
});

var EmployeeSearch = Class.create({
  initialize: function(containerElement,options) {
    this.options = Object.extend({
      url: '/umbraco/AjaxEmployeeResult.aspx'
    },options||{});
    this.containerElement = containerElement;
    this.searchButton = this.containerElement.down('INPUT.search');
    this.resultElement = this.containerElement.down('#results');
    this.resultFrameElement = this.resultElement.up('.infobox_section_frame');
    this.resultContainerElement = this.resultElement.up('.infobox_section_container');
    this.searchButton.observe('click',this.onSearchClick.bindAsEventListener(this));
    this.resultContainerElement.removeClassName('unfolded');
    
    // Add "show more matches" element
    this.nextElement = new Element('DIV');
    this.nextElement.addClassName('more-results-button');
    this.nextElement.update('<img src="/css/img/result-pager-next.png" />');
    this.nextElement.hide();
    this.resultElement.up().insert({bottom:this.nextElement});
    this.nextElement.observe('click',this.onMoreClick.bindAsEventListener(this));
  },
  hideResults: function() {
    // Hide results
    this.resultContainerElement.removeClassName('unfolded');
    this.resultElement.update("");
  },
  showResults: function() {
    this.resultContainerElement.addClassName('unfolded');
  },
  onMoreClick: function(e) {
    if (this.currentPage < this.pageCount) {
      this.appendPage();
    }
    if (this.currentPage >= this.pageCount) {
      this.nextElement.hide();
    }
  },
  onSearchClick: function(e) {
    Event.stop(e);
    this.hideResults();

    this.param = {};
    this.containerElement.select('INPUT[type=text]','SELECT').each(function(element){
      this.param[element.classNames()] = element.getValue();
          },this);

    this.param['PageCount']=1;
    this.param['Page']=1;
    new Ajax.Request(this.options.url,{
      method: 'get',
      parameters: this.param,
      onSuccess: this.onPageCountReady.bind(this)
    });
  },
  onPageCountReady: function(transport) {
    if (transport.responseText.match(/^\d+$/)===null) {
      this.resultElement.update('Error:<br/>'+transport.responseText);
      this.showResults();
      return;
    }
    this.pageCount = transport.responseText;
    this.currentPage = 0;
    if (this.pageCount) { this.appendPage(); }
    if (this.pageCount>1) { this.nextElement.show(); }
  },
  appendPage: function() {
    this.currentPage++;
    this.param['PageCount'] = 0;
    this.param['Page'] = this.currentPage;
    new Ajax.Request(this.options.url,{
      method: 'get',
      parameters: this.param,
      onSuccess: this.onResultReady.bind(this)
    });
  },
  onResultReady: function(transport) {
    this.showResults();

    var element = new Element('DIV');
    //element.hide();
    element.addClassName('resultpart');
    element.update(transport.responseText);
    this.resultElement.insert({
      bottom: element
    });
    //Effect.BlindDown(element);
    Cufon.refresh(".header5");
  }
});

Site = Class.create({
});

site = new Site();

// DOM Loaded events
document.observe("dom:loaded", function() {
  new HoverObserver('.infobox_header LI');
  new HoverObserver('.linklist LI');
  new FoldObserver('.infobox_section_container','.infobox_section_actions');
  new PopupObserver('.popup');

  if (Prototype.Browser.Gecko == true) {
    var employeeEmail = $("employee-email");
    if (employeeEmail != null) {
      employeeEmail.setStyle({"top": "4px"});
    }
    var employeeVcard = $("employee-vcard");
    if (employeeVcard != null) {
      employeeVcard.setStyle({"top": "4px"});
    }
  }
  
  $$('p.factsbox').each(function(element) {
    element.insert(new Element("div", { "class": "facts-header" }));
    element.insert(new Element("div", { "class": "facts-footer" }));
  });

  $$('.simplepage .rightcolumn').each(function(element){
    var rightElementHeight = element.getDimensions().height + 100;
    var contentHolderElement = $$('.simplepage')[0];
    if (rightElementHeight > contentHolderElement.getDimensions().height) {
      contentHolderElement.setStyle({"height": rightElementHeight + "px" });
    }
  });

  $$('.contentbody_block.underlined').each(function(element){
    var elementText = element.innerHTML.trim().toLowerCase().replace(/\"/g, '');
    if (elementText=='<span class=small-heading></span>'){
      element.hide();
    }
  });

  if ($('infobox')) {
    new TabObserver($('infobox'));
  }
  
  // Instantiate DoubleSearch if form is present
  if ($('doublesearchform')) {
    new DoubleSearch($('doublesearchform'));
  }
  
  // Replace .greybutton input submit's with buttons's
  $$('INPUT[type="submit"].greybutton').each(function(inputElement){
      // Create new button element
      var buttonElement = new Element('BUTTON');
      buttonElement.addClassName('greybutton');
      var spanElement = new Element('SPAN');
      spanElement.update(inputElement.value);
      spanElement.wrap(buttonElement);

    // Create new hidden element (and hold it in limbo for now)
    var hiddenElement = new Element('INPUT');
    hiddenElement.writeAttribute('type','hidden');
    hiddenElement.writeAttribute('id',inputElement.readAttribute('id'));
    hiddenElement.writeAttribute('name',inputElement.readAttribute('name'));
    hiddenElement.writeAttribute('value',inputElement.readAttribute('value'));

    // Visually replace element
      inputElement.insert({'after':buttonElement});
      inputElement.hide();

      // Observe click on new button
      buttonElement.observe('click',(function(event){
          Event.stop(event);
    buttonElement.previous().click();
    $$('input').each(function(resetElement) {
      if (resetElement.hasClassName("input-error-element") == true) {
        resetElement.removeClassName("input-error-element");
      }
    });
    $$('.error-message').each(function(errorElement) {
      errorElement.previous("input").addClassName("input-error-element");
    });
/*
    inputElement.insert({'after':hiddenElement});
    inputElement.form.submit();
*/
      }).bindAsEventListener());
  });

  // Wrap inline images in correct DIV and use ALT-text as caption
  $$('.inlineimage-right,.inlineimage-left').each(function(imgElement){
    var divElement = new Element('DIV');
    divElement.addClassName('inlineimage');
    divElement.addClassName(imgElement.hasClassName('inlineimage-left') ? 'left' : 'right');

    imgElement.writeAttribute('class','');
    imgElement.wrap(divElement);

    var captionStr = imgElement.readAttribute('alt');
    if (captionStr.match(/^\w+$/)===null) {
      var captionElement = new Element('DIV');
      captionElement.addClassName('caption');
      captionElement.update(captionStr);
      divElement.insert({bottom:captionElement});
    }
    var pElement = imgElement.up('P');
    pElement.insert({before:divElement});    
  });

/*
  $$('.search-result-top-link').each(function(element){
    var target = $(element.up().getElementsByClassName("search-result-bottom-link")[0]);
    var linkElement = new Element('A');
    linkElement.writeAttribute('href',element.readAttribute('href'));
    linkElement.update(element.readAttribute('href'));
    target.appendChild(linkElement);
  });
*/


  $$('.infobox_section.office-employee-container').each(function(element){
    new EmployeeSearch(element.up('.infobox_body'));
  });

/*
  var employeeSearchPage = 1;
  if ($$("#employee-search-filters .search").length > 0)
  {
    $$("#employee-search-filters .search")[0].observe("_click", function(event) {
      event.preventDefault();

      
      var employeeFilter = "";
      var areaFilter = "";
      var searchName = "";

      var searchQuery = "/umbraco/AjaxEmployeeResult.aspx";
      searchQuery += "?Page=" + employeeSearchPage;
      searchQuery += "&EmployeeFilter=" + $$(".EmployeeFilter")[0].getValue();
      searchQuery += "&AreaFilter=" + $$(".FilterArea")[0].getValue();
      searchQuery += "&SearchName=" + $$(".SearchName")[0].getValue();
      searchQuery += "&CountryPart=" + $$(".CountryPart")[0].getValue();

      new Ajax.Request(searchQuery, {
        onSuccess: function(response) {
          //$$("#search-results-pager a")[0].show();
          var resp = new Element("div").update(response.responseText);
          resp.hide();
          $$(".search-results")[0].insert(resp);
          Effect.SlideDown(resp);
          employeeSearchPage++;
          Cufon.refresh(".header5");
        }
      });
      return false;
    });
  }
*/


  // Ajax search
  if ($$("#search-results-pager a").length > 0)
  {
    $$("#search-results-pager a")[0].observe("click", function(event) {
      event.preventDefault();
      var page = $("Page").getValue();
      page++;
      $("Page").setValue(page);
      var numberOfSearchResultItemsPerPage = $("NumberOfSearchResultItemsPerPage").getValue();

      //$(this).hide();

      var searchQuery = "/umbraco/AjaxSearcher.aspx";
      searchQuery += "?SearchStartNodeId=" + $("SearchStartNodeId").getValue();
      searchQuery += "&DocumentTypes=" + $("DocumentTypes").getValue();
      searchQuery += "&SearchFields=" + $("SearchFields").getValue();
      searchQuery += "&NumberOfSearchResultItemsPerPage=" + numberOfSearchResultItemsPerPage;
      searchQuery += "&MisspelledWordsNodeId=" + $("MisspelledWordsNodeId").getValue();
      searchQuery += "&Query=" + $("Query").getValue();
      searchQuery += "&Page=" + page;

      // show ajax loader
      $$("#search-results-pager a")[0].hide();
      $("search-results-loader").show();

      new Ajax.Request(searchQuery, {
        onSuccess: function(response) {
          $$("#search-results-pager a")[0].show();
          $("search-results-loader").hide();
          // hide
          var page = $("Page").getValue();
          var numberOfSearchResultItemsPerPage = $("NumberOfSearchResultItemsPerPage").getValue();
          if (numberOfSearchResultItemsPerPage * page >= $("TotalResults").getValue())
          {
            $("search-results-pager").hide();
          }
          var resp = new Element("div").update(response.responseText);
          resp.hide();
          $$("#search-results-page ul")[0].insert(resp);
          //resp.appear();
          Effect.SlideDown(resp);
        }
      });
      return false;
    });
  }

  if ($$(".employee-pager a").length > 0)
  {
    $$(".employee-pager a").each(function(element){
      element.observe("click", function(event) {
        event.preventDefault();
        new Ajax.Request($(this).readAttribute("href"), {
          onSuccess: function(response) {
            var resp = new Element("div").update(response.responseText);
            var content = resp.select("#tab1_body");
            
            Element.replace("tab1_body", content.innerHTML);
            //$$("#tab1_body").update();
          }
        });
        return false;
      });
    });
  }

  $$(".contentbody_block.underlined").each(function(element){
    if (element.empty() == true) {
      element.remove();
    }
  });

  var removedFirst = false;
  if ($$("#tab1_body .infobox_section_body").length == 1)
  {
    if ($$("#tab1_body .infobox_section_body")[0].empty() == true) {
      $("tab1").up('li').remove();
      $("tab1_body").remove();
      $("tab2").up('li').className = "first selected";
      $("tab2_body").addClassName("unfolded");
      removedFirst = true;
    }
  }

  if ($$("#tab2_body .infobox_section_body").length == 1)
  {
    if ($$("#tab2_body .infobox_section_body")[0].empty() == true) {
      $("tab2").up('li').remove();
      $("tab2_body").remove();
      if (removedFirst == true)
      {
        $("tab3").up('li').className = "first selected";
        $("tab3_body").addClassName("unfolded");
      }
    }
  }
});

function tabboxlink(id, tab)
{
  $('tab' + tab).simulate  ("click");
  $$('.tab_fold_unfold_' + id + ' .unfold a').each(function(element){
    if (element.up('.infobox_section_container.unfolded') == null) {
      element.simulate('click');
    }
  });
  //window.location.hash = "#" + id + "-" + tab;
  window.location.hash = "#" + id;
}

// Window Loaded events
Event.observe(window, 'load', function(){
  // Tweak width on inline image containers

  $$('.inlineimage').each(function(element){
    element.select('IMG').each(function(imageElement){
      element.setStyle({'width':imageElement.getWidth()+"px"});
    });
  });
  /***** Cufon Font Replacement *****/
  if ($("print-bar").visibleExtended() == false) {
    Cufon.replace('.infobox_header A',{
        'hover':  true
    });
    Cufon.replace('.header_menu A',{
        'hover':  true
    });
    Cufon.replace('.hugefeature A');
    Cufon.replace('.foregroundlink A');
    //Cufon.replace('H1, H2, .header_bar_frame p');
    Cufon.replace('h1, .header1, .header2, .header_bar_frame p');
    //Cufon.replace('H3, .minifeature_header');
    Cufon.replace('h3, .large-heading, .minifeature_header');
    Cufon.replace('.header4');
    Cufon.replace('.section-header-title');
    Cufon.replace('.header5');
    Cufon.replace('.small-heading');
    Cufon.replace('.header6');
    Cufon.replace('.header3');
    Cufon.replace('.buttons BUTTON');
    Cufon.replace('#employee-header');
    Cufon.replace('#employee-phone');
    Cufon.replace('#employee-email');
    Cufon.replace('#employee-vcard-header');
    Cufon.replace('#employee-vcard');
    
    Cufon.replace('.facts-header span');
  }
});

Element.prototype.triggerEvent = function(eventName)
{
    if (document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);

        return this.dispatchEvent(evt);
    }

    if (this.fireEvent)
        return this.fireEvent('on' + eventName);
}

