// Oprah.com global namespace
var O = window.O || {}, Modal = window.Modal || {};


// Global colors
O.orange = '#FF6900';
O.gray   = '#CCC';


// lazy loading
window.addEvent('domready', function(){
  $$('noscript').each(function(e, count) {
    try {
      var obj  = new Hash(eval('O.' + e.get('title')));
      var config = e.get('params') ? JSON.decode("{" + e.get('params') + "}") : null;
      var elem = new Element('div', { id: e.get('id') }).replaces(e);
      // now we can check and see if object has the autoload method
      if (obj.has('autoLoad')) {
        obj.autoLoad(elem, config);
      }
    } catch(e) {
      //console.info('did not load one of the modules. Err msg: ', e);
    }
  });
  
  $$('a[href^=/ord/send_a_friend]').addEvent('click', function(event){
    event.stop();
    if (O.sender) {
      O.sender.show();
    } else {
      O.sender = new Modal.FormBox({form:this.href});
    }
  });
 
  // auto-load "send to a friend" for ODreamBoard
  if ($('sendToaFriendID')) {
    var path = window.top.location.href;
    if (path.contains('send=true')) {
        if (O.sender) {
          O.sender.show();
        } else {
          O.sender = new Modal.FormBox({form: '/ord/send_a_friend.html'});
        }
    }
  }
  
	// Internal Promo Ad Rotation
	if ($('intpromoad')){
	var promo_timer = (function(){
	// grab list
	var list = document.getElementById('intpromoad').getElementsByTagName('li');
	// set inital variables
	var CURRENT = 0, TOTAL = list.length - 1;
	// init first element's display to block
	list[CURRENT].style.display = 'block';
	// start interval [currently set to 1250, or 1.25 seconds]
	return window.setInterval(function(){
	// hide currently visible
	list[CURRENT].style.display = 'none';
	// determine if current should be incremented or reset
	CURRENT = (CURRENT == TOTAL) ? 0 : CURRENT + 1;
	// show new 'current' panel
	list[CURRENT].style.display = 'block';
	}, 6000);
	})();
	}
});

Element.implement({
  bindToLink: function(link) {
    if (link == null) return;
    var page = link.getProperty('href');
		var targ = link.getProperty('target');
    this.addEvents({
      'click'    : function() { if (targ == '_blank') window.open(page); else window.location.assign(page) },
      'mouseenter': function() { window.status = 'Go to "' + page + '"'},
      'mouseleave': function() { window.status = '' }
    });
  }
});

O.Observable = new Class({
  update: function(current, teardown, total){
    this[this.options.animate](current, teardown, total);
  }      
});

O.Counter = new Class({
  Extends: O.Observable,
  initialize: function(container){
    this.counter = new Element('div', {
      'class': 'counter',
      text: '1 of ??'
    }).inject(container);
  },
  update: function(current, teardown){
    this.counter.set('text', (current + 1) + ' of ' + total).tween('color', [O.orange, O.gray]);
  }
});

O.Sequence = {
  marked: 1,
  list_items: [],
  observers: [],
  initialize: function(size) {
    this.list_size = size;
    this.list = new Element('ul', {
      'class': 'paginator'
    });
  },
  attach: function(observer){
   this.observers.push(observer);
  },
  build: function(){
   this.list.grab(this.listItem('-', 'first-child'));
   for (var i= 1; i <= this.list_size; ++i) {
     this.list_items[i] = this.listItem(i).inject(this.list);
   };
   this.list.grab(this.listItem('+', 'last-child'));
   return this.list;  
  },
  highlight: function(current, force_refresh){
    var mark = current > this.list_size ? 1 : current == 0 ? this.list_size : current;
    this.list_items[this.marked].removeClass('active');
    this.list_items[mark].addClass('active');
    if (mark != this.marked || force_refresh) {
      this.notify(current, this.marked);
      this.marked = mark;
    }
  },
  listItem: function(index, cname) {
    return new Element('li', {
       html: '&bull; ' + index,
       title: index,
       'class': cname,
       events: {
         mouseup: function(event){
           $clear(this.intervalID);
           var str= event.target.get('title')
           var idx = Number(str)
           idx = isNaN(idx) ? eval(this.marked + str + 1) : idx;
           this.highlight(idx);
         }.bindWithEvent(this),
         mouseenter: function(){
           this.addClass('active');
         },
         mouseleave: function(idx){
           if (this.marked != idx && idx > 0) {
             this.list_items[idx].removeClass('active');
           }
         }.bind(this, index)
       }
     });
  },
  notify: function(index, current) {
    this.observers.each(function(observer) {
      observer.update(index, current, this.list_size);
    }, this);
  },
  autorun: function(value){
    this.highlight(this.marked + 1);
  }
};

O.Carousel = new Class({
  slides: [],
  sequencer: O.Sequence,
  Implements: [Options, O.Observable],
  options: {
    increment:1,    
    startIndex: 1,
    autoPlay: 0,
    animate: 'slidePanel'
  },
  initialize: function(container, input_file_path, module, opts){
    this.container = $(container);
    this.setOptions(opts);
    this.module = module;
    this.request = new Request.JSON({
      url: input_file_path,
      onSuccess: O[this.module].prepare.bind(this),
      onFailure:  O.Exception.xhr.bind(this.container)
    }).get();
  },
  flip: function(position, set){
    if(set === false) return;
    this.container.setStyle('left', position);
    var cursor = 0, cutoff = this.options.increment;    
    if (set) cursor = cutoff, cutoff = this.slides.length;
    do {
      this.container.grab(this.slides[cursor].dispose());
    } while (++cursor < cutoff);
  },
  slidePanel: function(current, teardown){
    var flipped = false;
    var position = this.container.getStyle('left').toInt();
    
    if (teardown < current) {
      var slideX = ((teardown - current) * this.panelWidth) + position;
      if (this.turns == teardown) {
        var slideX = ((teardown - current) * this.panelWidth);
        this.flip(0);
        var moveVal = 0;
        flipped = true; 
      };
    } else if (teardown > current) {
      var slideX = 0;
      if (current == 0) {
        this.flip(-this.panelWidth);
        flipped = true;
        var moveVal = -this.panelWidth;
      }
    }
    
    var effect = new Fx.Tween(this.container, {duration: 750, property:'left', onComplete:this.flip.bind(this,[moveVal,flipped])});
    effect.start(slideX);
  },
  fadePanel: function(current, teardown, total){
    current--, teardown--, total--;
    
    current = current > total ? 0 : current < 0 ? total : current;
    if (current != teardown) {
      this.slides[teardown].setStyle('display', 'none');
    }
    
    if (Browser.Engine.trident) {
      this.slides[current].setStyle('display', 'block');
    } else {
      this.slides[current].setStyles({display: 'block', opacity: 0}).fade('in');
    }
  }
});

/*
  TODO refactor this entire class.
*/

var SemiScroller = new Class({
  position:0,
  initialize: function(elem){
    this.viewer = $(elem);
    var morelist = this.viewer.getElements('li');
    if (morelist.length <= 20) return;
    var list_len = Math.floor(morelist.length / 20);
    
    
    this.scrollamt = (morelist[0].getSize().x + 5) * 2;
    this.viewer.getElement('ul').setStyle('width',  list_len * this.scrollamt  + (this.scrollamt  /2));
    
    this.scrollFx = new Fx.Scroll(this.viewer, {
        link:'chain',
        duration:500,
        transition: Fx.Transitions.Circ.easeOut
    }).start(0, 0);
    
    this.viewer.getParent('div').grab(this.buildScrollbar(), 'top');
    this.slider = new Slider(this.track, this.knob, {
        steps: list_len,
        snap:true,
        offset:1,
        onChange: function(step){
         this.knob.set('text', Number(step) + 1);
        },
        onComplete: function(step){
          this.position = Number(step);
          this.scrollFx.start(this.position * this.scrollamt, 0);
        }.bind(this)
    });
    
  },
  buildScrollbar: function(){
    this.scrollbar = new Element('div', {
      'class':'more_in_scrollbar'
    });
    this.track = new Element('div', {
      'class':'track'
    });
    this.knob = new Element('div', {
      'class':'knob',
      'text':1
    });
    this.back_button = new Element('button', {
      'class': 'back directional',
      'text': '-',
      'title':'back',
      'events': {
        click: function(event){
          this.slider.set(this.position - 1);   
        }.bind(this)
      }
    });
    this.next_button = new Element('button', {
      'class': 'next directional',
      'text': '-',
      'title':'next',
      'events': {
        click: function(event){
          this.slider.set(this.position + 1);   
        }.bind(this)
      }
    });
    return this.scrollbar.adopt(this.back_button, this.track.grab(this.knob), this.next_button);
  }
});


Modal.FormBox = new Class({
  form: null,
  container: null,
  overlay: null,
  options: {
    form: 'send_a_friend.jsp',
    share: (window.location.href.contains('send=true') ? window.location.href.split('?')[0] : window.location.href),
    css_class: 'saf'
  },
  Implements: Options,
  initialize: function(opts) {
    this.setOptions(opts);
    this.overlay = new Modal.Overlay;
    this.container = new Element('div', {
      'html':'<img src="http://static.oprah.com/images/global/spinner.gif" />',
      'styles': {
        'margin-top':window.getScroll().y + 150
      },
      'class': this.options.css_class
    });
    
    // grab our form include
    this.request = new Request({
      url: this.options.form,
      onSuccess: this.build.bind(this),
      onFailure: function(){
        this.container.set('html', '<p>Sorry, we are experiencing difficulties with this module. Please try again soon.</p>').grab(this.closeButton('Close'));
      }.bind(this)
    }).get();
    
    this.container.inject(window.overlay);
  },
  build: function(responseText){
    this.container.set('html', responseText);
    //this.container.getElement('fieldset').setStyle('opacity',0).tween('opacity', 0, 1);
    this.form = this.container.getElement('form');
    
    this.form.grab(this.closeButton('Cancel'));
    
    this.form.set('send', {
      url:this.form.getProperty('action'),
      method:'post',
      onSuccess: this.success.bind(this),
      onFailure: this.failure.bind(this)
    });
    
    this.form.addEvent('submit', this.send.bind(this));
    
    this.form[1].focus();
    /*
      TODO move tooltip into a better, more globally useful spot
    */
    var tip = new Tips({
      offsets: { x:10, y:-50 },
      fixed:true,
      className: 'tooltip'
    });
    tip.attach($('quicktip'));
  },
  send: function(event){
    event.stop();
    // if validated, XHR request.
    if (this.validate(this.form.getElements('input[type=text]'))) {
      this.form['par_page'].value = this.options.share;
      this.form.getElement('button').set('html', '<img src="http://static.oprah.com/images/global/spinner.gif" />');
      this.form.send();
    }
  },
  validate: function(inputs){
    var valid = true;
    inputs.each(function(input){
      if (input.hasClass('error')) {
        input.removeClass('error').getPrevious('em').dispose();
      };
      Validator.types.each(function(type) {
        if (input.hasClass(type)) {
          if(!Validator[type](input).valid) {
            valid = false;
            input.addClass('error');
            var err_msg  = new Element('em', {html: Validator[type](input).field.msg });
            err_msg.inject(input.getPrevious('label'), 'before');
          }
        };
      }, this);
    }, this);
    return valid;
  },
  success: function(responseText){
    s.linkTrackVars="pageName,prop15";
    s.prop15 = window.location;
    s.tl(true, 'o', 'Sent to a Friend');
    this.container.getElement('fieldset').style.display = 'none';
    new Element('div', {html:responseText}).grab(this.closeButton('Close',true)).inject(this.container);
  },
  failure: function(xhr){
    new Element('div', {html:xhr.responseText}).inject(this.container, 'top');
    this.form.getElement('button').set('html', 'Send');
  },
  reset: function(){
    this.form.getElement('button').set('html', 'Send');
    this.container.getElement('fieldset').style.display = 'block';
    this.container.getElement('div').dispose();
  },
  show: function(){
    this.overlay.show();
    this.container.setStyles({
      'display':'block',
      'margin-top':window.getScroll().y + 100
    });
    this.form[1].focus();
  },
  closeButton: function(text, reset){
    return new Element('button', {
       'html': text,
       'events': {
         click: function(event){
           event.stop();
           if (reset) this.reset();
           this.overlay.hide();
           this.container.setStyle('display', 'none');
         }.bind(this)
       }
    });
  }
});


Modal.Overlay = new Class({
  initialize: function(){
    if ($type(window.overlay)) {
      this.show();
    } else {
      this.make();
    }
    return this;
  },
  make: function(){
    var win = window.getScrollSize();
    // we need to be a lot more aware of our page dims before we go down this road...
    //document.body.style.overflow = 'hidden';
    window.overlay = new Element('div', {
      'class':'overlay',
      'styles': {
        'z-index':1500,
        'position':'absolute',
        'top':0,
        'left':0,
        'height':win.y,
        'width':'100%'
      }
    }).inject(document.body);
    // this is not ie friendly <-> if (pin && !browser.trident)
    // document.body.style.overflow = 'hidden';
  },
  show: function(){
    //document.body.style.overflow = 'hidden';
    window.overlay.setStyles({'display':'block'});
  },
  hide: function(){
    window.overlay.style.display = 'none';
    //document.body.style.overflow = 'auto';
  }
});



var Validator = {
  types: ['required', 'email', 'alpha', 'alpha_num'],
  required: function(elem){
    return {valid: elem.value.length != 0, field: { msg: "*Required", input: elem }};
  },
  email: function(elem){
    if(!this.required(elem).valid) return {valid: true };
    var ret;
    elem.value.split(/,\s*/).each(function(e) {
      /*
        TODO clean up syntax
      */
      if (!/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(e)) {
        ret = false;
        return;
      } else {
        ret = true
      }
    });
    return {valid: ret, field: { msg: "*E-mail not valid", input: elem }};
  },
  alpha: function(elem){
    if(!this.required(elem).valid) return {valid: true };
    return {valid: /^[a-zA-Z]+$/.test(elem.value), field: { msg: "Use only letters on " + elem.title, input: elem}};
  },
  alpha_num: function(elem) {
    if(!this.required(elem).valid) return {valid: true };
    return {valid: /^[a-zA-Z0-9\-\.\?\!\s\,*]+$/.test(elem.value), field: { msg: "Use only letters &amp; numbers in " + elem.title, input: elem}};
  }
};

O.hearst = {
  autoLoad: function(elem, opts){
    var is_embed = (Metas['contentsource'] == 'omag') ? (Metas['sectionname'] != 'omagazine') : false ;
    var unviewed = ! Cookie.read('subscriptionAdViewed');
    
    //console.log(Cookie.read('ADC'));
    if (is_embed && unviewed) {
      O.hearst.placeHearstAd(elem);
    } else {
      O.hearst.placeAd(elem, opts.adType);
    };
  },
  placeAd: function(elem, pos){
    var adv = advert[pos.toLowerCase()];
    var ifm = new IFrame({
      src: OAS_AD(pos, true),
      ad: true,
      frameBorder:0,
      height:adv.y,
      width:adv.x,
      styles: {
        overflow: 'hidden'
      }
    }).inject(elem);
    //Cookie.write('subscriptionAdViewed', true);
  },
  placeHearstAd: function(elem){
    //alert('place hearst ad: need to figure out if we need to inject this into a proxy html page, or straight up in our I frame.');
    //iframe.setProperty('src', null);
  }
};

O.feature = {
  autoLoad: function(elem, opts) {
    var carousel = new O.Carousel(elem, opts.url, 'feature', {animate: 'fadePanel', autoPlay:opts.playTime, pageType: opts.pageType});
  },
  prepare: function(responseJSON) {
    responseJSON[this.options.pageType].mainFeatureComponent.each(function(slide,index) {
      this.slides[index] = new Element('div', {
        html: '<h2 class="orange">' + slide.featureTitle + '</h2>',
        styles: {
          display: 'none'
        }
      }).inject(this.container);
      var img = new Asset.image(slide.imageFeatureOne.mainImage, {
        'alt': slide.imageFeatureOne.mainImageAltTag,
        'class': 'link',
        onload: function(e) {
          var effect = new Fx.Tween(e, {duration:1000, property:'opacity'}).start(0, 1);
        },
        onerror: function(img) {
          img.setProperty('src', 'http://static.oprah.com/images/global/global_search_towsnoimage_90x69.jpg').setStyle('visibility', 'visible');
        }
      });
      
      var p   = new Element('p', {html: slide.imageFeatureOne.promoText });
      var ul  = new Element('ul');
      var cite = new Element('cite', {
        html: slide.imageFeatureOne.photoCredit,
        'class': 'photocredit'
      });
      
      var links = $type(slide.imageFeatureOne.relatedLink) == 'string' ? [slide.imageFeatureOne.relatedLink] : slide.imageFeatureOne.relatedLink;
      
      if($type(links) == 'array') {
        links.each(function(e) {
          new Element('li', {
            html: e
          }).inject(ul);
        });
      }
      
      this.slides[index].adopt([img,p,ul,cite]);
      img.bindToLink(img.getPrevious().getFirst('a'));
    },this);
    
    this.sequencer.initialize(responseJSON[this.options.pageType].mainFeatureComponent.length);
    this.sequencer.build().inject(this.container, 'top');
    this.sequencer.attach(this);
    this.sequencer.highlight(this.options.startIndex, true);
    if (this.options.autoPlay > 0) {
      this.sequencer.intervalID = this.sequencer.autorun.periodical(this.options.autoPlay, this.sequencer);
    }
  }
};

O.topic = {
  autoLoad: function(elem, opts) {
    var carousel = new O.Carousel(elem, opts.url, 'topic', {increment:opts.panels, pageType: opts.pageType});
    carousel.sequencer.attach(carousel);
  },
  prepare: function(responseJSON) {
    this.container.getParent().grab(new Element('h2', {'class':'modhd1','html':responseJSON[this.options.pageType].globalPromoCarousel.carouselTitle}), 'top');
    responseJSON[this.options.pageType].globalPromoCarousel.carouselContents.each(function(panel, index) {
      this.slides[index] = new Element('div',{
        'html': panel.contentTitleLink,
        'class':(index + 1) % this.options.increment != 0 ? null : 'terminal'
      });
      var header = new Element('h3', {html: panel.header})
      var img = new Asset.image(panel.mainImage, {
        'alt': panel.mainImageAltTag,
        'class':'link',
        onload: function(e) {
          var effect = new Fx.Tween(e, {duration:1000, property:'opacity'}).start(0, 1);
        },
        onerror: function(img) {
          img.setProperty('src', 'http://static.oprah.com/images/global/global_search_towsnoimage_90x69.jpg').setStyle('visibility', 'visible');
        }
      });
      this.slides[index].grab(img, 'top');
      this.slides[index].grab(header, 'top');
      img.bindToLink(img.getNext('a'));
    }, this);
    
    // first things first
    this.container.adopt(this.slides);
    
    
    var total = this.slides.length;
    this.panelWidth = this.slides[0].getSize().x;

    this.container.setStyle('width', this.panelWidth * total);
    
    
    if (total <= this.options.increment) return;

    if ((this.options.increment * 2) > total) {
      this.options.increment = total % this.options.increment;
      this.turns = 2;
    } else {
      this.turns = Math.floor(total / this.options.increment);
    }
    
    this.panelWidth *= this.options.increment;
    this.sequencer.initialize(this.turns);
    var frame = this.container.getParent().setStyles({overflow:'hidden',position:'relative'});

    this.sequencer.build().inject(frame, 'top');
    this.sequencer.highlight(this.options.startIndex);
  }
};

O.minitwix = {
  autoLoad: function(elem, opts) {
    this.nav = $$('#minitwix_cal a');
    this.active = $('minitwix_init');
    this.twix = new Swiff('http://static.oprah.com/flash/player/promo_player.swf', {
      id: 'minitwix_swf',
      width: '100%',
      height: '100%',
      container: elem,
      params: {
        wmode: 'transparent',
        allowfullscreen: 'true',
        allowScriptAccess: 'always'
      },
      vars: {
        showXML:this.active.getProperty('href'),
        sAccount: s_account,
        sMovieID: 'minitwix',
        sPageName: s.pageName,
        sPageURL: document.URL
      },
      callBacks: {
        load: this.initNav()
      }
    });
  },
  initNav: function () {
    this.nav.each(function(e,i) {
      e.addEvent('click', function(event) {
        event.stop();
        this.active.removeClass('today');
        e.addClass('today');
        this.active = e;

        //Swiff.remote(this.twix, 'loadShowInfo', e.getProperty('href'));
        window.setMiniTwixData(e.getProperty('href'));
        
        new Request({
          method: 'get',
          url: 'minitwix_servlet.jsp?date='+e.get('name'),
          onSuccess: function(responseText) {
            $('replace_minitwix').set('html', responseText);
            $('minitwix_day').set('text', e.get('rel'));
          }
        }).send();
      }.bind(this));
    }, this);
  }
};

function getFlashMovie(objectId) {
  return (window[objectId]) ? window[objectId] : document[objectId];
}
function setMiniTwixData(url) {
  getFlashMovie("minitwix_swf").loadShowInfo(url);
}


function buildComments(responseJSON) {
  // create and build elements
  var container = $('comments');
  var comments = responseJSON.comments;
  var abuse = getCookie(usernameCookieName) || false;
  comments.each(function(comment){
    var div = new Element('div');
    var body = new Element('div', {
      'class':'comment-content',
      html: '<p>' + comment.body + '</p>'
    });
    var member_info = new Element('div', {'class':'member_info'});
    var img = new Asset.image('/community/' + comment.img);
    var level = new Asset.image('/community/' + comment.level, {
      'class': 'status'
    });
    var profile = new Element('a', {
      'class': 'profile',
      'href': '/community/' + comment.profile,
      'text': comment.username
    }).grab(img, 'top');

    member_info.adopt(profile, level);
    var posted = new Element('span', {
      'text':comment.time
    });

    if (abuse && abuse != comment.username) {
      posted.grab(new Element('a', {
        title:'report abuse',
        html: ' <img src="http://static.oprah.com/images/global/myoprah_icons_reportabuse_15x15.gif"/>',
        href: '/community/message-abuse!input.jspa?messageID='+comment.id+'&returnURL=' + window.location
      }));
    }
    div.adopt(member_info,body,posted);
    container.grab(div);
  });

  if (comments.length > 4) {
    	if (window.location.href.contains('recipe') ) {
      container.grab(new Element('a', {
        text: 'VIEW ALL REVIEWS',
        'class': 'fullpagelink',
        href: window.location.protocol + '//' + window.location.host + '/comments' + window.location.pathname.replace(/\/[0-9]+$/, '')
      })); 
    } else {
    	container.grab(new Element('a', {
        text: 'VIEW ALL COMMENTS',
        'class': 'fullpagelink',
        href: window.location.protocol + '//' + window.location.host + '/comments' + window.location.pathname.replace(/\/[0-9]+$/, '')
      }));
    }
  };
}


function postComment(event) {
  event.stop();
  this.set('send', {
    onSuccess: function(){
      this.message.value = '';
    }.bind(this),
    onFailure: function(){
      document.location = '/mbr/mbr_login.jsp?redirectURL=' + escape(document.location);
    }
  });
  this.message.value = this.message.value.replace(/^\s+|\s+$/g, '');
  if (this.message.value.length == 0) {
    alert('The text field is empty. Please enter a comment.');
  } else if (this.message.value.length > 1500) {
    alert('Character limit exceeded. Please revise post.');
  } else {
    this.send();
  }
};


/* 
Function to open Move Player Popup 
*/
function popMovePlayer(url,support) {
if ((screen.width >=1024) && (screen.height>=768)) {
newwindow=window.open(url,'name','width=980,height=665,resizable=no,location=no,scrollbars=no,toolbar=no');
window.name='oprah_main';
} else {
//send them to support page
window.document.location=support;
}
}

/* 
Function to open DC Map Popup 
*/
function popupDCPlayer(url) {
newwindow=window.open(url,'name','width=980,height=665,resizable=no,location=no,scrollbars=no,toolbar=no');
newwindow.document.close();
window.name='oprah_main';
}

/* 
Function to open Interactive Biography Popup 
*/
function popBio(url) {
newwindow=window.open(url,'name','toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=640,height=610');
newwindow.document.close();
window.name='oprah_main';
}

/* 
Function to open Printable Page Popup 
*/
function popPrintable(url) {
newwindow=window.open(url,'name','width=780,height=674,toolbar=yes,menubar=yes,status=no,locationbar=no,scrollbars=yes,resizable=yes,top=100,left=100');
newwindow.document.close();
window.name='oprah_main';
}

/*
Function to open slidepopup.jsp Popup
*/
function popSlide(url) {
newwindow=window.open(url,'slidepopup','height=600,width=810,scrollbars=no,resizable=no,toolbar=no,location=no,directories=no,menubar=no');
newwindow.document.close();
window.name='oprah_main';
}

/*
Generic Popup Trigger
*/
function triggerPopupPage(url, w, h) {
	newwindow=window.open(url,'name','width='+w+',height='+h+',scrollbars=no,resizable=no,toolbar=no,status=no,location=no,directories=no,menubar=no');
	newwindow.document.close();
	window.name='oprah_main';
}

/* 
Function to open Family Fun Calendar Popup 
*/
function popFamFunCal(url) {
newwindow=window.open(url,'name','width=1070,height=905,resizable=yes,location=no,scrollbars=yes,toolbar=no');
window.name='oprah_main';
}

O.Exception = {
  xhr: function(request) {
    this.set('html', '<p>There was a error loading this module. We are working to correct the problem</p>');
  },
  img: false
};

Object.prototype.toString = function(){
  return '';
}

var drop = {
  mouseenter: function() {
    $clear(this.retrieve('delay', 0));
    this.addClass('over');
  },
  mouseleave: function() {
    this.store('delay', this.removeClass.delay(250, this, 'over'));
  }
};

var sharePage = function(link) {
  link.addEvent('click', function(event){
    event.stop();
    s.linkTrackVars="pageName,prop15";
    s.prop15 = window.location;
    s.tl(true, 'o', link.get('text'));
    window.open(this.href + window.location.href);
  });
};


/*
PNG Capture and Fix for inline images (specifically ad placements)
*/
if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
document.writeln('<style type="text/css">#page_tools_ad img,#page_tools_ad2 img,#package_ad img{visibility:hidden;}</style>');
  window.attachEvent("onload", fnLoadPngs);
}

function fnLoadPngs() {
  var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
  var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);

  for (var i = document.images.length - 1, img = null; (img = document.images[i]); i--) {
    if (itsAllGood && img.src.match(/\.png$/i) != null) {
      var src = img.src;
      var div = document.createElement("DIV");
      div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizing='scale')"
      div.style.width = img.width + "px";
      div.style.height = img.height + "px";
      img.replaceNode(div);
    }
    img.style.visibility = "visible";
  }
}

/*
Google Analytics
*/
   var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
   document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

   var trackerID = (("www.oprah.com" == document.location.hostname) ? "UA-8224552-1" : ("static.oprah.com" == document.location.hostname) ? "UA-8224552-2" : ("images.oprah.com" == document.location.hostname) ? "UA-8224552-3" : ("media.oprah.com" == document.location.hostname) ? "UA-8224552-4" : "");
       
   try {
      var pageTracker = _gat._getTracker(trackerID);
      pageTracker._trackPageview();
      }catch(err) {}
