﻿(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() {
      $(this).each(function(i) {
        var jBlock=$(this);
        var text = jBlock.text();
        jBlock.attr("title", text);
        if (!text) { return; }

        var jSpan = $("span", jBlock);
        if (!jSpan.length) {
          jBlock.wrapInner(document.createElement("span"));
          jSpan = $("span", jBlock);
        }

        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);
  }

 /*
  Function description here
  */
  $.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;
    }
  };

 /*
  Global functions down here
  */
  
 /*
  Parse input to int, on error returns number 0
  */
  $.parse2Int = function(input) {
      try {
        return parseInt(input.match(/[0-9]*/));
      }
      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;
}
