if( window.jQuery )  // Avoid more errors in IE 5.0
{
  // Directly set flag for CSS to indicate JavaScript is enabled.
  // At this point "HTML" is the only accessable element.
  $(document.documentElement).addClass("jsEnabled");

  // Make jQuery code easier to debug.
  jQuery.fn.debug = function() { window.console && console.log( this.selector + " =", this ); return this; };

  function _fixLinkTargets()
  {
    // Geef links met rel="external" een target="_blank" attribuut.
    $(document.links).filter('[href][rel=external]').attr("target", "_blank");
  }

  $(document).ready( function() {


    // -------------------------------
    // Fix links

    _fixLinkTargets();


    // --------------------------------
    // Add hover effect for IE 6.0

    if( jQuery.browser.msie )
    {
      // Define actions only once
      var addHover     = function(e) { $(this).addClass("hover"); };
      var removeHover  = function(e) { $(this).removeClass("hover"); };

      // Apply to all elements needed:
      $("table.businesscardTable tbody tr").hover( addHover, removeHover );
    }


    // --------------------------------
    // Activate effect (choose bank)


    // Add "active" class to image labels.
    $("#chooseBankForm label").click( function()
     {
       $("#chooseBankForm label").removeClass("active");
       $(this).addClass("active");
     } );


    // --------------------------------
    // Form input label flip

    // Activeer 'overlabels' over compacte formulieren zoals het zoekscherm
    $('label.overlabel')
      .each( function()
      {
        // Get field
        var label = $(this);
        var id    = this.htmlFor || this.getAttribute('for');
        var field = null;
        if( ! id || ! (field = document.getElementById( id ) ) ) return;

        // Implement show/hide effect
        $(field).addClass("overlabel-js")                 // for setTimeout() below
                .focus( function() { label.hide(); } )
                .blur ( function() { this.value === '' && label.show(); } );

        // Hide overlabel when field is filled in.
        if( field.value !== '' ) 
        {
          label.hide();
        }

        // Also for mouse click
        label.mousedown( function() { setTimeout( function() { field.focus(); }, 20 ); } );
      }
    );

    // Hide overlabels after the form is auto-filled in by the browser.
    setTimeout( function()
    {
      var fields = $("input.overlabel-js");
      var labels = $("label.overlabel");
      fields.each( function() { this.value !== '' && labels.filter("[for=" + this.id + "]").hide(); } );
    }, 50 );

    // update counter so that one can see how many chars are still left
    //alert ( "test: " + $("#propositionField").val().length );
    if ($("#propositioncount").length)
    {
      if ($("#propositionField").val().length > 500)
      {
        $('#propositioncounttext').css("color", "#c00");
        $('#propositioncount').css("color", "#c00");
      }
    $("#propositioncount").html($("#propositionField").val().length);
    $("#propositioncounttext").removeClass("nocss");
    $("#propositionField").keyup(function() {
      //alert("test");
      //$("#propositioncount").html($("#propositionField").length);
      $("#propositioncount").html(this.value.length);
      if (this.value.length>500)
      {
        $('#propositioncounttext').css("color", "#c00");
        $('#propositioncount').css("color", "#c00");
      }
      else
      {
        $('#propositioncounttext').css("color", "#333");
        $('#propositioncount').css("color", "#333");
      }

    });
    }

    // --------------------------------
    // Advanced search 

    $('#advancedsearchLink')
      .wrapInner('<a href="#advanced"></a>')
      .find('a')
        .click( function()
          {
            $('#advancedsearch').slideToggle("slow");
            return false;
          }
        );

    $('#couponTrigger')
      .wrapInner('<a href="#couponform"></a>')
      .find('a')
        .click( function()
          {
            $('#couponFormfield').slideToggle("slow");
            return false;
          }
        );


    // --------------------------------
    // Fancybox effect

    var cardlinks = $('table.businesscardTable > tbody > tr > td > a');
    var terms     = $(document.links).filter('[href][rel=terms]');

    // Animations should be fast and functional.
    // Not slow like "whoo see how cool my effect is". It gets annoying quickly.
    jQuery.fx.speeds._default = 200;


    if( jQuery.fn.fancybox )
    {
      if( cardlinks )
      {
        cardlinks
          .fancybox( { frameWidth: 450
                     , frameHeight: 450
                     , overlayShow: true
                     , overlayOpacity: 0.1
                     , hideOnContentClick: false
                     , callbackOnShow: _fixLinkTargets
                     } )
          .each( function() { this.href += "&ajax=1"; } );   // the 'ajax=1' is picked up by the server.
      }

      if( terms )
      {
        terms
          .fancybox( { frameWidth: 600
                     , frameHeight: 450
                     , overlayShow: true
                     , overlayOpacity: 0.1
                     , hideOnContentClick: false
                     , callbackOnShow: _fixLinkTargets
                     } )
          .each( function() { this.href += "?ajax=1"; } );
      }
    }
    else
    {
      if( terms )
      {
        // zonder fancybox alsnog in een nieuw venster
        terms.attr("target", "_blank");
      }
    }


    // Make the whole row clickable
    if( cardlinks.length > 0 )
    {
      $('table.businesscardTable > tbody > tr').click( function() { $(this).find("td > a").eq(0).click(); } );
    }



    // --------------------------------
    // Edit profile fancybox

    var formFotos = $("#pasfotoField, #bedrijfslogoField");
    if( formFotos.length )
    {
      var editText  = "wijzig afbeelding";
      var form      = formFotos.parents("form").get(0);
      var formId    = form.id;
      var sessionId = ( form.$fs ? form.$fs.value : "" );   // access the hidden '$fs' field.

      if( ! formId )
      {
        window.console && console.error("missing id for element", form);
        return;
      }

      // Traverse back to the previous 'preview' field, and add a link.
      formFotos.each( function() {
        $(this)
          .parents("div.formfield")
          .prev("div.previewfield")
          .find("img")
            // add a link
            .after( "<a href='wijzigafbeelding.shtml?iframe=1' id='editImageLink-" + this.id + "' class='editImageLink-js'>" + editText + "</a>" )
            // and configure the link
            .next("a.editImageLink-js")
            .fancybox( { frameWidth: 600
                       , frameHeight: 250
                       , overlayShow: true
                       , overlayOpacity: 0.1
                       , hideOnContentClick: false
                       } )
            .each( function() {
              var elementId = $(this).parents("div.previewfield").find("label[for]").attr("for");
              var fieldName = $("#" + elementId).attr("name");
              this.href += "&callback=updateProfileForm&formId=" + formId + "&fieldName=" + fieldName + "&sessionId=" + sessionId;
            } )
            // add the error message to make it visible again
            .after( $(this).siblings("small.error") )
      } );
    }



    // --------------------------------
    // Crop area.

    $("#cropField_0, #cropField_1").change( function() { $("#submitButton").get(0).value = ( this.value == "1" ? "Volgende" : "Opslaan" ); } );

    if( jQuery.Jcrop )
    {
      var srcImage    = $("#cropArea img");
      self._cropPreview       = $("#cropPreview");
      self._cropPreviewImg    = $('#cropPreview img');
      self._srcWidth          = srcImage.width();
      self._srcHeight         = srcImage.height();
      self._cropPreviewWidth  = self._cropPreview.width();
      self._cropPreviewHeight = self._cropPreview.height();
      var jcrop_api = srcImage.Jcrop( { onSelect: updateCropPreview
                                      , onChange: updateCropPreview
                                      , minSize: [ 1, 1 ]
                                      //, aspectRatio: ( self._cropPreviewWidth / self._cropPreviewHeight )
                                      , keySupport: false   // workarround for jumping scrollbars.
                                      } );
    }

  } );
}



// This function will be called by the 'wijzigafbeelding.shtml' iframe.
function updateProfileForm( framedata )
{
  // Get the form.
  var $form = $("form#" + framedata.formId ).filter("form");
  var form  = $form.get(0);
  if( ! form ) return;

  // If the server created a session id, set it so images will be restored
  if( ! form.$fs )
  {
    $form.prepend("<input type='hidden' name='$fs' value='" + framedata.sessionId + "'/>");
    $form.find("a.editImageLink-js").each( function()
      {
        if( /sessionId=$/.exec( this.href ) )
        {
          this.href += framedata.sessionId;
        }
      });


  }

  // Set preview
  setFormPreview( form, framedata.fieldName, framedata );

  // Close the fancybox
  jQuery.fn.fancybox.close();
}


function setFormPreview( form, fieldName, fielddata )
{
  // Update the picture.
  var field           = form.elements[ fieldName ];
  var image           = $(field).parents("div.formfield").prev("div.previewfield").find("img").get(0);
  if( image )
  {
    image.src    = fielddata.previewUrl;
    image.width  = fielddata.previewWidth;
    image.height = fielddata.previewHeight;
  }
}


self._cropCss = {};
self._cropImgCss = {};
self._cropTimer = 0;

function updateCropPreview( coords )
{
  if( parseInt( coords.w ) > 0 )
  {
    // Project the box in the limited size of the preview area.
    var maxSize, fitSize;
    if( coords.w > coords.h )
    {
      maxSize = coords.w;
      fitSize = self._cropPreviewWidth;
    }
    else
    {
      maxSize = coords.h;
      fitSize = self._cropPreviewHeight;
    }

    var fitScale = ( fitSize / maxSize );
    var rx = ( self._cropPreviewWidth / fitScale / coords.w );
    var ry = ( self._cropPreviewHeight / fitScale / coords.h );

    var rw = self._cropPreviewWidth;
    var rh = self._cropPreviewHeight;

    // Update the preview.
    self._cropImgCss = { width:      Math.round( self._srcWidth * fitScale ) + 'px'
                       , height:     Math.round( self._srcHeight * fitScale ) + 'px'     // height is scaled equally with width, despite different sized box
                       , marginLeft: '-' + Math.round( coords.x * fitScale ) + 'px'
                       , marginTop:  '-' + Math.round( coords.y * fitScale ) + 'px'      // position does change
                       };
    self._cropCss    = { width:      Math.round( coords.w * fitScale ) + 'px'
                       , height:     Math.round( coords.h * fitScale ) + 'px' };         // preview box itself crops overflow height

    // Set a delay, so quick mouse moves are skipped 
    if( self._cropTimer == 0 )
    {
      updateCropPreviewImg();  // quick feedback for first move.
      self._cropTimer = setTimeout( updateCropPreviewImg, 40 );
    }

    // Update the form for submitting it.
    var c = document.cropForm;
    c.cropX.value      = coords.x;
    c.cropY.value      = coords.y;
    c.cropWidth.value  = coords.w;
    c.cropHeight.value = coords.h;
  }
}

function updateCropPreviewImg()
{
  // Already have the jQuery object cached, avoid finding it after each mouse move.
  self._cropPreview.css( self._cropCss );
  self._cropPreviewImg.css( self._cropImgCss );
  self._cropTimer = 0;
}



