Expandable = $.klass({
  onmousedown: function() { 
    $(this.element).parent().find('ul').toggle();
  }
});

$(document).ready(function(){
  // put the cursor into the front page search field by default
  $('input#fpsearch-field').focus();
  // make sure the front page submit button is not disabled (happends when the form is submitted)
  $('input#fpsearch-button').disabled = false;

  $("#fpfocus a").fancybox({
    'frameWidth'          : 714,
    'frameHeight'         : 463,
    'hideOnContentClick'  : false
  }); 

  $('a.popup').click(function(event) {
    // Prevent the browser's default onClick handler
    event.preventDefault();

    // Grab parameters using jQuery's data() method
    var params = $(this).data("popup") || {};            

    // Use the target attribute as the window name
    if ($(this).attr("target")) {
      params.windowName = $(this).attr("target");
    }

    // Pop up the window
    var windowObject = UTIL.popup.open(this.href, params);

    // Save the window object for other code to use
    $(this).data("windowObject", windowObject);
  });

  // style the sort form on the search result
  $('form#sortform input#sort-submit-button').remove();
  $('form#sortform select#sort').change(function(){
    $('form#sortform').submit();
  });
  $('li.expand span').attach(Expandable);

  // make the "add as favorite" forms in product listings apear as links
  $('table.result form.favorite input.add').replaceWith('<a href="#" class="gray">Tilføj som favorit</a>');
  $('table.result form.favorite input.remove').replaceWith('<a href="#" class="gray">Fjern favorit</a>');
  $('table.result form.favorite a').click(function(){
    $(this).parent().submit();
    return false;
  });

  // make the flash messages disappear after a certain amound of time
  setTimeout(hideFlashMessages, 8000);

  // combobox stuff: enable the posibility of a custom value in a select box
  $('select.combobox').next('input.combobox-custom-value').hide();
  $('select.combobox').change(function(){
    var select = $(this);
    var custom = select.next('input.combobox-custom-value');
    if (select.val() == 'custom')
      custom.fadeIn(200);
    else if (custom.is(':visible'))
      custom.fadeOut(200).val('');
  });

  // add Google Analytics tracking to outbound, email and download links
  $('a:not([href*="' + document.domain + '"])').click(function(e) {
    var href = $(this).attr('href');
    var path = '';
    if (href.match(/^mailto:/)) {
      var email = href.replace(/^mailto:(.*)/, '$1').split('@');
      path = '/email/' + email[1] + '/' + email[0];
      category = 'E-mails';
      action = 'Click mailto link';
      label = href.replace(/^mailto:(.*)/, '$1');
    }
    else if (href.match(/^(http:\/\/www\.digitaleprodukter\.dk)?\/downloads\//)) {
      path = '/download/' + href.replace(/^(http:\/\/www\.digitaleprodukter\.dk)?\/downloads\/(.*)/, '$2');
      category = 'Misc downloads';
      action = href.split('.').pop().toUpperCase();
      label = href.replace(/^(http:\/\/www\.digitaleprodukter\.dk)?\/downloads\/(.*)/, '$2')
    }
    else if (href.match(/^(http|https|ftp|ftps):\/\//)) {
      path = '/outbound/' + href.replace(/:\/\//, '/');
      category = 'Navigation';
      action = 'Follow outbound link';
      label = href;
    }

    if(path) {
      _gaq.push(['_trackEvent', category, action, label]);
      _gaq.push(['_trackPageview', path]);
    }
  });
});

$(function() {
  $('.gallery a.lightbox').lightBox({
    imageLoading: '/images/lightbox-gallery/lightbox-ico-loading.gif',
    imageBtnClose: '/images/lightbox-gallery/lightbox-btn-close.gif',
    imageBtnPrev: '/images/lightbox-gallery/lightbox-btn-prev.gif',
    imageBtnNext: '/images/lightbox-gallery/lightbox-btn-next.gif',
    imageBlank: '/images/lightbox-gallery/lightbox-blank.gif',
    txtImage: 'Billede',
    txtOf: 'af'
  });
});

function hideFlashMessages() {
  $('div#notice, div#warning, div#error').fadeOut(1000)
}

// Create a namespace for our utilities
var UTIL = UTIL || {};
UTIL.popup = UTIL.popup || {};

/**
* Open popup window
*
* Opens a popup window using as little as a URL. An optional params object can
* be passed.
*
* @param {String} href
* @param {Object} params
* @return {WindowObjectReference}
*/
UTIL.popup.open = function (href, params)
{
   // Defaults (don't leave it to the browser)
   var defaultParams = {
       "width":       "950",   // Window width
       "height":      "600",   // Window height
       "top":         "0",     // Y offset (in pixels) from top of screen
       "left":        "0",     // X offset (in pixels) from left side of screen
       "directories": "no",    // Show directories/Links bar?
       "location":    "no",    // Show location/address bar?
       "resizeable":  "yes",   // Make the window resizable?
       "menubar":     "no",    // Show the menu bar?
       "toolbar":     "no",    // Show the tool (Back button etc.) bar?
       "scrollbars":  "yes",   // Show scrollbars?
       "status":      "no"     // Show the status bar?
   };

    var windowName = params["windowName"] || "new_window";

    var i, useParams = "";

    // Override defaults with custom values while we construct the params string
   for (i in defaultParams)
   {
       useParams += (useParams === "") ? "" : ",";
       useParams += i + "=";
       useParams += params[i] || defaultParams[i];
   }

    return window.open(href, windowName, useParams);
};