/**
  * Helper functions which might make our life less miserable.  These are prototype functions added to the already well established String Object
  * author: ICF
  *
  */




//################### EXTENDS FUNCTION ####################################

/**
  * key function used to extend the functionaly of a new class with the functionality of a an existing class
  * param: sub - object representing the subtype which is ready to inherit from the super class
  * param: sup - object representing the supertype which will inherit its functions/methods to its subtype, sub
  */
function extend( subClass, superClass ) {
  //alert("sub: " + subClass + "\nsuper: " + superClass );
  var obj = function() {};
  obj.prototype = superClass.prototype;
  //--------_ _--------_ _--------_ _--------_ _--------_ _--------_ _--------_ _
  //-----_ _------------_ _
  subClass.prototype = new obj();
  subClass.prototype.constructor = subClass;
  subClass.baseConstructor = superClass;
  subClass.superclass = superClass.prototype;
}



function extend2( subClass, superClass ) {
  var obj = function() {};
  obj.prototype = superClass.prototype;

  //subClass.prototype = new obj();

  var obj2 = new obj();
  obj2.prototype = superClass.prototype;
  for( x in obj2.prototype ) {
    subClass.prototype[x] = obj2.prototype[x];
  }
  subClass.prototype.constructor = subClass;
  subClass.baseConstructor = superClass;
  subClass.superclass = superClass.prototype;
}







//################### EVENTS FUNCTIONS ####################################











//################### STRING FUNCTIONS ####################################



String.prototype.getFInt = function() {
  var str = this.toString();
  if( str == "" || str == null )
    return 0;

  var ans = str.getInt();
  var res= ans[0];
  return parseInt( res );
}




String.prototype.getInts = function() {
  var str = this.toString();
  if( str == "" || str == null )
    return 0;
  var ans = str.getInt();
  //alert("Current ans: " + ans );
  var res = ans.join( "" );
  return parseInt( res );
}


/**
  * Similar to parseInt, but this one returns the number from a string, it doesn't just turn a string into a number.  Actually it uses parseInt
  * to returnthe final result
  */
String.prototype.getInt = function() {
  var str = this.toString();
  var ans = new Array();
  if( str != "" || str != null ) {
    var intExp = /[+-]?[0-9]+/;
    var test = str.match( intExp );
    for( i in test )
      ans.push( parseInt(test[i]) );
    return ans;
  }
  else
    ans;
}





String.prototype.trim = function() {
  var str = this.valueOf();
  if( str != null ) {
    var trimmer = /^[\s\n\t\f]+|[\s\n\t\f]+$/;
    var res = str.replace( trimmer, "" );
    res = res.replace( trimmer, "" );
    ///alert('Trimmed input: _' + res + '_' );
    return res;
  }
  else
    return "";
}





String.prototype.trimAll = function() {
  var str = this.valueOf();
  if( str != null ) {
    str = str.trim();
    var trimmer = /[\s\n\t\f]+(?=\w)|[\s\n\t\f]{2,}/gi;
    var res = str.trim();
    //var matches = str.match( trimmer );
    //alert("Trimmed input: _" + res + "_" );
    res = str.replace( trimmer, " " );
    //alert("Trimmed input: _" + res + "_" );
    res = res.trim();
    return res;
  }
  else
    return "";
}







/**
  * tokenize:
  */
String.prototype.tokenize = function( delim, mods ) {
  var str = this.valueOf();
  if( mods == null )
    mods = "gi";

  var tokenizer = new RegExp( delim, mods );
  tokenizer.compile(tokenizer);
  str = str.trim();
  str = str.trimAll();
  var array = str.split( tokenizer );
  var ans = new Array();
  for( var x = 0; x < array.length; x++ ) {
    var temp = array[x];
    var spaces = /^[\s\n\f\t]+$/gi;
    if( temp == "" || temp == "undefined" || temp == null || temp.match( spaces  ) ) {
      continue;
    }
    else
      ans.push( temp.trim() );
  }
  return ans;
}




/**
  * returns a node with class 'className' within this node

Object.prototype.classNode = function( className ) {
  ch = this.childNodes;
  nodes = new Array();

  for( x in ch ) {
    tmp = ch[x];
    if( tmp.nodeType == 1 && (tmp.className != "" || tmp.className != null )) {
      classes = (tmp.className).tokenize( ",", "gi" );
      for( i in classes ) {
        aClass = "ivan";//classes[i].trim();
        if( className == aClass ){
          nodes.push( x );
          break;
        }//end of innermost if-statement
      }//end of inner loop
    }//end of outer if-statement
  }//end of outer loop
  return nodes;
}
*/




/**
  * useful function used to return an element with a given class.  The element is searched for within the given element
  */
function getByClass( src, clss ) {
  ch = src.childNodes;
  nodes = new Array();
  for( x in ch ) {
    tmp = ch[x];
    if( tmp.nodeType == 1 && (tmp.className != "" || tmp.className != null )) {
      classes = (tmp.className).tokenize( " ", "gi" );
      //alert("classes for this child: " + classes );
      for( var i = 0; i < classes.length; i++ ) {
        aClass = classes[i].trim();
        //alert("Input: " + clss + "\nCurrent class: " + aClass );
        //alert("Are classname and input equal: " + (clss == aClass) );
        if( clss == aClass ){
          nodes.push( ch[x] );
          break;
        }//end of innermost if-statement
      }//end of inner loop
    }//end of outer if-statement
  }//end of outer loop
  return nodes;
}














/**
  * nodeDim: returns information about the dimensions of a given HTML element
  */
function nodeDim( node ) {
  if( node.nodeType ) {
    ans = new Object();

    //total height with borders and padding, no margin
    oH = node.offsetHeight;
    oW = node.offsetWidth;

    //viewable height with no padding/border or scrollbars
    cH = node.clientHeight;
    cW = node.clientWidth;


    mT = node.style.marginTop;
    mB = node.style.marginBottom;
    mL = node.style.marginLeft;
    mR = node.style.marginRight;


    //border size
    bB = node.style.borderBottomWidth;
    bT = node.style.borderTopWidth;
    bL = node.style.borderLeftWidth;
    bR = node.style.borderRightWidth;

    pT = node.style.paddingTop;
    pB = node.style.paddingBottom;
    pL = node.style.paddingLeft;
    pR = node.style.paddingRight;

    ans.pH = cH + pT.getFInt() + pB.getFInt();
    ans.pW = cW + pL.getFInt() + pR.getFInt();

    //viewable height
    ans.vH = cH; //+ mT.getFInt() + mB.getFInt() + pT.getFInt() + pB.getFInt();
    ans.vW = cW; // + mT.getFInt() + mB.getFInt() + pT.getFInt() + pB.getFInt();

    //total height
    ans.tH = oH + mT.getFInt() + mB.getFInt();
    ans.tW = oW + mL.getFInt() + mR.getFInt();

    return ans;
  }
  else {
    return null;
  }
}



/**
  * randomNum: produces a random number in between the provided range
  * param: min - integer representing the minimum value that can be calculated
  * param: max - integer representing the maximum value that can be calculated
  * returns: an integer chosen at random, from within the provided range
  */
function randomNum( min, max ) {
  if( min > max ) {
    throw( "Min must be smaller than max\nInput[min]: " + min + "\nInput[max]: " + max );
  }
  range = Math.abs(max) + Math.abs( min );
  num = Math.round(Math.random()*(range) + min);
  return num;
}














/**
  * addPs: adds a paragraph to the buttons parent
  */
function addPs( inp ) {
  txts = new Array();
  var t1 = document.createTextNode("Lorem ipsum dolor sit amet, consectetur adipiscing elit. In mattis bibendum dolor nec sollicitudin. Proin quis diam nisi, sed pulvinar ante. Nulla eu dolor id urna interdum gravida in sagittis leo. Nunc adipiscing erat et neque congue lobortis. Donec convallis leo consequat turpis sodales tempor. Quisque pretium consectetur sem in vestibulum. Suspendisse potenti. Nulla id nibh eu leo molestie faucibus ut ac odio. Proin ornare mauris velit, in lobortis augue. Etiam tortor ligula, ullamcorper eu ornare et, ultricies vel nisl. Suspendisse nec lorem sed felis interdum fringilla non sit amet nisl. Vivamus ut aliquam mauris.");

  var t2 = document.createTextNode( "Proin lacinia sodales fringilla. Maecenas erat enim, adipiscing non varius ac, tempor eget nulla. Mauris eleifend urna ornare felis rhoncus ut lacinia erat congue. Donec a tortor nec orci porta aliquam vel eget lorem. Nulla cursus luctus quam vel auctor. Praesent tristique libero et est tempor interdum. Quisque consectetur odio nec erat mattis posuere. Aenean ullamcorper, tellus quis porttitor rutrum, tellus leo gravida justo, ut porta nulla magna vitae nisl. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis facilisis ligula sed turpis hendrerit ullamcorper. Sed vel ante ac dui viverra aliquam. Integer nulla elit, adipiscing sit amet commodo sed, eleifend a odio. Sed ac velit ante. Aliquam erat volutpat. Maecenas tortor eros, luctus sed ornare ullamcorper, lacinia id turpis. Curabitur eget vestibulum elit. Phasellus at urna sed eros pharetra consectetur sit amet sed augue.");

  var t3 = document.createTextNode( "Cras dapibus sollicitudin tellus, sit amet congue quam porttitor accumsan. Phasellus in tellus tellus, quis sagittis erat. Suspendisse sem erat, condimentum at lobortis eget, condimentum quis nulla. Nam vehicula odio ut risus sollicitudin tristique. Proin congue, justo sed faucibus dictum, quam tellus eleifend augue, ut vestibulum tortor purus eget elit. In volutpat, purus convallis dignissim consequat, risus eros volutpat lorem, et eleifend ipsum nulla vel odio. Phasellus blandit risus ac libero ultrices vel sodales mi vehicula. Pellentesque magna orci, sodales sit amet laoreet sit amet, blandit eu odio. Aliquam elementum, nisi sit amet aliquet suscipit, leo justo interdum turpis, vel consectetur neque libero sed neque. Nulla aliquet, odio aliquam elementum consequat, nibh sapien aliquet nisi, vel varius metus mi sit amet velit. Fusce fringilla massa blandit dolor fermentum tristique. Integer aliquam mattis dolor ac congue. Sed pharetra volutpat ipsum, nec scelerisque magna ultrices in. Nam molestie mollis tellus ut porta. Vestibulum velit orci, ultrices eu dignissim eget, scelerisque eget arcu. Nullam sem enim, tempus ut vestibulum sed, pharetra non massa. Nam tristique lorem sit amet enim tincidunt quis consequat magna interdum. Nam sed dolor erat, et ultricies urna.");

  var t4 = document.createTextNode("Duis justo turpis, mattis id rutrum eget, tincidunt vitae massa. Nunc imperdiet varius diam, et feugiat leo ullamcorper ac. Nunc dolor est, tempus quis venenatis nec, tempor eu tellus. Morbi odio enim, lacinia quis molestie quis, pharetra quis tortor. Vestibulum a sapien nec purus pretium dictum porttitor vitae enim. Donec eu dui erat. Integer rutrum odio et quam elementum sodales fermentum risus pharetra. Donec in ligula lectus, et lacinia leo. Aenean feugiat turpis eu neque dignissim sollicitudin. Aliquam non elementum justo. Integer malesuada interdum risus et ullamcorper. Aliquam erat volutpat. In ultrices pharetra nunc faucibus accumsan. Nunc massa ante, egestas at eleifend ac, placerat porta neque. Nulla fringilla, erat id fringilla faucibus, lorem nisl ornare augue, sed dignissim neque lacus et nunc. Morbi rhoncus hendrerit massa, vitae condimentum urna auctor eget. In hac habitasse platea dictumst. Duis sodales sodales auctor. Aenean ante purus, consectetur ac imperdiet eget, mollis aliquam nisl. Sed leo leo, pellentesque laoreet semper id, dapibus quis ante.");

  var t5 = document.createTextNode( "Nam mi velit, hendrerit et malesuada sed, feugiat non quam. Maecenas condimentum, quam vitae bibendum egestas, tellus lectus feugiat nunc, vitae vestibulum odio velit at augue. Phasellus porttitor tempus libero. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean non neque elit. Nulla scelerisque, tortor ut aliquet iaculis, ligula purus posuere dolor, ac condimentum lorem orci ut nisi. Aenean sem sapien, sagittis vitae ultrices quis, tempus id velit. Duis vitae lectus nisi, quis molestie purus. Morbi eget dui sit amet nunc bibendum consectetur. Praesent est dolor, laoreet in eleifend ut, tempor ut eros. Sed turpis lectus, sodales ut iaculis ut, tempus eget augue. Nullam commodo molestie adipiscing. Duis ultrices ultrices felis, sit amet tristique arcu pretium eget. Suspendisse potenti. In a quam lectus, a ullamcorper ipsum.");



txts.push( t1 );
txts.push( t2 );
txts.push( t3 );
txts.push( t4 );
txts.push( t5 );


//rn = Math.round( Math.random()*(txts.length-1) );
rp = txts[randomNum( 0, (txts.length-1)) ];


 var par = inp.offsetParent;
 var p = document.createElement( 'p' );
 //p.appendChild( document.createTextNode( "this a test paragraph" ) );
 p.appendChild( rp );
 par.appendChild( p );
}



/**
  * getCSSRule: returns the specified rule from the given HTMLElement
  * param: elem - HTMLElement which will be queried about its css rules
  * param: rule - string representing the name of a CSS rule.  E.g. widht, height, border, etc
  */
function getCSSRule( elem, rule ) {
  if( elem != null ) {
    if( elem.currenStyle && elem.currenStyle[rule] )
      return elem.currentStyle[rule];
    else if( window.getComputedStyle && window.getComputedStyle( elem, null ) ) {
      tmp = window.getComputedStyle( elem, null);
      return tmp[rule];
    }
    else {
      return null;
    }
  }
  else
    return null;
}






Array.prototype.findIndex = function( id ) {
  if( this.indexOf ) {
    return this.indexOf( id );
  }
  else {
    //alert("using the one I defined");
    for( var i = 0; i < this.length; i++ ) {
      if( this[i] == id )
        return i;
    }
    return -1;
  }
}

  function setFontSize(size) {
    document.body.style.fontSize = size;
  }

  function setCopyrightYear( y1 ) {
    var date = new Date()
    var currYear = date.getFullYear();
    if( y1 != null && y1 < currYear )
      return " " + y1 + ", " + currYear + " ";
    else
      return " " + currYear + " ";
  }








