/*		Trim Functions		*/

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"

*/


/*		Numeric Sort Function		*/

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?		*/

function isArray(testObject) {   
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

/*
Usage… 

var tmp = [5,9,12,18,'blue',30,7,97,53,33,30,35,27,30];
var tmp2 = {0:5,1:9,2:12}

test1 = isArray(tmp);    // returns true
test2 = isArray(tmp2);   // returns false;
*/


/*		Cookies!		*/

function cookiesAllowed() {
   setCookie('checkCookie', 'test', 1);
   if (getCookie('checkCookie')) {
     return deleteCookie('checkCookie');
     
   }
   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 ) ) 
   {
	 setCookie(name,"test","Thu, 01-Jan-1970 00:00:01 GMT");
	 //document.cookie = name + '=' + ( ( path ) ? ';path=' + path : '') + ( ( domain ) ? ';domain=' + domain : '' ) +';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	  return true;
   }
   else
   {
		return false;   
   }
}

/*
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,men
*/



/*		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 - Temporarily blocked		*/

/*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');
*/



/*		AJAX		*/

function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}

/*
Usage… 

// Just a stub function we'll tell ajaxObject to call when it's done
// callback functions get responseText, and responseStat respectively
// in their arguments.
function fin(responseTxt,responseStat) {
  alert(responseStat+' - '+responseTxt);
}

// create a new ajaxObject, give it a url it will be calling and
// tell it to call the function "fin" when its got data back from the server.
var test1 = new ajaxObject('http://someurl.com/server.cgi',fin);
    test1.update();
	
// this can be also written inline	with all three optional parameters
var test1 = new ajaxObject('http://someurl.com/server.cgi',fin);
	test1.callback = function(responseText, responseStatus, responseXML) {
      alert(responseStat+' - '+responseTxt);
    }
    test1.update();
                
// create a new ajaxObject, give it a url and tell it to call fin when it
// gets data back from the server.  When we initiate the ajax call we'll
// be passing 'id=user4379' to the server.              
var test2 = new ajaxObject('http://someurl.com/program.php',fin);
    test2.update('id=user4379');
                
// create a new ajaxObject but we'll overwrite the callback function inside
// the object to more tightly bind the object with the response hanlder.
var test3 = new ajaxObject('http://someurl.com/prog.py', fin);
    test3.callback = function (responseTxt, responseStat) {
      // we'll do something to process the data here.
      document.getElementById('someDiv').innerHTML=responseTxt;
    }
    test3.update('coolData=47&userId=user49&log=true'); 
                
// create a new ajaxObject and pass the data to the server (in update) as
// a POST method instead of a GET method.
var test4 = new ajaxObject('http://someurl.com/postit.cgi', fin);
    test4.update('coolData=47&userId=user49&log=true','POST');  
*/


