function showForm(obj, f) {
    var
        jQueryobj = jQuery(obj),
        jQueryform = jQuery(f),
        pos = jQueryobj.offset();

    if(jQueryform.length && jQueryobj.length)
    {
      if (!jQueryform.hasClass('__popup')) {
          jQueryobj.addClass('__popup_handler');
          jQueryform.addClass('__popup').appendTo('body');
      } else {
          jQueryobj.removeClass('__popup_handler');
          jQueryform.removeClass('__popup').appendTo('body');
      }
      jQueryform.css({
          position: 'absolute',
          left:     pos.left - ((jQueryform.width() - jQueryobj.width()) / 2) + "px",
          top:      pos.top + 20 + "px"
      }).toggle();
    }
}

function showLoginForm(obj) {
    showForm(obj, '#inloggen_popup');
}

function initIdleFields() {
  jQuery('input[type="text"],textarea').addClass("idleField");
  jQuery('input[type="text"],textarea').focus(function()
  {
    jQuery(this).removeClass("idleField").addClass("focusField");
    if (this.value == this.defaultValue)
    {
      this.value = '';
    }
    if (this.value != this.defaultValue)
    {
      this.select();
    }
  });
  jQuery('input[type="text"],textarea').blur(function()
  {
    jQuery(this).removeClass("focusField").addClass("idleField");
    if (jQuery.trim(this.value) == '')
    {
      this.value = (this.defaultValue ? this.defaultValue : '');
    }
  });
}

function attachPopupEventHandlers()
{
  jQuery('body').click(function(e) {
        if (!jQuery(e.target).hasClass('__popup_handler')) {
            jQuery('.__popup').filter(
                function() {
                    return this != e.target && jQuery(e.target).parents('.__popup').length == 0;
                }).hide();
        }
    });
}

function initPiwikTracker()
{
  var goalMap = {
    4:  'body.Home #inloggen_popup button.greyBtn',
    5:  'a[href^="mailto:"]',
    9:  'body.laatste-nieuws #inloggen_popup button.greyBtn',      
    10: 'body.opinie #inloggen_popup button.greyBtn',
    11: 'body.forecastenprijzen #inloggen_popup button.greyBtn',
    12: 'body.over-powerhouse .ce_zad_aplayer .play',
    20: 'body.handelsplatform .ce_zad_aplayer .play'
  };


  for(var goal in goalMap) {
      jQuery(goalMap[goal]).data('goal', goal).click(function() {
          //alert('test!!');
        piwikTracker.trackGoal($(this).data('goal'));
      });
  }
}

function initDropDownMenu()
{
  jQuery('#nav').droppy({speed: 0});
  jQuery('#nav li:has(li.active)').addClass('active');
}

jQuery(document).ready(function() {
  initDropDownMenu();
  showForm('#right_col a.meer_weten', '#popup-contact:has(input.error)');
  attachPopupEventHandlers();
  initIdleFields();
  initPiwikTracker();
});
