(function(){
 // page initialization
 function init(){
  if(typeof(window.ol)=='function'){ // check if the individual page has an onload listener
   window.ol()
  }
  new AlertControl('alerts');
  new togglingInput('dhwcEmail');
  var newsEvents = new window.jeremy.molded.SearchControl();
  newsEvents.addSearcher(new window.jeremy.molded.CalendarSearch);
  newsEvents.addSearcher(new window.jeremy.molded.NewsSearch);
  var twitterSearch = new TwitterSearch;
  twitterSearch.setQueryAddition('@DebraHeightsDM');
  newsEvents.addSearcher(twitterSearch);
  newsEvents.draw('newsEvents',{drawMode : 'tabbed'});
  newsEvents.setResultSetSize(8);
  newsEvents.makeActiveTab(newsEvents.b[0]);
  newsEvents.execute(' ');
  window._gaq = window._gaq || [];
  window._gaq.push(['_setAccount', 'UA-2088380-5']);
  window._gaq.push(['_trackPageview']);
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  document.getElementsByTagName('head')[0].appendChild(ga);
 }
 function togglingInput(id){
  var z= this,
   el = this.el = document.getElementById(id);
  el.className += ' togglingInput';
  window.jeremy.addEvent('focus',function(){
                           togglingInput.prototype.toggle.apply(z, [])
                         },el);
  window.jeremy.addEvent('blur',function(e){
                           togglingInput.prototype.toggle.apply(z,[e])
                         },el);
 }
 togglingInput.prototype.toggle=function(){
  var el = this.el;
  if(el.value == el.defaultValue){
   el.value = '';
  }else if(el.value == ''){
   el.value = el.defaultValue;
  }
 };
 
 // Alerts Control
 function AlertControl(el, opt_options){
  this.el = typeof(el)=='string' ? document.getElementById(el) : el;
  if(!opt_options){
   opt_options = {}
  }
  this.options = opt_options;
  var searcher = this.searcher = new jeremy.molded.NewsSearch;
  searcher.setRestriction('type','alert');
  searcher.setSearchCompleteCallback(this, AlertControl.prototype.callback);
  this.refreshInterval = setInterval(createClosure(this,AlertControl.prototype.execute),(opt_options.refreshInterval || 60) * 1000);
 }
 AlertControl.prototype.callback=function(){
  var el = this.el,
   searcher = this.searcher;
  if(searcher.results){
   for(var i=0;i<searcher.results.length;i++){
    var result = searcher.results[i];
    if(!document.getElementById('alert'+result.id)){
     var resultEl = result.alertHtml = createEl('div','alert',[
      createEl('a','alert',[
       document.createTextNode(result.title)
      ],{
       'href' : result.url,
       'title' : result.title
      })
     ],{
      id : 'alert'+result.id
     });
     resultEl.style.marginTop='-100px';
     el.insertBefore(resultEl,el.firstChild);
     this.reveal(resultEl);
    }
   }
  }
 };
 AlertControl.prototype.reveal=function(el){
  if(el.revealTimer){
   clearTimeout(el.revealTimer)
  }
  var newMargin = parseInt(el.style.marginTop) + 5;
  el.style.marginTop = newMargin + 'px';
  if(newMargin < 0){
   el.revealTimer=setTimeout(createClosure(this,AlertControl.prototype.reveal,[el]), 50);
  }
 };
 AlertControl.prototype.execute=function(query){
  this.searcher.execute(query || '')
 };

 // Twitter Search
 function TwitterSearch(opt_options){
  var z = this,
   options = z.options = {
    'rpp' : 8
   },
   searchers = TwitterSearch.searchers,
   context = z.context = searchers.length;
  searchers.push(z);
  for(var i in opt_options){
   options[i] = opt_options[i]
  }
 }
 TwitterSearch.prototype = new window.jeremy.molded.Search;
 TwitterSearch.prototype.execute = function(q){
  var z=this,
   baseUrl='http://search.twitter.com/search.json?',
   c=z.options,
   params=[
    'q='+encodeURIComponent(q)+(z.queryAddition?encodeURIComponent(' '+z.queryAddition):''),
    'callback='+encodeURIComponent('window.jeremy.TwitterSearch.searchers.s'+z.context+'.callback')
   ],
   script=document.createElement('script'),
   onload=function(){
    script.onload=null;
    script.parentNode.removeChild(script);
    delete(script)
   },
   onreadystatechange=function(){
    if(script.readyState.match(/loaded|complete/i)){
     script.onreadystatechange=null;
     onload()
    }
   };
  if(z.stc){
   z.stc()
  }
  for(var i in c){
   params.push(i+'='+encodeURIComponent(c[i]))
  }
  script.type='text/javascript';
  script.src=baseUrl+params.join('&');
  if(navigator.product=='Gecko'){
   script.onload=onload
  }else{
   script.onreadystatechange=onreadystatechange
  }
  document.getElementsByTagName('head')[0].appendChild(script)
 }
 TwitterSearch.prototype.setQueryAddition=function(a){
  this.queryAddition=a;
 }
 TwitterSearch.prototype.setRestriction=function(a){
  var z=this,
   b=z.options;
  for(var i in a){
   b[i]=a[i]
  }
 };
 TwitterSearch.prototype.callback=function(response){
  var z=this,
   b=z.results=response.results||[];
  z.cursor={moreResultsUrl:null,estimatedResultCount:null,pages:[]};
  for(var i=0;i<b.length;i++){
   z.createHtml(b[i])
  }
  if(z.sc){
   z.sc()
  }
 };
 TwitterSearch.prototype.createHtml=function(result){
  var z=this,
   b=result.html=createEl(null,'gs-result',[
                                         createEl('img','gs-image',null,{
                                              src : result['profile_image_url'],
                                              alt : result.from_user
                                         }),
                                         createEl(null,'gs-snippet',[
                                                                      createEl('strong','gs-fromUser',[
                                                                                                      createEl('a','gs-fromUser',[
                                                                                                        document.createTextNode(result['from_user']+': ')
                                                                                                      ],{
                                                                                                        href : 'http://www.twitter.com/'+result.from_user
                                                                                                      })
                                                                      ]),
                                                                      result['text'].replace(/(http:\/\/\S*)/ig, function(a){return '<a href="'+a+'">'+a+'</a>'})
                                                                      ]),
                                          createEl(null,'gs-relativePublishedDate',[
                                                                                    document.createTextNode(z.getRelativeDate(result.created_at))
                                                                                    ])
                                          ]);
  return b
 };
 TwitterSearch.prototype.getLabel=function(){
  return 'Twitter'
 };
 TwitterSearch.prototype.getRelativeDate=function(created){
  created=new Date(created);
  var now=new Date(),
   rel=(now.getTime()-created.getTime())/1000,
   minutesAgo=' minutes ago',
   hoursAgo=' hours ago',
   secondsPerHour=3600,
   secondsPerDay=86400;
  if(rel<0){
   return 2+minutesAgo;
  }
  if(rel<secondsPerHour){
   return Math.round(rel/60)+minutesAgo;
  }
  if(rel<secondsPerDay){
   return Math.round(rel/secondsPerHour)+hoursAgo;
  }
  return created.getDate()+' '+['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][created.getMonth()]+' '+created.getFullYear();
 };
 TwitterSearch.searchers = {
  length:0,
  push : function(item){
   this['s'+this.length]=item;
   this.length++;
  }
 };
 
 function createEl(tagName, className, children, attribs, styles){
  var el=document.createElement(tagName || 'div');
  if(className){
   el.className=className
  }
  if(children){
   for(var i=0;i<children.length;i++){
    var child=children[i];
    if(typeof(child)=='string'){
     el.innerHTML+=child;
    }else{
     try{
      el.appendChild(child);
     }catch(err){
     }
    }
   }
  }
  if(attribs){
   for(var i in attribs){
    el.setAttribute(i, attribs[i])
   }
  }
  if(styles){
   for(var i in styles){
    el.style[i] = styles[i]
   }
  }
  return el;
 }
 
 function createClosure(context, method, args){
  return function(){
   return method.apply(context, args || arguments)
  }
 }
 
 window.jeremy.TwitterSearch = TwitterSearch;

 window.jeremy.addEvent('load',init);
})()
