﻿/* event Listening */
function AddListener(Elt, EventName, functionName) {
    if (Elt.addEventListener) { Elt.addEventListener(EventName, functionName, false); }
    else if (window.attachEvent) { Elt.attachEvent("on" + EventName, functionName); }
} //function addListener

/* tools from http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have

//######################################################################################
/* trim */
String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
   return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
   return this.replace(/\s+$/g,"");
}
/* usage 
var test = "   Test   ";
var test1 = test.ltrim();   // returns "Test   "
var test2 = test.rtrim();   // returns "   Test"
var test3 = test.trim();    // returns "Test"
*/
//######################################################################################
/* NumericSort */
Array.prototype.sortNum = function() {
   return this.sort( function (a,b) { return a-b; } );
}
/* usage 
var tmp = [5,9,12,18,56,1,10,42,30,7,97,53,33,35,27];
    tmp=tmp.sortNum(); // returns 1,5,7,9,10,12,18,27,30,33,35,42,53,56,97 
*/
//######################################################################################
/*Formatting Numbers*/
function formatNumber(num,prefix){
   prefix = prefix || '';
   num += '';
   var splitStr = num.split('.');
   var splitLeft = splitStr[0];
   var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
   var regx = /(\d+)(\d{3})/;
   while (regx.test(splitLeft)) {
      splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
   }
   return prefix + splitLeft + splitRight;
}

function unformatNumber(num) {
   return num.replace(/([^0-9\.\-])/g,'')*1;
}
/* usage
var test1 = formatNumber('5123456789.25'); // returns 5,123,456,789.25
var test2 = formatNumber(1234.15,'$');     // returns $1,234.15
var test3 = unformatNumber('$1,234.15');   // returns 1234.15
*/
//######################################################################################
/*Search an Array*/
Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}
/* usage
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
//         0/1/2 /3 /4/5 /6 /7     /8  /9/10/11/12/13/14/15/16/17/  18/    19/      20
var thirty=tmp.find(30);             // Returns 9, 14, 17
var thirtyfive=tmp.find('35');       // Returns 18
var thirtyfive=tmp.find(35);         // Returns 15
var haveBlue=tmp.find('blue');       // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/);          // returns 8,20    (first letter starts with b)
var regexp1=tmp.find(/^b/i);         // returns 8,19,20 (same as above but ignore case)
*/

//######################################################################################
/*HTML Entities*/
String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};
String.prototype.stripTags = function () {
   return this.replace(/<([^>]+)>/g,'');
}
/* usage
var tmp = '<html><head></head>';
var safe= tmp.htmlEntities(); // Returns &lt;html&gt;&lt;head&gt;&lt;/head&gt;
var tmp = '<a href="htpp://somespammer.com">Some Link</a>';
var safe= tmp.stripTags(); // Returns Some Link;
*/

//######################################################################################
/*Is it an object, or is it an Array?*/
//Object.prototype.isArray = function() {
//   return this.constructor == Array;
//}
/* usage
alert( [].isArray() ); // true
alert( {}.isArray() ); // false
*/

//######################################################################################
/*Cookies!*/
function cookiesAllowed() {
   setCookie('checkCookie', 'test', 1);
   if (getCookie('checkCookie')) {
      deleteCookie('checkCookie');
      return true;
   }
   return false;
}

function setCookie(name,value,expires, options) {
   if (options===undefined) { options = {}; }
   if ( expires ) {
      var expires_date = new Date();
      expires_date.setDate(expires_date.getDate() + expires)
   }
   document.cookie = name+'='+escape( value ) +
      ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + 
      ( ( options.path ) ? ';path=' + options.path : '' ) +
      ( ( options.domain ) ? ';domain=' + options.domain : '' ) +
      ( ( options.secure ) ? ';secure' : '' );
}

function getCookie( name ) {
   var start = document.cookie.indexOf( name + "=" );
   var len = start + name.length + 1;
   if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
      return null;
   }
   if ( start == -1 ) return null;
   var end = document.cookie.indexOf( ';', len );
   if ( end == -1 ) end = document.cookie.length;
   return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ){ 
        document.cookie = name + '=' +
        ( ( path ) ? ';path=' + path : '') +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    }
}      
/* usage
// Check if cookies are allowed in this browser.
if cookiesAllowed() { 
  alert('you can set cookies');
} else {
  alert("This browser doesn't allow cookies.");
}
// Create a cookie named myCookie with a value of 'Peanut Butter'
// The cookie will expire in 10 days.
setCookie('myCookie','Peanut Butter', 10);

// Retreive the value of 'myCookie'
var userCookie = getCookie('myCookie');

// Delete 'myCookie'
deleteCookie('myCookie');  
*/

//######################################################################################
/*Function Mapping*/
Array.prototype.map = function(f) {
  var returnArray=[];
  for (i=0; i<this.length; i++) {
    returnArray.push(f(this[i]));
  }
  return returnArray;
}
/* usage
function trim(str) {
  return str.replace(/^\s+|\s+$/g,'');
}

var tmp = ['now', 'is', '   the   ', 'time    ', '    for ',  ' all', ' good ', '   men   '];
var test = tmp.map(trim);  // returns now,is,the,time,for,all,good,me
*/

//######################################################################################
/*Controling Stylesheets*/
function getCSSRule(ruleName, deleteFlag) {
   ruleName=ruleName.toLowerCase(); 
   if (document.styleSheets) {      
      for (var i=0; i<document.styleSheets.length; i++) { 
         var styleSheet=document.styleSheets[i];
         var ii=0;                              
         var cssRule=false;                      
         do {                                   
            if (styleSheet.cssRules) {          
               cssRule = styleSheet.cssRules[ii];
            } else {                             
               cssRule = styleSheet.rules[ii];    
            }                                    
            if (cssRule)  {                      
               if (cssRule.selectorText.toLowerCase()==ruleName) { 
                  if (deleteFlag=='delete') {    
                     if (styleSheet.cssRules) {  
                        styleSheet.deleteRule(ii);
                     } else {                     
                        styleSheet.removeRule(ii);
                     }                            
                     return true;                 
                  } else {                        
                     return cssRule;              
                  }                               
               }                                  
            }                                     
            ii++;                                 
         } while (cssRule)                        
      }                                           
   }                                              
   return false;                                  
}                                                  

function killCSSRule(ruleName) {     
  return getCSSRule(ruleName,'delete');  
}                                         

function addCSSRule(ruleName) {       
  if (document.styleSheets) {        
    if (!getCSSRule(ruleName)) {    
      if (document.styleSheets[0].addRule) {       
        document.styleSheets[0].addRule(ruleName, null,0);
      } else {                   
        document.styleSheets[0].insertRule(ruleName+' { }', 0);
      }        
    }           
  }              
  return getCSSRule(ruleName);   
} 
/* usage
// returns the object for the CSS class "fancyStyle"      
fancyStyleObject=getCSSRule('fancyStyle');
// applies underline to the fancyStyle class. 
fancyStyleObject.style.textDecoration='underline'

// Deletes the class "fancyStyle" unstyling any objects that used it. 
killCSSRule('fancyStyle');

// Creates a new stylesheet rule (P for paragraphs in this instance)
newStyle=addCSSRule('p');
// Gives all paragraphs blue text.
newStyle.style.color='blue';

// creates a new CSS class called fancyStyle.
newStyle=addCSSRule('.fancyStyle');
// Gives all objects with a class of fancyStyle a green background.  
newStyle.backgroundColor='green';
*/

//######################################################################################
/*getElementsByClassName*/
//Object.prototype.getElementsByClass = function (searchClass, tag) {      
//   var returnArray = [];
//   tag = tag || '*';
//   var els = this.getElementsByTagName(tag);
//   var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
//   for (var i = 0; i < els.length; i++) {
//      if ( pattern.test(els[i].className) ) {
//         returnArray.push(els[i]);
//      }
//   }
//   return returnArray;
//}
/* usage
// returns all objects with a class name of "fancyStyle"
els=document.getElementsByClass('fancyStyle');
// returns all the objects with a class name of "fancyStyle" for paragraphs
els=document.getElementsByClass('fancyStyle','p');
*/
//Object.prototype.getElementsByClassName = function(cl) {
document.getElementsByClassName = function(cl) {  
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
}

function CenterElt(elt) {
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    var elementWidth= elt.offsetWidth;
	var elementHeight= elt.offsetHeight;
    
	var posX= Math.max(0, myWidth  - (myWidth/2) - (elementWidth/2));
	var posY= Math.max(0, myHeight - (myHeight/2) - (elementHeight/2));
	elt.style.left=posX+"px";
    elt.style.top=posY+"px";
}