/**
 * 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,
         actionIds: [],
         curAction: 0,
         windowHeight: 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 = {};
                  }
                  
                  $.a.client = 'imc';
                  
                  // 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://dev-static.poprule.com/';
                  }
                  
                  if($.a.brand == 'thin') {
                    $.f.requestStylesheet('imc/thin.css');
                  }
                  else {
                    $.f.requestStylesheet('imc/main.css');
                  }
  
                  $.f.buildStructure();
                  
                  theScripts[i].parentNode.insertBefore($.c, theScripts[i]);
                  theScripts[i].parentNode.removeChild(theScripts[i]);
                  break;
               }
            }
         },
         leave : function() {
           $.f.loadContent('report_engage', '&source=widget&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;
           
           // Overlay
           if($.a.brand == 'thin') { 
             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;
             };
             
             var dblg = document.createElement('a');
             dblg.className = 'pr-ovdb';
             dblg.href = '#';
             dblg.innerHTML = 'Doctor Blogs &raquo;';
             dblg.onclick = function() {
                    $.f.hideOverlay();
                    $.f.loadContent('api/content/imc/doctors', '', true);
                    return false;
             };
                
             $.w.idivi.appendChild(dblg);
           
             $.w.idivii.appendChild($.w.icl);
           
             $.w.idiv.ttl = document.createElement('div');
             $.w.idiv.ttl.className = 'pr-ttl';
             $.w.idiv.ttl.innerHTML = 'INTERNATIONAL MEDICAL CORPS';
  
             $.w.idivii.appendChild($.w.idiv.ttl);
           
             $.w.vidiv = document.createElement('div');
           
             $.w.idivii.appendChild($.w.vidiv);

             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/imc/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/imc', '&configure=1&issue=haiti', true);
            
           $.w.appendChild($.w.p);
            
           // Create footer
           $.w.p.foot = document.createElement('div');
           $.w.p.foot.className = 'pr-ftr';
           
           // 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.p.appendChild($.w.p.foot);
           
           $.c.appendChild($.w);
         },
         goBack : function(home) {
           if($.f.cachePos != 0) {
             if(home) {
               $.f.cachePos = 0;
             }
             else {
               $.f.cachePos--;
             }
             
             $.f.renderResult($.f.pageCache[$.f.cacheOrder[$.f.cachePos]]);
           }
         },
         loadContent : function(src, args, refresh) {     
           var url = $.f.baseUrl + src + '?key=' + $.a.client + args;
           
           if($.f.partnerId) { 
             url += '&ref=' + $.f.partnerId;
           }
           else { 
             url += '&t=' + escape(document.title) + '&ref=' + escape(location.href.replace(/\?.*|#/,'')); 
           }
           
           $.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;
             
             // Log unique click
             if($.f.partnerId) {
               $.f.clickCount++;
               
               // Is this the initial click?
               if($.f.clickCount == 1) { 
                 url += '&initial=1';
               }
             }
             
             $.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.brand == 'thin') {
               url += '&thin=1';
             }
             
             url += '&callback=' + id;
             
             $.f.runScript(url, id);
           }
         },
         showOverlay: function() {
           $.w.idiv.style.left = (($.f.windowWidth - 500) / 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 - 500) / 2) + "px";

           //$.w.shade.style.height = $.f.windowHeight + 'px';
         },
         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['overlay']) {
               l.onclick = function() {
                 var c = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/' + o['overlay'] + '&hl=en_US&fs=1&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + o['overlay'] + '&hl=en_US&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
                 c += '<a class="pr-twt" style="margin:1px 3px; text-decoration: none;" target="_blank" href="' + $.f.baseUrl + 'share/any/twitter/0/widget?t=' + escape(o['title']) + '&u=' + escape('http://youtu.be/' + o['overlay']) + '&ref=' + $.f.partnerId + '&key=imc">Tweet</a>';
                 c += '<a class="pr-fb" style="margin:1px 3px; text-decoration: none;" target="_blank" href="' + $.f.baseUrl + 'share/any/facebook/0/widget?t=' + escape(o['title']) + '&u=' + escape('http://youtu.be/' + o['overlay']) + '&ref=' + $.f.partnerId + '&key=imc">Share</a>';
                 $.w.vidiv.innerHTML = c;
                  
                 $.f.showOverlay();
                  
                 return false;
               }
             }
             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;
         },
         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';
         },
         renderResult: function(r) {
            if(!$.f.partnerId) {
              $.f.partnerId = r.pid;
            }
            
            if(r.masthead) {
              $.w.p.m.href = r.masthead;
            }
            
            if(r.tabs) {
             for(i=0;i<r.tabs.length;i++) {
               if(!($.a.brand == 'thin' && i == 2)) {
                 var nextTab = document.createElement('a');
                 nextTab.className = 'pr-tab';
               
                 if(i==0) {
                   nextTab.className += ' pr-tab-on';
                 }
               
                 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); 
               }
             }
           }
           
            var a;
            n = document.createElement('div');
            
            if(r.type == 'html') {
              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/imc/follow', '&twitter=1', true); return false; };
                sharetw.innerHTML = 'Follow Us on Twitter';
                
                n.appendChild(sharetw);
                
                var sharefb = document.createElement('a');
                sharefb.className = 'pr-icbtn pr-icfb';
                sharefb.href='#';
                if($.a.brand == 'thin') {
                  sharefb.onclick = function() { $.f.loadContent('api/content/imc/follow', '&fb=2', true); return false; };
                }
                else {
                  sharefb.onclick = function() { $.f.loadContent('api/content/imc/follow', '&fb=1', true); return false; };
                }
                sharefb.innerHTML = 'Become a Fan on Facebook';
                  
                n.appendChild(sharefb);
              }
              
              if(r.share_page) {
                var shembed = document.createElement('a');
                shembed.className = 'pr-icbtn pr-icemb';
                shembed.href='#';
                shembed.onclick = function() { $.f.loadContent('api/content/imc/embed', '', true); return false; };
                shembed.innerHTML = 'Put this Action Widget on your website or blog';
                  
                n.appendChild(shembed);
              }
            }
            else if(r.type == 'links') {
              if(!r.error) {
                hone = document.createElement('h1');
                hone.innerHTML = 'Haiti Earthquake Media';
                if($.a.brand == 'thin') {
                  hone.style.fontSize = '13px';
                }
                else {
                  hone.style.fontSize = '15px';
                }
                hone.style.margin = '0 0 2px 0';
                n.appendChild(hone);

                for(i=0;i<r.results.length;i++) {
                  n.appendChild($.f.formatLink(r.results[i], true));
                }
              }
              else {
                err = document.createElement('p');
                err.innerHTML = 'Your search returned no results.';
                n.appendChild(err);
              }
            }
            else if(r.type == 'player') {
              n.bdy = document.createElement('div');
              n.bdy.className = 'pr-fvid';
              
              n.bdy.style.background = 'url("' + r.vid_img + '") center center no-repeat';
              
              n.inr = document.createElement('div');
              n.inr.className = 'pr-fvid-in';
              
              n.inrt = document.createElement('h1');
              n.inrt.innerHTML = r.vid_title;
              
              n.inr.appendChild(n.inrt);
              
              n.inrh = document.createElement('h2');
              n.inrh.innerHTML = 'Play. Share. Give.';
              
              n.inr.appendChild(n.inrh);
              
              n.ply = document.createElement('a');
              n.ply.className = 'pr-btn';
              n.ply.innerHTML = 'Play Video';
              n.ply.href = '#';
              if($.a.brand == 'thin') {
                n.ply.onclick = function() {
                  var c = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/' + r.vid_url + '&hl=en_US&fs=1&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + r.vid_url + '&hl=en_US&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
                  c += '<a class="pr-twt" style="margin:1px 3px; text-decoration: none;" target="_blank" href="' + $.f.baseUrl + 'share/any/twitter/0/widget?t=' + escape(r.vid_title) + '&u=' + escape('http://youtu.be/' + r.vid_url) + '&ref=' + $.f.partnerId + '&key=imc">Tweet</a>';
                  c += '<a class="pr-fb" style="margin:1px 3px; text-decoration: none;" target="_blank" href="' + $.f.baseUrl + 'share/any/facebook/0/widget?t=' + escape(r.vid_title) + '&u=' + escape('http://youtu.be/' + r.vid_url) + '&ref=' + $.f.partnerId + '&key=imc">Share</a>';
                  $.w.vidiv.innerHTML = c;
                  
                  $.f.showOverlay();
                  
                  return false;
                };
              }
              else {
                n.ply.onclick = function() {
                  $.f.loadContent('api/youtube/' + r.vid_url, '&width=294&height=175&autoplay=1&share=1&t=' + escape(r.vid_title), true);
                  return false;
                };
              }
              
              n.inr.appendChild(n.ply);
              
              if($.a.brand == 'thin') {
                n.dblg = document.createElement('a');
                n.dblg.className = 'pr-dblg';
                n.dblg.href = '#';
                n.dblg.innerHTML = 'Doctor Blogs &raquo;';
                n.dblg.onclick = function() {
                  $.f.loadContent('api/content/imc/doctors', '', true);
                  return false;
                };
                
                n.inr.appendChild(n.dblg);
              }
 
              n.inrp = document.createElement('p');
              n.inrp.innerHTML = r.vid_sub;
              
              n.inr.appendChild(n.inrp);
              
              n.twt = document.createElement('a');
              n.twt.className = 'pr-twt';
              n.twt.innerHTML = 'Tweet';
              n.twt.href = $.f.baseUrl + 'share/any/twitter/0?ref=' + $.f.partnerId + '&source=widget&key=' + $.a.client + '&u=' + escape('http://youtu.be/' + r.vid_url) + '&t=' + escape(r.vid_title);
              n.twt.target = '_blank';

              n.inr.appendChild(n.twt);
              
              n.fb = document.createElement('a');
              n.fb.className = 'pr-fb';
              n.fb.innerHTML = 'Share';
              n.fb.href = $.f.baseUrl + 'share/any/facebook/0?ref=' + $.f.partnerId + '&source=widget&key=' + $.a.client + '&u=' + escape('http://youtu.be/' + r.vid_url) + '&t=' + escape(r.vid_title);
              n.fb.target = '_blank';
                
              n.inr.appendChild(n.fb);
              
              n.bdy.appendChild(n.inr);
              
              n.appendChild(n.bdy);
            }
            
            if(r.nexturl) {
                  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; Prev';
                  }
                  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);
            }
            
            if(r.flag == 'video') {
              n.db = document.createElement('a');
              n.db.className = 'pr-dbs';
              n.db.innerHTML = "Doctor Blogs";
              
              n.db.href = '#';
              n.db.onclick = function() {
                $.f.loadContent('api/content/imc/doctors', '', true);
                return false;
              };
              
              n.appendChild(n.db);
            
              n.mr = document.createElement('a');
              n.mr.className = 'pr-mre';
                
              n.mr.innerHTML = 'More &raquo;';

              n.mr.href = '#';
              n.mr.onclick = function() {
                $.f.loadContent('api/content/imc/media', '&mtype=video', true);
                return false;
              };
      
              n.appendChild(n.mr);
            }
            
            $.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\/imc.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);
   }
} )();