﻿jQuery(function() {
  // Onready catch click on new captcha
  jQuery("div.rij.captcha").each(function() {
    var current = $(this);
    var img = current.find("img.captchaimage");
    var lnk = current.find("a.captcha_renew_link");
    var imgSrc = img.attr("src");

    var counter = 0;
    lnk.click(function() {
      img.attr("src", imgSrc+"&count="+(counter++));
      return false;
    });
  });

  if (jQuery.browser.msie && jQuery.browser.version < 8) {
    jQuery("table[class]").each(function() {
      if ($(this).attr("class") != '' && $(this).attr("class").contains(' ')) {
        var spacing = $(this).attr("class").split(' ');
        if(spacing.length > 0 && spacing[spacing.length -1].contains('spacing')) {
          spacing = spacing[spacing.length -1].substring(7);
          jQuery(this).attr("cellspacing", spacing);
        }
      }
    });
  }
});

(function($){
 /*
  Chain functions down here
  */

 /*
  Replace element by another element.
  Returns new element.
  */
  $.fn.replaceBy = function(selector) {
    $(this).after($(selector)).remove();
    return $(this);
  };

 /*
  Delays an animation.
  Returns the original wrappedset.
  */
  $.fn.delayedAnimate = function() {
      var args = arguments;
      if (args != null && args.length > 0) {
        var delayTime = 500;
        var time = 1000;
        var css;
        var func;
        switch(args.length) {
          case 1:
            css = args[0];
            break;
          case 2:
            css = args[0];
            delayTime = args[1];
            break;
          case 4:
            css = args[0];
            time = args[1];
            delayTime = args[2];
            func = args[3];
            break;
          default:
            css = args[0];
            time = args[1];
            delayTime = args[2];
            break;
        }
        var current = $(this);
        setTimeout(function() {
            current.stop().animate(css, time, func);
          }, delayTime, current, css, time, func);
      }
      return $(this);
    };

    /*
     * Chop inner text until it fits in its container
     */
    $.fn.chop = function(setTextAsAlt) {
      $(this).each(function(i) {
        var jBlock=$(this);
        var text = jBlock.text();
        if (setTextAsAlt) {
          jBlock.attr("title", text);
        }
        if (!text) { return; }

        var jSpan = $("span", jBlock);
        if (!jSpan.length) {
          jBlock.wrapInner(document.createElement("span"));
          jSpan = $("span", jBlock);
        }

        // Try to chop the string according to height and width.
        var realArea = jSpan.height() * jSpan.width();
        var blockArea = jBlock.height() * jBlock.width();
        // + 20 to ensure chopping is done.
        var startLength = Math.round((blockArea/realArea) * text.length) + 20;
        if (text.length > startLength) {
          text = (text.substring(0, startLength));
        }

        jBlock.scrollLeft(1);
        jBlock.scrollTop(1);
        while (text && (jBlock.scrollLeft() > 0 || jBlock.scrollTop() > 0)) {
          text = text.substring(0, text.length - 1);
          jSpan.text(text + "...");
          jBlock.scrollLeft(1);
          jBlock.scrollTop(1);
        }
      });

      return $(this);
    };

 /*
  Creates an id if the element doesn't have one
  Returns the original wrappedset.
  */
  var makeIdCounter = 1;
  $.fn.makeId = function() {
    var prefix = 'infoprojects';
    if (arguments.length > 0) {
      prefix = arguments[0];
    }
    $(this).not("[id]").each(function() {
        var id = prefix + makeIdCounter++;
        $(this).attr("id", id);
      });
    return $(this);
  };

 /*
  Returns the names of element in the dom
  */
  $.fn.tag = function() {
    var tags = new Array();
    $(this).each(
      function() {
        tags[tags.length] = $(this)[0].tagName;
      }
    );
    if (tags.length == 1 && tags[0] == "undefined") {
      return null;
    }
    else if (tags.length == 1) {
      return tags[0];
    }
    else {
      return tags;
    }
    return $(this);
  };

 /*
  Gets the rectangle info for a tag
  */
  $.fn.rectangle = function(useWhenNotVisible) {
    var lv_useWhenNotVisible = useWhenNotVisible != null ? useWhenNotVisible : $(document);
    try {
      var rectangleThis = $(this);
      if (rectangleThis.size() > 1) {
        return rectangleThis.filter(":first").rectangle();
      }
      else if (rectangleThis.size() == 1) {
        var full = false;
        var current = $(this);
        if (!current.tag()){
          current = $(lv_useWhenNotVisible);
        };
        if (!current.tag() || current.tag() == "body") {
          full = true;
        };
        return  {
          // width: full ? "100%" : current.width(),
          // height: full ? "100%" : current.height(),
          width: full ? $(document).width() : current.width(),
          height: full ? $(document).height() : current.height(),
          left: current[0].tagName == null ? 0 : current.offset().left,
          top: current[0].tagName == null ? 0 : current.offset().top
        };
      }
    }
    catch (e) {
      alert("Something went wrong: " + e.message);
      return null;
    }
  };

 /*
  Set the maxlength of a text input
  */
  $.fn.maxLength = function(maxlength) {
    var current = $(this);
    if (maxlength == null) {
      current.each(function() {
        var found = $(this).attr("class").match(/maxlength_([0-9].*)/);
        if (found.length > 0) {
          var curmaxlength =  parseInt(found[1],10);
          if (!isNaN(curmaxlength) && curmaxlength > 0) {
            $(this).maxLength(curmaxlength);
          }
        }
      });
    }
    else {
      var checkMaxLength = function(textbox, maxlength) {
        var length = textbox[0].value.replace("\n", "##").length;
        var jLength = textbox[0].value.length;
        var difference = length - jLength;
        // Only when enters have been entered ;-), set difference - 1
        if (difference > 0) {
          difference -= 1;
        }

        if (textbox[0].value.replace("\n", "##").length > maxlength) {
          textbox[0].value = textbox[0].value.substring(0, maxlength - difference);
        }
        return true;
      };
      current.change(function() { checkMaxLength($(this), maxlength); })
             .keypress(function() { checkMaxLength($(this), maxlength); })
             .blur(function() { checkMaxLength($(this), maxlength); })
             .submit(function() { checkMaxLength($(this), maxlength); });

      // Check now
      current.each(function() {
        checkMaxLength($(this), maxlength);
      });
    }
  };

  $.fn.popup = function(options) {
    var config = $.extend({
      mode: 'click',
      showMode: 'normal', // normal, outside
      alwaysRefresh: false,
      offset: {
        x: 0,
        y: 0
      },
      containment: '#abracadabra',
      container: {
        top: 0,
        left: 0,
        width: $(window).width(),
        height: $(window).height()
      },
      replaceTag: "a",
      replaceBy: "div",
      popupIdFunc: function(id) {
        return "#popup_"+id;
      },
      speedShow: 1000,
      speedHide: 500
    }, options || {});

    // only one container allowed
    if ($(config.containment).size() == 1) {
      config.container = {
        top: $(config.containment).offset().top,
        left: $(config.containment).offset().left,
        width: $(config.containment).width(),
        height: $(config.containment).height()
      };
    }

    var linkedPopups = $(this);
    var selected = $("#abracadabra");
    linkedPopups.each(function() {
      var current = $(this);
      var id = current.attr("id");
      if (config.replaceTag.indexOf(current.tag().toLowerCase()) > -1) {
        // Replace by div
        var replacement = $('<'+config.replaceBy+'>'+current.html()+'<'+config.replaceBy+'>');
        var attrs = new Array('title', 'alt', 'class');

        for(var i = 0; i < attrs.length; i++) {
          if (current.attr(attrs[i]) != '') {
            replacement.attr(attrs[i], current.attr(attrs[i]));
          }
        }
        current.replaceBy(replacement);
        current = replacement;
        current.attr('id', id);
      }
      var popupId = config.popupIdFunc(id);
      var popup = $(popupId);

      if (current.find(popupId).size() == 0) {
        current.append(popup);
      }
      popup.css({
        opacity: 0,
        position: "absolute"
      });

      var popupFunc = function(event) {
        try {
          if (selected === popup && !config.alwaysRefresh) {
            popup.stop();
            popup.show();
            popup.stop().animate({"opacity": 1}, config.speed);
          }
          else {
            popup.stop();

            var rect = {
              left: event.clientX + config.offset.x + $(window).scrollLeft(),
              top: event.clientY + config.offset.y + $(window).scrollTop(),
              width: popup.outerWidth(),
              height: popup.outerHeight()
            };

            switch(config.showMode) {
              case "outside":
              rect.left = (current.offset().left + current.width() + config.offset.x);
              rect.top = (current.offset().top + current.height() + config.offset.y);
              break;
            }

            var lb = {
              x: rect.left + rect.width,
              y: rect.top + rect.height
            };

            var lbMax = {
              x: config.container.left + config.container.width,
              y: config.container.top + config.container.height
            };

            if (lb.x > lbMax.x) {
              rect.left -= (rect.width + config.offset.x);
              switch(config.showMode) {
                case "outside":
                rect.left -= current.width() + config.offset.x;
                break;
              }
              if (rect.left < 0) {
                rect.left = config.offset.x;
              }
            }
            else if (config.container.left < rect.left) {
              rect.left += config.container.left + config.offset.x;
            };

            if (lb.y > lbMax.y) {
              rect.top -= (rect.height + config.offset.y);
              switch(config.showMode) {
                case "outside":
                rect.top -= current.height() + config.offset.y;
                break;
              }
            } else if (config.container.top < rect.top) {
              rect.top += config.container.top + config.offset.y;
            };

            selected.removeClass("selected").css({"opacity": 0}).hide();
            selected = popup;
            popup.addClass("selected");
            popup.css({
              left: rect.left,
              top: rect.top
            });
            popup.show();
            popup.stop().animate({"opacity": 1});
          }
        }
        catch (e) {
          alert(e);
        }
        return false;
      };

      var popoutFunc = function() {
        popup.stop().animate({"opacity": 0}, config.speedHide, function() {
          popup.hide();
        });
        return false;
      };

      // find close button
      popup.find(".sluitkruis a").click(popoutFunc);

      if (config.mode == 'hover') {
        current.hover(popupFunc, popoutFunc);
      }
      else {
        current.click(popupFunc);
      }
    });
  };

 /*
  Global functions down here
  */

 /*
  Preloads a set of images.
  Arguments: comma seperated list of image locations
  Usages: $.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");
  */
  $.preloadImages = function() {
    for(var i = 0; i<arguments.length; i++) {
      $("<img>").attr("src", arguments[i]);
    }
  };

 /*
  Parse input to int, on error returns number 0
  */
  $.parse2Int = function(input) {
      try {
        return parseInt(input.match(/[0-9]*/),10);
      }
      catch (e) {
        alert(e.message);
        return 0;
      }
    };

 /*
  Parse input to int, on error returns number 0
  */
  $.cleanUrl = function(url) {
      try {
        url = url.replace(/&amp;/g, "&");
        return url;
      }
      catch (e) {
        alert(e.message);
        return 0;
      }
    };

 /*
  Returns a random integer.
  */
  $.randomInt = function() {
      var args = arguments;
      var minValue = 0;
      var maxValue = 10;
      switch (args.length) {
        case 1:
          maxValue = args[0];
          break;
        default:
          minValue = args[0];
          maxValue = args[1];
          break;
      }
      var seed = maxValue - minValue;
      var random = Math.random();
      return Math.round((random * seed) + minValue);
    };

 /*
  Make a string of a object (cannot create that object again.).
  */
  $.toString = function(obj) {
      var retVal = "{";
      for (var field in obj) {
        if (typeof(fieldContents) != "function") {
          retVal += retVal != ("{" ? ","  : "") + field + ": " + obj[field];
        }
      }
      retVal += " }";
      return retVal;
    };

 /*
  Make a query string of a object (cannot create that object again.).
  */
  $.toQueryString = function(obj) {
      var retVal = "";
      for (var field in obj) {
        if (typeof(fieldContents) != "function") {
          retVal += (retVal != "" ? "&"  : "") + field + "=" + obj[field];
        }
      }
      return retVal;
    };

 /*
  Stop executing anything for a specified time.
  */
  $.pause = function(ms) {
      var date = new Date();
      curDate = null;
      do { var curDate = new Date(); }
      while ( curDate - date < ms);
    };

 /*
  Get and returns a upperleft corner coordinate based on given arguments to center child.
  */
  $.getCenterPoint = function(obj, context, mode) {
      if (!mode) {
        mode = "both"; // vertical, horizontal
      }

      var retObj = {
        viewport: {
          width: $(context).width(),
          height: $(context).height()
        },
        obj: {
          width: $(obj).width(),
          height: $(obj).height()
        }
      };
      var centerPoint = new Object();
      if (mode == "both" || mode == "horizontal") {
        centerPoint.left = (retObj.viewport.width - retObj.obj.width) / 2;
      }
      if (mode == "both" || mode == "vertical") {
        centerPoint.top = (retObj.viewport.height - retObj.obj.height) / 2;
      }

      return centerPoint;
    };

 /*
  Make an object with all variables for a js file
  */
  $.getScriptParams = function(filename) {

  };
 /*
  Creates of uses debugwindow to show debug info.
  Do not use in production environment
  */
  var __debugwindow;
  $.log = function(message) {
      if (!__debugwindow) {
        $("body").append('<div id="debugwindow"></div>');
        __debugwindow = $("body > #debugwindow");
        __debugwindow.css({
            position: "absolute",
            right: 20,
            top: 20,
            width: 250,
            height: 250,
            overflow: "hidden",
            border: "solid 3px black",
            "background-color": "#FFFFFF",
            "color": "#000000",
            "text-align": "left",
            "padding": 3,
            opacity: 0.7
          }
        ).click(
          function() {
            $(this).remove();
            __debugwindow = null;
          }
        );
      }

      __debugwindow.prepend('<div class="debugline">'+message+'</div>');
    };

  $.browser.name = function() {
    if ($.browser.msie) {
      return "ie";
    }
    else if ($.browser.mozilla) {
      return "mozilla";
    }
    else if ($.browser.opera) {
      return "opera";
    }
    else if ($.browser.safari) {
      return "safari";
    }
    else {
      return "unknown";
    }
  };
})(jQuery);

String.prototype.contains = function(find) {
  return this.indexOf(find) > -1;
};
