var wrFunction = {
  value: {
    pageErrors: new Array()
  },
  /*
    BLOCK
    Date and time-functions
  */

  isDate: function(dateStr){
    return wrFunction.validateDate(dateStr);
  },

  /**
   * Validate a date to se that it is a date (format 2011-04-16)
   * @param dateStr
   */
  validateDate: function(dateStr) {
    if(dateStr==""){
      return false;
    } else {
      var r = /^\d{4}-{1}\d{2}-{1}\d{2}$/
      return r.test(dateStr); // Returns true or false
    }
    return false;
   },

  /**
   * Compare two dates and check so that they're in a timeline
   * @param firstDate     First date (with format YYYY-MM-DD)
   * @param secondDate    Second date (with format YYYY-MM-DD)
   * @param minDiff       Minimum difference (in days) between dates, defaults to zero diff
   *
   * Difference in days is calculated with included start and stop-date. In other words "2011-01-01" to "2011-01-31"
   * equals a difference in 31 days
   */
  isTimeline: function(firstDate, secondDate, minDiff){
    var firstDateObj = new Date();
        firstDateObj.setFullYear(firstDate.substr(0,4), firstDate.substr(5,2), firstDate.substr(8,2));
    var secondDateObj = new Date();
        secondDateObj.setFullYear(secondDate.substr(0,4), secondDate.substr(5,2), secondDate.substr(8,2));

    if(firstDate > secondDate){
      // firstDate is later than secondDate, that's never allowed
      return false;
    }

    if(minDiff){
      if(((secondDateObj.getTime() - firstDateObj.getTime())/(1000*60*60*24)+1) < minDiff){
        return false;
      } else {
        return true;
      }
    } else {
      return true;
    }
  },

  /*
    BLOCK
    Validations
   */

  /**
   * Takes a string and test if it only contains number
   * @param str
   */
  isInteger: function(str){
    if(str==""){
      return false;
    } else {
      var r = /^\d+$/
      return r.test(str); // Returns true or false
    }
    return false;
  },

  /**
   * Validate a string to see that it's an e-mail-address
   * @param email
   */
  validateEmail: function(email){
     var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
     if(reg.test(email) == false) {
        return false;
     } else {
       return true;
     }
  },

  validateBox: function(boxID, passedValidation, hasWarning){
    if(passedValidation){
      if(hasWarning){
        wrFunction.setIndicator(boxID, 'warning');
      } else {
        wrFunction.setIndicator(boxID, 'ok');
      }
      return true;
    } else {
      wrFunction.setIndicator(boxID, 'error');
      return false;
    }
  },

  /*
    BLOCK
    String modifiers and stuff like that
   */

  /**
   * Takes 'str' and tries to remove from beginning of string what's in 'removeBefore', then tries to do the same from the
   * end of the string with 'removeAfter'.
   * @param str
   * @param removeBefore
   * @param removeAfter
   *
   * @Todo Make more smart with actual test that it is from beginning and from end of string...
   */
  filterString: function(str, removeBefore, removeAfter){
    if(removeBefore){
      str = str.replace(removeBefore, '');
    }

    if(removeAfter){
      str = str.replace(removeAfter, '');
    }

    return str;
  },

  /**
   * Adjust string to functional filename or path
   * @param filename
   */
  toFilename: function(filename){
    return wrFunction.processString(filename);
  },

  toVar: function(key){
    var modifiedKey = wrFunction.processString(key);

    //For variables, we can't have the following signs
    modifiedKey = wrFunction.toCamelCase(modifiedKey);

    return modifiedKey;
  },

  toUsername: function(key){
    var modifiedKey = wrFunction.processString(key);

    //For variables, we can't have the following signs
    modifiedKey = modifiedKey.replace(/-/g, ".");
    modifiedKey = modifiedKey.toLowerCase();

    return modifiedKey;
  },

  processString: function(str, allowed){
    str = str.replace(/!/g, "");
    str = str.replace(/"/g, "");
    str = str.replace(/#/g, "nr-");
    str = str.replace(/\$/g, "");
    str = str.replace(/%/g, "");
    str = str.replace(/&/g, "och");
    str = str.replace(/'/g, "");
    str = str.replace(/\(/g, "");
    str = str.replace(/\)/g, "");
    str = str.replace(/\*/g, "");
    str = str.replace(/\+/g, "plus");
    str = str.replace(/,/g, "-");
    str = str.replace(/\./g, "-");
    str = str.replace(/\//g, "-");
    str = str.replace(/:/g, "");
    str = str.replace(/;/g, "");
    str = str.replace(/</g, "");
    str = str.replace(/=/g, "-");
    str = str.replace(/>/g, "");
    str = str.replace(/\?/g, "");
    str = str.replace(/@/g, "-at-");
    str = str.replace(/\[/g, "");
    str = str.replace(/\\/g, "");
    str = str.replace(/\]/g, "");
    str = str.replace(/\^/g, "");
    str = str.replace(/`/g, "");
    str = str.replace(/{/g, "");
    str = str.replace(/\|/g, "-");
    str = str.replace(/}/g, "");
    str = str.replace(/~/g, "-");
    //Extended latin
    str = str.replace(/€/g, "euro");
    str = str.replace(/‘/g, "");
    str = str.replace(/’/g, "");
    str = str.replace(/“/g, "");
    str = str.replace(/”/g, "");
    str = str.replace(/•/g, "-");
    str = str.replace(/—/g, "-");
    str = str.replace(/§/g, "paragraf");

    //Letters
    //Uppercase
    str = str.replace(/À/g, "A");
    str = str.replace(/Á/g, "A");
    str = str.replace(/Â/g, "A");
    str = str.replace(/Ã/g, "A");
    str = str.replace(/Ä/g, "A");
    str = str.replace(/Å/g, "A");
    str = str.replace(/Æ/g, "AE");
    str = str.replace(/Ç/g, "C");
    str = str.replace(/È/g, "E");
    str = str.replace(/É/g, "E");
    str = str.replace(/Ê/g, "E");
    str = str.replace(/Ë/g, "E");
    str = str.replace(/Ì/g, "I");
    str = str.replace(/Í/g, "I");
    str = str.replace(/Î/g, "I");
    str = str.replace(/Ï/g, "I");
    str = str.replace(/Ñ/g, "N");
    str = str.replace(/Ò/g, "O");
    str = str.replace(/Ó/g, "O");
    str = str.replace(/Ô/g, "O");
    str = str.replace(/Õ/g, "O");
    str = str.replace(/Ö/g, "O");
    str = str.replace(/Ø/g, "O");
    str = str.replace(/Ù/g, "U");
    str = str.replace(/Ú/g, "U");
    str = str.replace(/Û/g, "U");
    str = str.replace(/Ü/g, "U");
    str = str.replace(/Ý/g, "Y");
    //Lowercase
    str = str.replace(/à/g, "a");
    str = str.replace(/á/g, "a");
    str = str.replace(/â/g, "a");
    str = str.replace(/ã/g, "a");
    str = str.replace(/ä/g, "a");
    str = str.replace(/å/g, "a");
    str = str.replace(/æ/g, "ae");
    str = str.replace(/ç/g, "c");
    str = str.replace(/è/g, "e");
    str = str.replace(/é/g, "e");
    str = str.replace(/ê/g, "e");
    str = str.replace(/ë/g, "e");
    str = str.replace(/ì/g, "i");
    str = str.replace(/í/g, "i");
    str = str.replace(/î/g, "i");
    str = str.replace(/ï/g, "i");
    str = str.replace(/ñ/g, "n");
    str = str.replace(/ò/g, "o");
    str = str.replace(/ó/g, "o");
    str = str.replace(/ô/g, "o");
    str = str.replace(/õ/g, "o");
    str = str.replace(/ö/g, "o");
    str = str.replace(/ø/g, "o");
    str = str.replace(/ù/g, "u");
    str = str.replace(/ú/g, "u");
    str = str.replace(/ü/g, "u");
    str = str.replace(/ý/g, "y");
    str = str.replace(/ÿ/g, "y");

    str = str.replace(/ /g, "-");
    str = str.replace(/…/g, "");
    str = str.replace(/---/g, "-"); //There's a difference between this and the next line, keep intact!
    str = str.replace(/-–-/g, "-"); //See note one line up!
    str = str.replace(/--/g, "-");

    if(str.substr(str.length-1) == '-'){
      str = str.substr(0, str.length-1);
    }

    return str;
  },

  /**
   * Takes a string (probably a variablename) and turns it into camelCase
   * Example: this-is-an-example -> thisIsAnExample
   * @param str
   */
  toCamelCase: function(str){
      return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
    },

    isInArray: function(array, findMe){
    if(typeof(array) == 'array'){
      var i;
      var isFound = false;
      for(i in array){
        if(array[i] == findMe){
          isFound = true;
        }
      }
    } else {
      return false;
    }

    return isFound;
  },

  /**
   * Trying to take the string and make it a valid birthday
   */
  toBirthday: function(str){
    // To make it easier to format the birthday, remove '-' and ' '
    str = str.replace(/-/g, "");
    str = str.replace(/ /g, "");

    // Use current year to compare with birthday
    thisYear = wrDate.makeDate(false, 'getFullYear');

    // Since this is a birthday as a date, add the century if needed
    if(str.length == 10 || str.length == 6){
      if(parseInt('20' + str.substr(0,2)) > parseInt(thisYear)){
        str = '19' + str;
      } else {
        str = '20' + str;
      }
    }

    // Format it correctly
    str = str.substr(0,4) + '-' + str.substr(4,2) + '-' + str.substr(6,2);

    return str;
  },

  toFilesize: function(filesize){
    filesize = parseInt(filesize);
    niceFilesize = 0.0;
    if(filesize >= 1099511627776){
      // It's at least one terabyte
      return wrFunction.toNumberFormat(filesize / 1099511627776, 2, ' ', ',') + ' TB';
    } else if(filesize >= 1073741824){
      // It's at least a gigabyte
      return wrFunction.toNumberFormat(filesize / 1073741824, 2, ' ', ',') + ' GB';
    } else if(filesize >= 1048576){
      // It's at least one megabyte
      return wrFunction.toNumberFormat(filesize / 1048576, 2, ' ', ',') + ' MB';
    } else if(filesize >= 1024){
      // It's at least one kilobyte
      return wrFunction.toNumberFormat(filesize / 1024, 2, ' ', ',') + ' KB';
    } else {
      // It's just counted in bytes
      return wrFunction.toNumberFormat(filesize, 2, ' ', ',') + ' bytes';
    }
  },

  /**
   * @param number              The number to format
   * @param decimal             Number of decimals
   * @param thousandSign        Thousands separator
   * @param decimalSign         The decimal point, for example ','
   * @param prepend             label before number, add whitespace if wanted
   * @param append              label after number, add whitespace if wanted
   */
  toNumberFormat: function(number,decimal,thousandSign,decimalSign,prepend,append){
    if(!decimal){
      decimal = 2;
    }
    if(!thousandSign){
      thousandSign = ' ';
    }
    if(!decimalSign){
      decimalSign = ',';
    }
    if(!prepend){
      prepend = '';
    }
    if(!append){
      append = '';
    }
    srcNumber = parseFloat(number);

    number += ''; // Make it to string
    x = number.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? x[1] : '';
    if(x2.length < decimal){
      x2 = wrFunction.pad(x2, decimal);
    }
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + thousandSign + '$2');
    }

    return prepend + x1 + decimalSign + x2.substr(0,decimal) + append;
  },

  /**
   * Trying to take the string and make it a valid social securitynumber
   */
  toSocialSecurityNr: function(str, withLastFour){
    // To make it easier to format the birthday, remove '-' and ' '
    str = str.replace(/-/g, "");
    str = str.replace(/ /g, "");

    thisYear = wrDate.makeDate(false, 'getFullYear');

    if(str.substr(0,2) == '19' || str.substr(0,2) == '20'){
      str = str.substr(2);
    }

    if(str.length == 10){
      str = str.substr(0,6) + '-' + str.substr(6);
    }

    return str;
  },

  pad: function(str, length){
    //Make sure it's a string (converts it otherwise)
    var str = new String(str);
    //If lenght is not given, set it to default value
    if(!length){
      length = 2;
    }

    //Pad on!
    while (str.length < length) {
        str = '0' + str;
    }

    return str;
  },

  processDecimal: function(float){
    str = float + '';
    str = str.replace(',', '.');
    if(str.indexOf('.') > 0){
      decimal = parseInt(str.substr(str.indexOf('.') + 1));
      if(decimal < 1){
        return parseFloat(str.substr(0, str.indexOf('.')));
      } else {
        return parseFloat(str);
      }
    } else {
      return parseFloat(float);
    }

    return parseFloat(float);
  },

  /*
    BLOCK
    Error-handling
   */
  addError: function(key, error, solution){
    var thisError = new Object();
        thisError.error = error;
        thisError.solution = solution;

    if(!wrFunction.value.pageErrors.hasOwnProperty(key)){
      wrFunction.value.pageErrors[key] = new Array();
    }

    wrFunction.value.pageErrors[key].push(thisError);

    return true;
  },

  clearError: function(key){
    try {
      delete(wrFunction.value.pageErrors[key]);
    } catch(errno){

    }


    return true;
  },

  getErrors: function(key){
    if(wrFunction.value.pageErrors.hasOwnProperty(key)){
      var $errorList = $('<dl>');

      var i;
      for(i in wrFunction.value.pageErrors[key]){
        var $errorItemError = $('<dt>');
            $errorItemError.html(wrFunction.value.pageErrors[key][i].error);
            $errorList.append($errorItemError);
        var $errorItemSolution = $('<dd>');
            $errorItemSolution.html(wrFunction.value.pageErrors[key][i].solution);
            $errorList.append($errorItemSolution);
      }

      return $errorList;
    } else {
      return false;
    }
  },

  /*
    BLOCK
    Update Box Indicator
   */
  setIndicator: function(boxID, value){
    var fadeDuration = 750;
    switch(value){
      case 'green':
      case 'ok':
        $('#' + boxID + ' .indicator').animate({
          backgroundColor: '#96c700'
        }, fadeDuration);
      break;
      case 'yellow':
      case 'warning':
        $('#' + boxID + ' .indicator').animate({
          backgroundColor: '#f4cc14'
        }, fadeDuration);
      break;
      case 'red':
      case 'error':
        $('#' + boxID + ' .indicator').animate({
          backgroundColor: '#d31717'
        }, fadeDuration);
      break;
      case 'blue':
      case 'neutral':
        $('#' + boxID + ' .indicator').animate({
          backgroundColor: '#5f83b9'
        }, fadeDuration);
      break;
      default:
        $('#' + boxID + ' .indicator').animate({
          backgroundColor: '#' + value
        }, fadeDuration);
      break;
    }
  },

  /*
    BLOCK
    Forms and stuff
   */
  niceCornerJQueryUI: function($wrapper){
    var i = 0;
    var tmpTopPosition = 0;
    $wrapper.find('label.ui-button').each(function(){
      if(i > 0){
        /*if($(this).prev().position().top < $(this).position().top){
          console.log(i + '. ' + $(this).prev().text() + ': ' + $(this).prev().position().top + ' vs ' + $(this).text() + ' ' + $(this).position().top);
          $(this).prev().addClass('ui-corner-right');
          $(this).addClass('ui-corner-left');

        }*/
        /*if(tmpTopPosition < $(this).position().top){
          console.log(i + '. ' + $(this).prev().text() + ': ' + $(this).prev().position().top + ' vs ' + $(this).text() + ' ' + $(this).position().top);
          $(this).prev().addClass('ui-corner-right');
          $(this).addClass('ui-corner-left');
        }*/
        if($(this).position().top < $(this).next().position().top){
          console.log(i + '. ' + $(this).prev().text() + ': ' + $(this).prev().position().top + ' vs ' + $(this).text() + ' ' + $(this).position().top);
          //$(this).prev().addClass('ui-corner-right');
          //$(this).addClass('ui-corner-left');
        }
      }
      tmpTopPosition = $(this).position().top;
      i++;
    });
  }
}
