/*
 * File: methods.js
 * Created: Sept 27, 2006
 * Author: Wes Jones
 * Purpose: To provide functions that are used on a consistent 
 *    basis or that do not belong to any particular class
 */

String.prototype.ucfirst = function(){
     return this.toLowerCase().replace(/\w+/g,function(s){
          return s.charAt(0).toUpperCase() + s.substr(1);
     })
}

String.prototype.ucwords = function(){
     return this.toLowerCase().replace(/\w+/g,function(s){
          var a = s.split(' ');
          for(var i = 0; i < a.length; ++i) {
             s = s.replace(a[i],a[i].ucfirst());
          }
          return s;
     })
}

String.prototype.charpac = function(n){
      var str = '';
      for(var i = 0; i < n; ++i) { str += this; }
      return str;
}

String.prototype.trim = function() {
    str = this != window? this : str;
    return str.replace(/^\s+/, '').replace(/\s+$/, '');
}

Number.prototype.decimals = function(n){
   var z = parseInt(n) ? parseInt('1'+('0'.charpac(n))) : 1;
   return z > 1 ? Math.round(this*z)/z : this;
}

function clone (obj,deep) {
  var objectClone = new obj.constructor();
  for (var property in obj)
    if (!deep)
      objectClone[property] = obj[property];
    else if (typeof obj[property] == 'object')
      objectClone[property] = clone(obj[property],deep);
    else
      objectClone[property] = obj[property];
  return objectClone;
}


function count(__object__){
   var len = 0; for(var i in __object__) { len += 1; }; return len;
}

// GLOBALS this is used to hold global variables between functions
// this allows functions to have variables when returned from AJAX
var GLOBALS = new Object(); 
var PO = new ParseObj();

function divWindow (dw,img,hdr,str,w,h,x,y,onclose,dir) {
/*
 * Purpose: to simulate a popup window with a div layer
 * dw is the a div object
 */
   // if dw is a string make it become the object assuming it is the id for the object
   var dw = document.getElementById(dw);
   var w = parseInt(w) > 100 ? parseInt(w) : 400;
   var h = parseInt(h) > 50 ? parseInt(h) : 400;
   dw.style.position = 'absolute';
   dw.style.width = w+'px';
   dw.style.height = h+'px';
   dw.style.left = (typeof(x) ? x : screen.width/2 - w/2)+'px';
   dw.style.top = (typeof(y) ? y : screen.height/2 - h/2)+'px';
   dw.style.zIndex = 100;
   dw.style.backgroundColor = '#ffffff';
   dw.onclose = function () {
      this.innerHTML = '';
      this.style.position = 'absolute';
      this.style.left = '0px';
      this.style.top = '0px';
      this.style.width = '1px';
      this.style.height = '1px';
   }
   dw.path = typeof(dir) ? dir : '';
   dw.innerHTML = '<IFRAME id="'+dw.id+'_frame" style="position:absolute;background-color:'+dw.style.backgroundColor+';width:'+(is_nav ? w+8 : w)+'px;height:'+(is_nav ? h+8 : 8)+'px;" frameborder=0 scrolling=no marginwidth=0 src="" marginheight=0></iframe>'+
                  '<div style="position:absolute;border:4px ridge;background-color:'+dw.style.backgroundColor+';width:'+w+'px;height:'+h+'px;">'+
                     '<div id="'+dw.id+'_content" style="position:absolute;margin-top:20px;width:'+(is_ie ? w-8 : w)+'px;height:'+((is_ie ? h-8 : h)-20)+'px;overflow:auto;">'+str+'</div>'+
                  '</div>'+
                  '<div id="'+dw.id+'_hdr" style="position:absolute;top:4px;left:4px;background-image:url('+img+');width:'+(document.all ? w-7 : w+1)+'px;height:20px;color:#ffffff;">'+hdr+'</div>'+
                  '<div id="'+dw.id+'_close" align="center" style="position:absolute;top:6px;left:'+(w-(is_ie ? 20 : 13))+'px;width:16px;height:16px;display:table-cell;vertical-align:middle;text-align:center;"><a href="javascript:divClose(\''+dw.id+'\');"><img src="'+dw.path+'/cache/sv/1202925915931/postcard/images/close.gif" border="0" width="16" height="14"></a></div>';
str = '';
for(var i in dw.style) {
   str+= i+' = '+dw.style[i]+'<br>';
}
   makeDraggable(document.getElementById(dw.id+'_hdr'),dw);
}

function divClose(dw) {
   var dw = document.getElementById(dw);
   dw.onclose();
}

function setCookie(cookieName,cookieValue,nDays) {
   var today = new Date();
   var expire = new Date();
   if (nDays==null || nDays==0) nDays=1;
   expire.setTime(today.getTime() + 3600000*24*nDays);
   document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
}

function deleteCookie(cookieName) {
   var c = new Date();
   document.cookie = cookieName+'=1;expires='+c.toGMTString()+';'+';';
}


function escapeHtml(str) {
   if(typeof(str) == 'string') {
      str = str.replace(/\</gi,'&lt;');
      str = str.replace(/\>/gi,'&gt;');
      str = str.replace(/\"/gi,'&quot;');
      str = str.replace(/\&/gi,'&amp;');
      str = str.replace(/\-/gi,'&ndash;');
      str = str.replace(/\_/gi,'&mdash;');
      str = str.replace(/\'/gi,'&lsquo;');
   }
   return str;
}

function unescapeHtml(str) {
   if(typeof(str) == 'string') {
      str = str.replace(/\&lt\;/gi,'<');
      str = str.replace(/\&gt\;/gi,'>');
      str = str.replace(/\&quot\;/gi,'"');
      str = str.replace(/\&amp\;/gi,'&');
      str = str.replace(/\&ndash\;/gi,'-');
      str = str.replace(/\&mdash\;/gi,'_');
      str = str.replace(/\&lsquo\;/gi,'\'');
      str = str.replace(/\&rsquo\;/gi,'\'');
   }
   return str;
}


function daysInMonth(year,month) {
   // month needs to be 0-11
   var d= new Date();
   year = year ? year : d.getFullYear();
   var days = new Array(31,((year%4==0&& year%100!=0)||year%400==0?29:28),31,30,31,30,31,31,30,31,30,31);
   if (!isNaN(month)) { return days[month]; }
   else { return days; }
}

function getMonthName(month,chars) {
   var months = new Array('January','February','March','April','May','Jun','July','August','September','October','November','December');
   return months[month].substr(0,(parseInt(chars) > 0 ? chars : months[month].length));
}

function startTime(divid) {
   var today=new Date()
   var h=today.getHours()
   var m=today.getMinutes()
   var s=today.getSeconds()
   // add a zero in front of numbers<10
   h=dd(h);
   m=dd(m)
   s=dd(s)
   document.getElementById(divid).innerHTML=h+":"+m+":"+s
   t=setTimeout('startTime()',500)
}

function dd(i){ // make double digits
   if (i<10) {i="0" + i}
   return i;
}

function charpac(s,n) {
   var str = '';
   for(var i = 0; i < n; ++i) { str += s; }
   return str;
}

function getMilliseconds() {
   var d = new Date();
   var n = 0;
   n += d.getHours()*60*60*1000;
   n += d.getMinutes()*60*1000;
   n += d.getSeconds()*1000;
   n += d.getMilliseconds();
   return n;
}

function preInput(type,id,txt,rows,cols,style) {
   if(type == 'text') {
      return '<input type="text" name="'+id+'" id="'+id+'" value="'+txt+'" style="'+(style ? style : 'color:#999999;width:230px;font-family:arial;font-size:11px;')+'" onfocus="preInputText(\''+txt+'\',this,\'focus\');" onblur="preInputText(\''+txt+'\',this,\'blur\');">';
   } else if(type == 'textarea') {
      return '<textarea  name="'+id+'" id="'+id+'" rows="'+rows+'" cols="'+cols+'" style="'+(style ? style : 'color:#999999;width:230px;font-family:arial;font-size:11px;')+'" onfocus="preInputText(\''+txt+'\',this,\'focus\');" onblur="preInputText(\''+txt+'\',this,\'blur\');">'+txt+'</textarea>';
   }
}

function preInputText(str,obj,cmd) {
   if(cmd == 'focus') {
      if(obj.value == str) {
         obj.style.color = '#000000';
         obj.value = '';
      }
   } else if (cmd == 'blur') {
      if(obj.value == '') {
         obj.style.color = '#999999';
         obj.value = str;
      }
   }
}

function PopUp () {
   this.name = 'popup';
   this.toolbar = 'no';
   this.scrollbars = 'yes';
   this.status = 'no';
   this.resizable = 'no';
   this.menubar = 'no';
   this.width = 320;
   this.height = 240;
   this.win = null;
   this.url = null;
   this.go = function (url) {
      this.url = url;
      this.win=window.open(url,this.name,'toolbar='+this.toolbar+',scrollbars='+this.scrollbar+',status='+this.status+',resizable='+this.resizable+',menubar='+this.menubar+',width='+this.width+',height='+this.height);
   }
   this.write = function (str) {
      this.win.document.write(str);
   }
}


function exists(obj,attribute) {
   var e = false;
   for(var i in obj) {
      if(i == attribute) {
         e = true;
         break;
      }
   }
   return e;
}


function CreateBookmarkLink(title) {
   url = document.location;

   if (window.sidebar) { // Mozilla Firefox Bookmark
      window.sidebar.addPanel(title, url,"");
   } else if( window.external ) { // IE Favorite
      window.external.AddFavorite( url, title);
   } else if(window.opera && window.print) { // Opera Hotlist
      return true;
   }
}

function getKeyCode (e) {
   if(window.event) { // IE
      return e.keyCode;
   } else if (e.which) { // Netscape/Firefox/Opera
      return e.which;
   }
}

function secondstostr (s,chop) {
   // convert a time in seconds to Y-m-d H:i:s
   if(s == 0) { return 0; }
   else {
      var negative = '';
      if(s<0) { s = Math.abs(s); negative='-'; }
      var tl = s;
      s = dd(s%60);
         tl = (tl-s)/60;
      var i = dd(tl%60);
         tl = (tl-i)/60;
      var h = dd(tl%24);
         tl = (tl-h)/24;
      var mydate = new Date();
         dim = daysInMonth(mydate.getFullYear(),mydate.getMonth());
      var d = dd(tl%dim);
         tl = (tl-d)/dim;
      var m = dd(tl%12); 
         tl = (tl-m)/12;
      var y = dd(tl);
      if(!chop) {
         return negative+y+'-'+m+'-'+d+' '+h+':'+i+':'+s;
      } else {
         str='';
         if(y>0||str){ str+=y+'-'; }
         if(m>0||str){ str+=m+'-'; }
         if(d>0||str){ str+=d+' '; }
         if(h>0||str){ str+=h+':'; }
         if(i>0||str){ str+=i+':'; }
         str+=s;
         return negative+str;
      }
   }
}

function ByteSize(bytes) {  
/* format sizes of bytes */
   size = bytes / 1024;  
   if(size < 1024){
       // kilobytes
       size = (parseInt((size)*100)/100)+'kb';  
   } else {  
       if(size / 1024 < 1024) {
           // megabytes
           size = size/1024;
           size = (parseInt((size)*100)/100)+'mb';  
       } else if(size/1024/1024 < 1024) {
           // gigabytes
           size = size/1024/1024;
           size = (parseInt((size)*100)/100)+'gb';  
       } else {  
           // terrabytes
           size = size/1024/1024/1024;  
           size = (parseInt((size)*100)/100)+'tb';  
       }  
   }  
   return size;  
}

function ParseObj() {
/*
 * ParseObj.js
 * Created Sept 26, 2006
 * Author: Wes Jones
 * Purpose: take any url or query string and parse it into a hiearchal object return as array of objects
 * Example: gets variables out of a query string
 *   var str = 'test=hello&user[id]=1&user[level]=2';
 *   var p = new ParseObj();
 *   var obj = p.parseIt(str);
 *   alert(p.traceIt(obj)); // traces like print_r in php
 * Example 2: gets variables out of the url
 *   var p = new ParseObj();
 *   var urlvars = p.getURL();
 *   alert(p.traceIt(urlvars));
 */
   this.obj = new Object();
   this.getURL = function () { // get url and parseIt
      var str = document.location+'';
      var sp = str.split('?');
      return this.parseIt(sp[1]);
   }
   this.parseIt = function (vars,chr) {
      // parese query string into variable object and return it
      this.obj = new Object();
      chr = chr ? chr : '&';
      if(typeof(vars) != 'string') { vars = vars+''; }
      var v = vars.split(chr);
      for(var i = 0; i < v.length; i ++) {
         v[i] = v[i].split('=');
         var tmp = v[i][0].split('[');
         if (tmp.length > 1) {
            if (this.obj[tmp[0]] == undefined) {
               this.obj[tmp[0]] = new Object();
            }
            var keys = v[i][0].split('[');
            keys = keys.splice(1,keys.length-1);
            for(var j in keys) {
               keys[j] = keys[j].replace(']','');
            }
            this.obj[tmp[0]] = this.addKV(this.obj[tmp[0]],keys,v[i][1]);
         } else {
            if (v[i][0]) {
               this.obj[v[i][0]] = v[i][1];
            }
         }
      }
      return this.obj;
   }
   this.addKV = function (obj,keys,val) {
      // add sub child objects recursivly
      if(keys.length > 1) {
         if(!obj[keys[0]]) {
            obj[keys[0]] = new Object();
         }
         obj[keys[0]] = this.addKV(obj[keys[0]],keys.splice(1,keys.length-1),val);
      } else {
         obj[keys[0]] = val.match(/^\d+$/) ? parseFloat(val) : val.replace(/\|\#35\;/gi,'&');
      }
      return obj;
   }
   this.charPac = function (c,d) {
      // add spacing for legibility
      var str = '';
      for(var i = 0; i < d; ++i) { str += c; }
      return str;
   }
   this.traceIt = function (obj,depth) {
      // recursivly trace the array and ouput in hiearchal string
      var str = '';
      depth = depth ? parseInt(depth) : 0;
      for(var i in obj) {
         str += this.charPac('---',depth+1)+'['+i+'] '+(typeof(obj[i]) == 'object' ? '= Object (\n'+this.traceIt(obj[i],depth+2) : ' = '+obj[i]+',')+'\n';
         str += typeof(obj[i]) == 'object' ? this.charPac('---',depth+1)+'),\n' : '';
      }
      return str;
   }
   this.toString = function (obj,name) {
      var str = '';
      for (i in obj) {
         if (typeof(obj[i]) != 'function') {
            if(typeof(obj[i]) == 'object' || typeof(obj[i]) == 'array') {
               str += this.toString(obj[i],name+'['+i+']');
            } else {
               str += name+'['+i+']='+obj[i]+'&';
            }
         }
      }
      return str;
   }
}

function copy_clip(meintext) {
   if (window.clipboardData) {
      // the IE-manier
      window.clipboardData.setData("Text", meintext);
   } else if (window.netscape) { 
      // you have to sign the code to enable this, or see notes below 
      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
      // maak een interface naar het clipboard
      var clip = Components.classes['@mozilla.org/widget/clipboard;1']
                 .createInstance(Components.interfaces.nsIClipboard);
      if (!clip) return;
         // maak een transferable
         var trans = Components.classes['@mozilla.org/widget/transferable;1']
                  .createInstance(Components.interfaces.nsITransferable);
      if (!trans) return;
         // specificeer wat voor soort data we op willen halen; text in dit geval
         trans.addDataFlavor('text/unicode');
         var str = new Object();
         var len = new Object();
   
         var str = Components.classes["@mozilla.org/supports-string;1"]
                .createInstance(Components.interfaces.nsISupportsString);
   
         var copytext=meintext;
   
         str.data=copytext;
   
         trans.setTransferData("text/unicode",str,copytext.length*2);
   
         var clipid=Components.interfaces.nsIClipboard;
   
         if (!clip) return false;

         clip.setData(trans,null,clipid.kGlobalClipboard);
      }
      return false;
}