/**
 * PopRule Action Engine UI
 * Copyright 2009-2010 PopRule, LLC
 * All Rights Reserved
 */
( function() {
   var trueName = '';
   for (var i = 0; i < 16; i++) {
      trueName += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
   }
   window[trueName] = {};
   var $ = window[trueName];
   $.f = function() {
      return {
         runFunction : [],
         baseUrl : 'http://poprule.com/',
         cdnUrl : 'http://static.poprule.com/',
         pageCache : {},
         cacheOrder : [],
         cachePos : -1,
         interactTime: 0,
         startTime: 0,
         clickCount: 0,
         partnerId: false,
         init : function(target) {
            var theScripts = document.getElementsByTagName('SCRIPT');
            for (var i = 0; i < theScripts.length; i++) {
               if (theScripts[i].src.match(target)) {
                  if (theScripts[i].innerHTML) {
                    // Replace CDATA and HTML in the arguments
                    
                    var toeval = theScripts[i].innerHTML;
                    
                    toeval = toeval.replace(/<!--|\/?\/?.*-->/g, "");
                    toeval = toeval.replace(/\/\/.*<!\[CDATA\[/g, "");
                    toeval = toeval.replace(/\/\/.*\]\]>/gi, "");
                    toeval = toeval.replace(/<(?:.|\s)*?>/gi,"");

                    if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]+$/.test(toeval.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) {
                      try {
                        $.a = eval( '(' + toeval + ')' );
                      }
                      catch(err) { }
                    }
                  }
                  if (typeof $.a !== 'object') {
                     $.a = {};
                  }
                  
                  // Determine what server to use
                  if($.a.server == 'test') {
                    $.f.baseUrl = 'http://test.poprule.com/';
                    $.f.cdnUrl = 'http://test-static.poprule.com/';
                  }
                  else if($.a.server == 'dev') {
                    $.f.baseUrl = 'http://dev.poprule.com/';
                    $.f.cdnUrl = 'http://static.poprule.com/';
                  }
                  
                  $.a.client = 'liveearth';
                  
                  if(!$.a.brand) {
                    $.a.brand = 'main';
                  }
                  
                  $.f.requestStylesheet($.a.client + '/' + $.a.brand + '.css');
                 
                  $.f.buildStructure();
                  
                  theScripts[i].parentNode.insertBefore($.c, theScripts[i]);
                  theScripts[i].parentNode.removeChild(theScripts[i]);
                  break;
               }
            }
         },
         leave : function() {
           if($.f.startTime != 0) {
             var d = new Date();
             $.f.interactTime += (d.getTime() - $.f.startTime);
           }
         
           $.f.loadContent('report_engage', '&source=widget&time=' + ($.f.interactTime / 1000) + '&clicks=' + $.f.clickCount, false);
           
           return true;
         },
         requestStylesheet: function(sheet) {
            stylesheet = document.createElement("link");
            stylesheet.rel = "stylesheet";
            stylesheet.type = "text/css";
            stylesheet.href = $.f.cdnUrl + 'css/' + sheet;
            stylesheet.media = "all";
            document.lastChild.firstChild.appendChild(stylesheet);
         },
         buildStructure : function() {         
           $.c = document.createElement('div');
        
           $.w = document.createElement('div');
           $.w.className = 'pr-wdgt';
           $.w.id = trueName;
           $.w.onmouseover = function() { $.f.logTime('enter'); };
           $.w.onmouseout = function() { $.f.logTime('exit'); };
           
           // Overlay
           var de = document.documentElement;
             $.f.windowHeight = self.innerHeight || document.body.clientHeight;
             $.f.windowWidth = self.innerWidth || document.body.clientWidth;
             
             $.w.shade = document.createElement('div');
             $.w.shade.id = 'pr-shade';
             $.w.shade.style.height = $.f.windowHeight + 'px';
             $.w.shade.style.display = 'none';
             document.body.appendChild($.w.shade);
           
             //Specify iframe to display. Change src and other attributes except "position" and "left/top":
             $.w.idiv = document.createElement('div');
             $.w.idiv.id = 'pr-overlay';
             $.w.idiv.style.display = 'none';

             $.w.idivi = document.createElement('div');
             $.w.idivi.className = 'pr-overmid';
             $.w.idiv.appendChild($.w.idivi);
             
             $.w.idivii = document.createElement('div');
             $.w.idivii.className = 'pr-overinner';
             $.w.idivi.appendChild($.w.idivii);
           
             $.w.icl = document.createElement('a');
             $.w.icl.href='#';
             $.w.icl.className = 'pr-close';
             $.w.icl.innerHTML = 'close';
             $.w.icl.onclick = function() {
               $.f.hideOverlay();
               return false;
             };
           
             $.w.idivii.appendChild($.w.icl);
           
             $.w.idiv.ttl = document.createElement('div');
             $.w.idiv.ttl.className = 'pr-ttl';
             $.w.idiv.ttl.innerHTML = '<strong>DOW LIVE EARTH /</strong> RUN FOR WATER';
  
             $.w.idivii.appendChild($.w.idiv.ttl);
           
             $.w.iframe = document.createElement('iframe');
             $.w.iframe.scrolling = "no";
           
             $.w.idivii.appendChild($.w.iframe);

           document.body.appendChild($.w.idiv);

           $.w.p = document.createElement('div');
           $.w.p.className = 'pr-act';
           
           $.w.p.loading = document.createElement('div');
           $.w.p.loading.className = 'pr-load';
           $.w.p.loading.innerHTML = '<img src="' + $.f.cdnUrl + 'img/liveearth/loader.gif" />';
           $.w.p.appendChild($.w.p.loading);
           
           // Create Masthead
           $.w.p.m = document.createElement('a');
           
           $.w.p.m.className = 'pr-mst';
           $.w.p.m.innerHTML = '&nbsp;';
           $.w.p.m.target = '_blank';
           $.w.p.appendChild($.w.p.m);
           
           // Create content area
           $.w.p.dyn = document.createElement('div');
           $.w.p.dyn.className = 'pr-content';
            
           $.w.p.appendChild($.w.p.dyn);
           
           $.f.loadContent('api/primary/liveearth', '&configure=1&issue=water', true);
           
           // Create footer
           $.w.p.foot = document.createElement('div');
           $.w.p.foot.className = 'pr-ftr';

           $.w.p.appendChild($.w.p.foot);
           
           // Powered by PopRule
           $.w.p.ia = document.createElement('a');
           $.w.p.ia.href = 'http://poprule.com/';
           $.w.p.ia.innerHTML = 'Powered by PopRule';
           $.w.p.ia.target = "_blank";
           $.w.p.ia.className = 'pr-logo';
           $.w.p.appendChild($.w.p.ia);
           
           $.w.appendChild($.w.p);
           $.c.appendChild($.w);
         },
         loadContent : function(src, args, refresh) {
           var url = $.f.baseUrl + src + '?key=' + $.a.client + args;
           
           if($.f.partnerId) { 
             url += '&ref=' + $.f.partnerId;
             
             // Log the click
             $.f.clickCount++;
           }
           else {
             if($.a.page) {
               url += '&t=adserver&ref=' + escape($.a.page);
             }
             else {
               url += '&t=' + escape(document.title) + '&ref=' + escape(location.href.replace(/\?.*|#/,'')); 
             }
           }
           
           if($.a.brand == 'thin') {
             url += '&thin=1';
           }
           
           $.f.cachePos++;
           $.f.cacheOrder[$.f.cachePos] = url;
           
           if($.f.pageCache[url]) {
             $.f.renderResult($.f.pageCache[url]);
           }
           else {
             if(refresh) {
               $.w.p.loading.style.display = 'block';
             }
         
             var n = $.f.runFunction.length;
             var id = trueName + '.f.runFunction[' + n + ']';
             
             var preCB = url;
             
             $.f.runFunction[n] = function(r) {
               $.f.pageCache[preCB] = r;
             
               delete($.f.runFunction[n]);
               $.f.removeScript(id);
               $.f.renderResult(r);

               $.w.p.loading.style.display = 'none';   
             };
             
             if($.a.redirect) {
               url += '&r=' + $.a.redirect;
             }
             
             url += '&callback=' + id;
             
             $.f.runScript(url, id);
           }
         },
         switchTab : function(tab) {
           var tabs = $.w.p.foot.getElementsByTagName('a');
           
           for(var i=0;i<tabs.length;i++) {
             tabs[i].className = 'pr-tab';
           }
           
           tab.className = 'pr-tab pr-tab-on';
         },
         formatLink: function(o, front) {
           l = document.createElement('a');
           l.className = 'pr-lnk';

           if(o['type'] != false) {
             ls = document.createElement('span');
             ls.className = 'pr-' + o['type'];
             ls.innerHTML = o['type'].toUpperCase();
             
             l.appendChild(ls);
           }
           
           l.innerHTML += ' ' + o['title'];
           
           if(!o['html']) {
             if(o['url']) {
               l.href = o['url'];
               l.target = '_blank';
             }
             else {
               if(!o['callback_args']) { o['callback_args'] = ''; }
           
               l.href = '#';
               l.onclick = function() {
                 $.f.loadContent(o['callback'], o['callback_args'], true);
                 return false;
               };
             }
           }
           
           return l;
         },
         goBack : function(home) {
           if($.f.cachePos != 0) {
             if(home) {
               $.f.cachePos = 0;
             }
             else {
               $.f.cachePos--;
             }
             
             $.f.renderResult($.f.pageCache[$.f.cacheOrder[$.f.cachePos]]);
           }
         },
         logTime: function(dir) {
           var d = new Date();
           if(dir == 'enter') {
             $.f.startTime = d.getTime();
           }
           else if(dir == 'exit') {
             $.f.interactTime += (d.getTime() - $.f.startTime);
             $.f.startTime = 0;
           }
         },
         switchTab : function(tab) {
           var tabs = $.w.p.foot.getElementsByTagName('a');
           
           for(var i=0;i<tabs.length;i++) {
             tabs[i].className = 'pr-tab';
           }
           
           tab.className = 'pr-tab pr-tab-on';
         },
         showOverlay: function(url) {
           $.w.iframe.src = url;
           $.w.idiv.style.left = (($.f.windowWidth - 710) / 2) + "px";
           //$.w.idiv.style.top = (($.f.windowHeight - 610) / 2) + "px";
           $.w.idiv.style.top = "50px";
           //$.w.shade.style.display = 'block';
           $.w.idiv.style.display = 'block';
         },
         hideOverlay: function() {
           //$.w.shade.style.display = 'none';
           $.w.idiv.style.display = 'none';
         },
         resize: function() {
           $.f.windowHeight = self.innerHeight || (de && de.clientHeight ) || document.body.clientHeight;
           $.f.windowWidth = self.innerWidth || document.body.clientWidth;
           
           $.w.idiv.style.top = (($.f.windowHeight - 610) / 2) + "px";
           $.w.idiv.style.left = (($.f.windowWidth - 710) / 2) + "px";

           $.w.shade.style.height = $.f.windowHeight + 'px';
         },
         renderResult: function(r) {
           if(!$.f.partnerId) {
             $.f.partnerId = r.pid;
           }
            
           if(r.masthead) {
             var mastUrl = $.f.baseUrl + 'clicktrack?source=widget&ref=' + $.f.partnerId + '&key=' + $.a.client + '&u=' + escape(r.masthead);
            
             if(!$.a.redirect) {
               $.w.p.m.href = mastUrl;
             }
             else {
               $.w.p.m.href = $.a.redirect + escape(mastUrl);
             }
           }
           n = document.createElement('div');
           
           if($.a.brand == 'thin') {
             n.style.height = '312px';
           }
           else {
             n.style.height = '176px';
           }
            
           if(r.tabs) {
             for(i=0;i<r.tabs.length;i++) {
               var nextTab = document.createElement('a');
               if(i==0) {
                 nextTab.className = 'pr-tab pr-tab-on';
               }
               else {
                 nextTab.className = 'pr-tab';
               }
               
               if($.a.brand == 'thin') {
                 if(i==0 || i==2) {
                   nextTab.style.width = '36px';
                 }
                 else if(i==3) {
                   nextTab.style.clear = 'left';
                 }
               }
               
               nextTab.href = '#';
               nextTab.rel = r.tabs[i].callback;
               if(r.tabs[i].callback_args != '') {
                 nextTab.title = r.tabs[i].callback_args;
               }
               else {
                 nextTab.title = '';
               }
               nextTab.onclick = function() { 
                 $.f.switchTab(this);
                 $.f.loadContent(this.rel, this.title, true); 
                 return false; 
               };
               nextTab.innerHTML = r.tabs[i].title;
               $.w.p.foot.appendChild(nextTab); 
             }
           }
            
           if(r.type == 'html') {
             if(r.links) {
               lDiv = document.createElement('div');
               lDiv.className = 'pr-flnks';
                 
               for(i=0;i<r.links.length;i++) {
                   var nextTab = document.createElement('a');
                   nextTab.className = r.links[i].cls;
                   nextTab.innerHTML = r.links[i].title;
                   
                   if(r.links[i].url) {
                     nextTab.href = r.links[i].url;
                     nextTab.target = '_blank';
                   }
                   else {
                     nextTab.href = '#';
                     nextTab.rel = r.links[i].cb;
                     
                     nextTab.onclick = function() { $.f.loadContent(this.rel, '', true); return false; };
                   }

                   lDiv.appendChild(nextTab); 
               }
                 
               n.appendChild(lDiv);
             }
             else {
               if(r.pager) {
                 nDiv = document.createElement('div');
                 nDiv.innerHTML = r.html_content;
                 
                 n.appendChild(nDiv);
                 
                 pDiv = document.createElement('div');
                 pDiv.className = 'pr-srch';
                 
                 if(r.prevargs) {
                   prv = document.createElement('a');
                   prv.className = 'pr-srch-prev';
                   prv.innerHTML = "&lt; Previous Tip";
                   prv.href = '#';
                   prv.onclick = function() {
                     $.f.loadContent(r.pager, r.prevargs, true);
                     return false;
                   };
                 
                   pDiv.appendChild(prv);
                 }
                 
                 if(r.nextargs) {
                   nxt = document.createElement('a');
                   nxt.className = 'pr-srch-next';
                   nxt.innerHTML = "Next Tip &gt;";
                   nxt.href = '#';
                   nxt.onclick = function() {
                     $.f.loadContent(r.pager, r.nextargs, true);
                     return false;
                   };
                 
                   pDiv.appendChild(nxt);
                 }
                 
                 n.appendChild(pDiv);
               }
               else {
                 n.innerHTML = r.html_content;
               }
             }
               
             if(r.follow_page) {
                 var sharetw = document.createElement('a');
                 sharetw.className = 'pr-icbtn pr-ictwt';
                 sharetw.href='#';
                 sharetw.onclick = function() { $.f.loadContent('api/content/liveearth/twitter', '', true); return false; };
                 sharetw.innerHTML = 'Twitter';
                
                 n.appendChild(sharetw);
                
                 var sharefb = document.createElement('a');
                 sharefb.className = 'pr-icbtn pr-icfb';
                 sharefb.href='#';
                 sharefb.onclick = function() { $.f.loadContent('api/content/liveearth/facebook', '', true); return false; };
                 sharefb.innerHTML = 'Facebook';
                  
                 n.appendChild(sharefb);
                 
                 var shareyt = document.createElement('a');
                 shareyt.className = 'pr-icbtn pr-icyt';
                 shareyt.href='#';
                 shareyt.onclick = function() { $.f.loadContent('api/content/liveearth/media', '&videos=1', true); return false; };
                 shareyt.innerHTML = 'YouTube';
                  
                 n.appendChild(shareyt);
                 
                 var sharefl = document.createElement('a');
                 sharefl.className = 'pr-icbtn pr-icfl';
                 sharefl.href='#';
                 sharefl.onclick = function() { $.f.loadContent('api/content/liveearth/media', '&photos=1', true); return false; };
                 sharefl.innerHTML = 'Flickr';
                  
                 n.appendChild(sharefl);
             }
             
             if(r.walk) {
               var wp = document.createElement('p');
               wp.style.marginTop = '10px';
             
               var wReg = document.createElement('a');
               wReg.href = '#';
               wReg.innerHTML = '&gt; REGISTER YOUR SCHOOL';
               wReg.className = 'pr-wlka';
               
               var em_url = $.f.baseUrl + 'frame/any?url=' + escape('http://www.joinliveearth.org/page/s/walking#main') + '&full=1&ref=' + $.f.partnerId;
               wReg.onclick = function() { $.f.showOverlay(em_url); return false; };
               
               wp.appendChild(wReg);
               
               var wLrn = document.createElement('a');
               wLrn.href = '#';
               wLrn.innerHTML = '&gt; LEARN MORE';
               wLrn.style.paddingLeft = '10px';
               wLrn.className = 'pr-wlka';
               
               var lr_url = $.f.baseUrl + 'frame/any?url=' + escape('http://www.akvo.org/blog/?p=618#post-618') + '&full=1&ref=' + $.f.partnerId;
               wLrn.onclick = function() { $.f.showOverlay(lr_url); return false; };
               
               wp.appendChild(wLrn);
               
               n.appendChild(wp);
             }
             
             if(r.give) {
               var dnt = document.createElement('a');
               dnt.href = '#';
               dnt.innerHTML = 'Donate Now';
               dnt.className = 'pr-btn';
               
               var d_url = $.f.baseUrl + 'frame/any?url=' + escape('https://donate.globalwaterchallenge.org/page/contribute/liveearth1') + '&full=1&ref=' + $.f.partnerId;
               dnt.onclick = function() { $.f.showOverlay(d_url); return false; };
               
               n.appendChild(dnt);
             }
           }
           else if(r.type == 'links') {
             if(!r.error) {
               for(i=0;i<r.results.length;i++) {
                 n.appendChild($.f.formatLink(r.results[i], true));
               }
              
               if(!r.front) {
                n.c = document.createElement('div');
                n.c.className = 'pr-srch-nav';
              
                n.p = document.createElement('a');
                n.p.className = 'pr-srch-prev';
                n.p.href = '#';
                
                n.p.onclick = function() {
                  $.f.goBack();
                  return false;
                };
                
                if(r.start != 0) {
                  n.p.innerHTML = '&lt; Previous';
                }
                else {
                  n.p.innerHTML = '&lt; Back';
                }
                 
                 n.c.appendChild(n.p);
             
                 if(!r.end) {
                   n.nxt = document.createElement('a');
                   n.nxt.className = 'pr-srch-next';
                   n.nxt.href = '#';
                   n.nxt.innerHTML = 'Next &gt;';
                   qString = '&start=' + (r.start * 1 + r.limit) + '&max=' + r.max;
                   if(r.query) { qString += '&query=' + escape(r.query); }
                   if(r.ntype) { qString += '&type=' + r.ntype; }
                   if(r.nextargs) { qString += r.nextargs; }
                    
                   n.nxt.onclick = function() {
                     $.f.loadContent(r.nexturl, qString, true);
                     return false;
                   };
                   n.c.appendChild(n.nxt);
                 }
               
                 n.appendChild(n.c);
               }
             }
             else {
               err = document.createElement('p');
               err.innerHTML = 'Your search returned no results.';
               n.appendChild(err);
             }
           }

           $.w.p.dyn.innerHTML = '';
           $.w.p.dyn.appendChild(n);
         },
         runScript : function(url, id) {
           var s = document.createElement('script');
           s.id = id;
           s.type ='text/javascript';
           s.src = url;
           document.getElementsByTagName('body')[0].appendChild(s);
         },
         removeScript : function(id) {
            var s = '';
            if (s = document.getElementById(id)) {
               s.parentNode.removeChild(s);
            }
         }
      };
   }();
   var thisScript = /^https?:\/\/[^\/]*poprule.com\/js\/liveearth.js$/;
   if(typeof window.addEventListener !== 'undefined') {
      window.addEventListener('load', function() { $.f.init(thisScript); }, false);
      window.addEventListener('unload', function() { $.f.leave(); }, false);
      window.addEventListener('resize', function() { $.f.resize(); }, false);
   } else if(typeof window.attachEvent !== 'undefined') {
      window.attachEvent('onload', function() { $.f.init(thisScript); });
      window.attachEvent('onbeforeunload', function() { $.f.leave(); });
      window.attachEvent('onresize', function() { $.f.resize(); }, false);
   }
} )();