function anyPopup(url,h,w){window.open(url,"TMZ","scrollbars=yes,location=no,directories=no,height="+h+",width="+w+",menubar=no");}
function flagComment(commentId, domId, url) {}
String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
String.prototype.titleize = function() {
  var r = new Array();
  var words = this.split('_');
  for(var i = 0; i < words.length; i++) {
    r.push(words[i].capitalize());
  }
  return r.join(' ');
}
String.prototype.template = function (o) {
  return this.replace(/{([^{}]*)}/g,
    function (a, b) {
      var r = o[b];
      if(!r) return "";
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    }
  );
};
/*
 * jqDnR - Minimalistic Drag'n'Resize for jQuery.
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * $Version: 2007.08.19 +r2
 */
/* modified 2009.10.29 by Pete to support our scrollbar as lightly as possible */
(function($){
$.fn.jqDrag=function(h){return i(this,h,'d');};
$.fn.jqResize=function(h){return i(this,h,'r');};
$.jqDnR={dnr:{},e:0,
drag:function(v){
 if(M.k == 'd') {
    //E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY});
    /* added by Pete */
    var rangeMin = 11;
    var rangeMax = 586;
    var offsetTop = Math.max(Math.min(M.Y+v.pageY-M.pY, rangeMax), rangeMin);
    E.css({top:offsetTop});
    var pct = (offsetTop - rangeMin) / (rangeMax - rangeMin)
    var scrollArea = $('.scroller .interior');
    var maxScroll = scrollArea.attr('scrollHeight') - scrollArea.height();
    scrollArea.scrollTop(pct * maxScroll);
 }
 else E.css({width:Math.max(v.pageX-M.pX+M.W,0),height:Math.max(v.pageY-M.pY+M.H,0)});
  return false;},
stop:function(){E.css('opacity',M.o);$().unbind('mousemove',J.drag).unbind('mouseup',J.stop);}
};
var J=$.jqDnR,M=J.dnr,E=J.e,
i=function(e,h,k){return e.each(function(){h=(h)?$(h,e):e;
 h.bind('mousedown',{e:e,k:k},function(v){var d=v.data,p={};E=d.e;
 // attempt utilization of dimensions plugin to fix IE issues
 if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}}
 M={X:p.left||f('left')||0,Y:p.top||f('top')||0,W:f('width')||E[0].scrollWidth||0,H:f('height')||E[0].scrollHeight||0,pX:v.pageX,pY:v.pageY,k:d.k,o:E.css('opacity')};
 E.css({opacity:0.8});$().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
 return false;
 });
});},
f=function(k){return parseInt(E.css(k))||false;};
})(jQuery);

(function($) {
  $.ajaxSetup({
    'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
  });
  
  $.AnchorParser = function() {
    this.getAnchorString = function() {
      if(document.location.href.indexOf('#') > -1) return /(\#.*$)/.exec(document.location.href)[0].replace('#', '');
      return "";
    }
    
    this.getValue = function(key) {
      var qsa = this.getAnchorString().split('&');
      for(var i = 0; i < qsa.length; i++) {
        var kvp = qsa[i].split('=');
        if(kvp[0] == key) return kvp[1];
      }
      return false;
    }
    
    this.setValue = function(key, val) {
      var keyFound = false;
      var qsa = this.getAnchorString().split('&');
      for(var i = 0; i < qsa.length; i++) {
        var kvp = qsa[i].split('=');
        if(kvp[0] == key) {
          keyFound = true;
          kvp[1] = val;
        }
        qsa[i] = kvp.join('=');
      }
      if(keyFound == false) qsa.push(key + '=' + val); 
      document.location.href = document.location.href.split('#')[0] + '#' + this.serialize(qsa);
    }
    
    this.serialize = function(qsa) {
      if(qsa[0] == "") qsa.splice(0,1);
      return qsa.join('&');
    }
  }
  
  $.Gallery = function() {
    this.initialize = function(galleryData) {
      this.galleryData = galleryData;
      this.images = galleryData.images;
  		this.index = 0;
  		this.amountOfClicks = 0;
  		this.adShowInterval = 5; 						// How many clicks before showing an ad
  		this.adDomId = 'interstitial_ad'; 	// The DOM ID of the interstitial ad
  		this.showingAd = false;							// Are we showing an ad right now?
  		this.anchorParser = new $.AnchorParser();
  		this.preloadedImages = Array();
  		this.preloadWindowSize = 3;
  		this.domElement = $('.sf_gallery');
  		this.nextGallery = false;
  		this.nextGalleryCollection = "most_recent";
  		this.prevGallery = false;
  		this.prevGalleryCollection = "most_recent";
      this.adTemplate = '<iframe src="http://ad.doubleclick.net/adi/tmz.photos.wb.dart/{ad_var}{ord}" name="interstitial_ad_iframe" width="300" height="250" frameborder="0" border="none" marginwidth="0" marginheight="0" scrolling="no">';
      this.adTemplate += '<script language="JavaScript1.1" src="http://ad.doubleclick.net/adj/tmz.photos.wb.dart/{ad_var}{ord}"></script>';
      this.adTemplate += '<noscript>';
      this.adTemplate += '<a href="http://ad.doubleclick.net/jump/tmz.photos.wb.dart/{ad_var}{ord}>';
      this.adTemplate += '<img src="http://ad.doubleclick.net/ad/tmz.photos.wb.dart/{ad_var}{ord}" width="300" height="250" border="0">';
      this.adTemplate += '</a>';
      this.adTemplate += '</noscript>';
      this.adTemplate += '</iframe>';
        		
  		// ### Temporary for poll promotion
  		if(document.location.href.match(/galleries\/threes_a_crowd/)) {
  		  $('.sf_gallery .description').after('<div class="polls" align="center" style="margin-top:15px;"></div>');
		  }
    }
    
    this.preloadWindow = function() {
      for(var i = this.index - this.preloadWindowSize; i < this.index + this.preloadWindowSize; i++) {
        var idx = (i<0) ? this.images.length + i : i;
        if(idx >= this.images.length || idx < 0) idx = 0;
        var imgSrc = this.images[idx].full_path;
        if( $.inArray(imgSrc, this.preloadedImages) == -1) {
          this.preloadedImages.push(imgSrc);
          $('<img/>').attr('src', imgSrc);
        }
      }
    }
    
    this.navigate = function(direction) {
      if(this.nextGallery && (direction == "forward") && (this.index == this.images.length - 1)) {
        window.location = "/galleries/" + this.nextGallery + "#tab=" + this.nextGalleryCollection;
        return false;
      }
      if(this.prevGallery && (direction == "backward") && (this.index == 0)) {
        window.location = "/galleries/" + this.prevGallery + "#tab=" + this.prevGalleryCollection;
        return false;
      }
      
      if(this.shouldDisplayAd()) {
        this.displayAd();
        return false;
      }
      if(direction == "forward") {
        this.index = this.getNextIndex();
      } else if(direction == "backward") {
        this.index = this.getPreviousIndex();
      }
      this.render(this.index);
    }
    
    this.getNextIndex = function() {
      if(this.index + 1 > this.images.length - 1) return 0;
      return this.index + 1;
    }
    
    this.getPreviousIndex = function() {
      if(this.index -1 < 0) return this.images.length - 1;
      return this.index - 1;
    }
    
    this.render = function(idx) {
      // ### Temporary for poll promotion
      if(document.location.href.match(/galleries\/threes_a_crowd/)) {
        pollIds = ['3582',
        '3592',
        '3601',
        '3602',
        '3611',
        '3711',
        '3612',
        '3621',
        '3622',
        '3632',
        '3642',
        '3652',
        '3662',
        '3672',
        '3681',
        '3691',
        '3701']

        $('.sf_gallery .polls').empty();        
        if(pollIds[idx]) {
          $('.sf_gallery .polls').append('<iframe scrolling="no" frameborder="0" marginwidth="0" marginheight="0" width="250" height="120"></iframe>');
          var pollHTML = '<html><head><title></title><script src="http://www.blogsmithmedia.com/stadium.weblogsinc.com/tmz/gallery/v3/javascripts/jquery-1.3.2.min.js" type="text/javascript"></script></head><body><script type="text/javascript" src="http://polls.tmz.com/polls/'+pollIds[idx]+'/insert.js?stencil_id=2.js"></script></body></html>';
          $('.sf_gallery .polls iframe').contents()[0].write(pollHTML);
          var iframe = $('<iframe style="display:none;"></iframe>');
          $('body').append(iframe); // prevents infinite browser spinner
          iframe.remove();
        } else {
        }
      }
      this.index = idx;
      var image = this.images[idx];
      this.domElement.find('.image').empty().append('<img src="' + image.full_path + '"/>');
      this.domElement.find('.image_count').html((idx + 1) + "/" + this.images.length);
      this.domElement.find('.description').html(image.description);
      this.domElement.find('.credit').html(image.credit);
      
      if(this.showingAd) this.hideAd();
      this.preloadWindow();
      
      if(this.amountOfClicks != 0) {
        // after initial load
        this.anchorParser.setValue('id', image.id);
        // Setting Omniture vars -- the first two lines are heavy handed but have been agreed upon.
    		s_265.prop12=document.location.href.split("?")[0].split("#")[0];
    		s_265.pageURL=document.location.href.split("?")[0].split("#")[0] + "#id=" + (image.id);
    		s_265.campaign="";
    		s_265.eVar16="";
    		s_265.eVar18="";
    		s_265.eVar19="";
    		s_265.referrer="";
    		var s_code=s_265.t(); 	// .t(); sends the impression to Omniture.
    		var s_code2=s.t();
    		
    		//$.getJSON('http://cdn.photos.tmz.com/comscore.xml?j=?');
    		//comscoreUrl = "http://cdn.photos.tmz.com/comscore.xml?" + new Date().getTime().toString();
    		//var script = document.createElement("script");        
        //script.setAttribute("src",comscoreUrl);
        //script.setAttribute("type","text/javascript");                
        //document.body.appendChild(script);
        $.ajax({type:'GET', url:'http://photos.tmz.com/comscore.xml', cache:false});
        COMSCORE.beacon({
        c1:2,
        c2:"3000013",
        c3:"3000013",
        c4:"",
        c5:"",
        c6:"",
        c15:""
        });
		  }
    }
    
    this.shouldDisplayAd = function() {
      if(this.galleryData.display_interstitial_ads == false) return false;
  		this.amountOfClicks++;
  		return (this.amountOfClicks % this.adShowInterval) == 0;
    }
    
    this.displayAd = function() {
      var ord=Math.random()*10000000000000000;
      this.showingAd = true;
      // ### Temporary for poll promotion
      this.domElement.find('.polls').hide();
      this.domElement.find('.interstitial_ad_wrapper').show();
      this.domElement.find('.description').html('');
      this.domElement.find('.credit').html('');
      this.domElement.find('.image').empty();
      $('#'+this.adDomId).html(this.adTemplate.template({ord: ord, ad_var: this.galleryData.magic_numbers[4]}));
    }
    
    this.hideAd = function() {
      $('#'+this.adDomId).html('');
      this.domElement.find('.interstitial_ad_wrapper').hide();
      // ### Temporary for poll promotion
      this.domElement.find('.polls').show();
      this.showingAd = false;
    }
    
    this.getIndexByID = function(image_id) {
  		for(var i = 0; i < this.images.length; i++) {
  			if(this.images[i].id == image_id) {
  				return i;
  			}
  		}
  		return 0;
  	}
  }
  
  /* Tabbed Collection Widget
  *****************************/
  
  $.sfTabbedCollectionWidget = function(object, opts) {
    var $o = $(object);
    var $galleryList = $o.find('.galleries');
    var $paginationWrapper = $o.find('.pagination-wrapper');
    var $tabs = $o.find('.collection-tabs li');
    var selectedTabIndex = 0;
    var galleryItemTemplate = '<li><a href="/galleries/{permalink}#tab={tab}" title="{title}"><img src="{thumb_path}"/><p>{title}</p></a></li>';
    var $xhr;
    
    function render(data) {
      $.each(data.galleries, function(i, gallery) {
        gallery.tab = $tabs.find('a.active').parent().attr('class');
        $galleryList.append(galleryItemTemplate.template(gallery));
      });
      $paginationWrapper.empty().append(data.pagination_links);
      $paginationWrapper.find('a').click(function(evt) {
        evt.preventDefault();
        if($xhr)$xhr.abort();
        get($(this).attr('href'), true);
      });
    }
    
    function simulate_click(collection_name, data) {
      $tabs.find('a.active').removeClass('active');
      $tabs.parent().find('li.' + collection_name).addClass('active');
      $galleryList.empty();
      render(data);
    }
    
    function get(href, pagination_click) {
      if(!pagination_click) {
        $tabs.find('a.active').removeClass('active');
        $tabs.find('a[href=' + href + ']').addClass('active');
      }
      $galleryList.empty();
      var href = href.replace(/\.json$/, '') + '.json';
      $xhr = $.getJSON(href, render);
    }
    
    $tabs.find('a').click(function(evt) {
      evt.preventDefault();
      if($xhr)$xhr.abort();
      get($(this).attr('href'));
    });
  }
  
  $.fn.sfTabbedCollectionWidget = function(options) {
    var opts = $.extend({}, $.fn.sfTabbedCollectionWidget.defaults, options);

    return this.each(function() {
      new $.sfTabbedCollectionWidget(this, opts);
    });
  }

  $.fn.sfTabbedCollectionWidget.defaults = {
    selectedTab: 'hot_photos'
  }
})(jQuery);

window.anchorParser = new $.AnchorParser();

/* All Pages
*******************/

/* All Pages
********************/

function setupSearch() {
  var searchResultTemplate =   '<li class="clearfix">';
  searchResultTemplate +=      '  <div class="thumb"><a href="/galleries/{permalink}" title="{title}"><img src="{thumb_path}"/></a>';
  searchResultTemplate +=      '  <div class="text">';
  searchResultTemplate +=      '    <a href="/galleries/{permalink}" title="{title}">{title}</a>';
  searchResultTemplate +=      '  </div>';
  searchResultTemplate +=      '</li>';
  
  function submitSearch(e) {
    e.preventDefault();
    
    var $interior = $('.scroller .interior');
    $interior.find('.list').hide();
    var searchTerm = $('.search input').val();
  
    $.ajax({
      url: "/search/" + searchTerm + ".json",
      dataType: 'json',
      success: function(data) {
        $searchResults = $interior.find('.search-results');
        $resultsList = $searchResults.find('ul').empty();
        $searchResults.show();
        if(data.length == 0) {
          $searchResults.find('h2').after('<p class="no-results">No Results</p>');
        } else {
          $.each(data, function(i,gallery) {
            gallery.thumb_path = gallery.thumb_path.replace(/_thumb.jpg$/, '_medium.jpg');
            $resultsList.append(searchResultTemplate.template(gallery));
          });
        }
        //$('html,body').animate({scrollTop: $('.scroller').offset().top}, 500); 
      },
      error: function(xhr, textStatus, errorThrown) {
        $searchResults = $interior.find('.search-results');
        $resultsList = $searchResults.find('ul').empty();
        $searchResults.show();
        $searchResults.find('h2').after('<p class="no-results">No Results</p>');
      }
    });
  }
  
  $('.search form').submit(submitSearch);
  $('.search button').click(submitSearch);
  
}

// disable the below once the new search partial is deployed and the cache is swept, and we'll get better responsiveness
$(document).ready(function() {
  sfShowGalleryContext();
});

$('.search-results .close').live('click', function(e) {
  e.preventDefault();
  var $interior = $('.scroller .interior');
  $interior.find('.search-results').hide();
  $interior.find('.list').show();
});

/* Gallery Show
*******************/

var tab;
function sfGetTab() {
  tab = anchorParser.getValue('tab')
  if(!tab) {
    tab = "most_recent";
  } else if (!galleryContextData[tab]) {
    tab = "most_recent";
  } else if (!galleryContextData[tab].previous || !galleryContextData[tab].next) {
    tab = "most_recent";
  }
  anchorParser.setValue('tab', tab);
}

function sfCullRightRail() {
  $('.scroller .interior .collection').not('.' + tab).hide();
  $('.back-to-galleries').show();
}

function sfBreadcrumb() {
  $('#breadcrumbs a:contains(photos)').after(" &raquo; " + tab.titleize());
}

function sfCollectionName() {
  $('h2.collection-name span').html(tab.titleize());
}

function sfShowGalleryContext() {
  // Set up gallery context for next/prev gallery navigation
  var galleryContext = galleryContextData[tab];
  $('.context_galleries .previous_gallery a').attr('href', '/galleries/' + galleryContext.previous.permalink + '#tab=' + galleryContext.previous.collection);
  $('.context_galleries .previous_gallery .thumb img').attr('src', galleryContext.previous.thumb);
  $('.context_galleries .previous_gallery .title').html(galleryContext.previous.title);
  
  $('.context_galleries .next_gallery a').attr('href', '/galleries/' + galleryContext.next.permalink + '#tab=' + galleryContext.next.collection);
  $('.context_galleries .next_gallery .thumb img').attr('src', galleryContext.next.thumb);
  $('.context_galleries .next_gallery .title').html(galleryContext.next.title);
  
  $('.context_galleries').show();
  
  sfGallery.nextGallery = galleryContext.next.permalink;
  sfGallery.nextGalleryCollection = galleryContext.next.collection;
  sfGallery.prevGallery = galleryContext.previous.permalink;
  sfGallery.prevGalleryCollection = galleryContext.previous.collection;
}

function sfSelectCollectionTab(which_tab) {
  if(!which_tab) which_tab = tab;
  $('.tabbed-collection-widget li.' + which_tab + ' a').click();
}

/* www.tmz.com's common_aol_tmz.js
**********************************************/

var is_aol = navigator.userAgent.toLowerCase().indexOf("aol") != -1;
var is_mac = navigator.userAgent.indexOf('Mac') != -1;

// Start Channel 
function channel_init(){
}

// Header2.0
function p_o(o){return document.getElementById(o);}

function ai_posX(obj){
 var left=0;
 if(obj.offsetParent){
  while(obj.offsetParent){
   left+=obj.offsetLeft;
   obj=obj.offsetParent;
  }
 }else if(obj.x)left+=obj.x;
 return left;
}
function ai_posY(obj){
 var top=0;
 if(obj.offsetParent){
  while(obj.offsetParent){
   top+=obj.offsetTop;
   obj=obj.offsetParent;
  }
 } else if(obj.x)top+=obj.y;
 return top;
}

function togMore(e,state){
 var oDiv=p_o('smore');
 if(state=='show'){
  posMore(e);
  oDiv.style.zIndex=99999999;
  oDiv.style.display='block';
 } else {
  oDiv.style.display='none';
 }
 return false;
}
function posMore(e){
	var oDiv=p_o('smore');
	var oLnk=p_o('smorea');
	posY = findMousePos(e);
	oDiv.style.left=(ai_posX(oLnk)+-50)+'px';
	oDiv.style.top=(posY+oLnk.offsetHeight/2)+'px';
}
// Begin : Headers 2 code
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function srchSub(ref){
  var frm=p_o("search");
  var queryval = frm.topquery.value.trim();
  queryval = queryval.replace( /\+/, " ");
  newurl = ref.href + queryval;
  window.location = newurl;
  return false;
}

function searchTarget(parent, url, newWindow, newTarget) {
    form = $(parent + ' form')[0];
    // Set the target for the form
    form.action = url;
    if (newWindow) {
        form.target = '_blank';
    } else {
        form.target = '';
    }
    
    $(parent + ' .searchCatBg').removeClass('searchCatBg');
    document.getElementById(newTarget).className = 'searchCatBg';

    return false;
}

function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
  var arrClass = strClass.split(delim);
  for (var i = 0, j = objColl.length; i < j; i++) {
    var arrObjClass = objColl[i].className.split(' ');
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr[arr.length] = objColl[i];
          //arr.push(objColl[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return arr;
}

function eventIsEnterKey(event) {
    if (event && event.which == 13 || window.event && window.event.keyCode == 13 || event && event.which == 3 || window.event && window.event.keyCode == 3) {
        return true;
    }
    return false;
}

function submitHeaderSearch(parent, event) {
    if (event == "onclick" || eventIsEnterKey(event)) {
        return srchSub2(parent);        
    } else {
        return true;
    }
}

function srchSub2(parent) {
    var frm = $(parent + ' form')[0];
    var queryval = frm.query.value.trim();
    queryval = queryval.replace( /\+/, " ");
    var newurl = frm.action + queryval;
    if (frm.target == '_blank') {
        window.open(newurl, '_blank', '');
    } else {
        window.location = newurl;
    }
    return false;
}

//adRefresh
function adRefresh() {
var adSpots = '0';
try {
if (pgAdSpots != null && pgAdSpots != 'undefined' && pgAdSpots != '') {
adSpots = pgAdSpots;
}
} catch(e) {
adSpots = '0';
}
try {
top.ch_refresher.refresh_ads_by_spot(adSpots);
} catch(e) { }
return true;
}

// NON-MODULE CODE
function popup_window(url,width,height){
	var features="status=0,menubar=0,location=0,toolbar=0";
	if (!isNaN(parseInt(width))){features+=",width="+width;}
	if (!isNaN(parseInt(height))){features+=",height="+height;}
	if (typeof(window.screenLeft)!="undefined"){
		features+=",left="+window.screenLeft;
		features+=",left="+Math.round(window.screenLeft+((document.body.clientWidth/2)-(width/2)));
	} else if (typeof(window.screenX)!="undefined"){
		features+=",left="+Math.round(window.screenX+((window.outerWidth/2)-(width/2)));
	}
	if (typeof(window.screenTop)!="undefined"){
		features+=",top="+window.screenTop;
		features+=",top="+Math.round(window.screenTop+150);
	} else if (typeof(window.screenY)!="undefined"){
		features+=",top="+Math.round(window.screenY+((window.outerHeight-window.innerHeight)+150));
	}
	var popupWin=window.open(url,"popupWin",features);
	if (popupWin.focus){popupWin.focus();}
}

function popupWindow(url,width,height,features) {
	if (!isNaN(parseInt(width))){features+=",width="+width;}
	if (!isNaN(parseInt(height))){features+=",height="+height;}
	if (typeof(window.screenLeft)!="undefined"){
		features+=",left="+window.screenLeft;
		features+=",left="+Math.round(window.screenLeft+((document.body.clientWidth/2)-(width/2)));
	} else if (typeof(window.screenX)!="undefined"){
		features+=",left="+Math.round(window.screenX+((window.outerWidth/2)-(width/2)));
	}
	if (typeof(window.screenTop)!="undefined"){
		features+=",top="+window.screenTop;
		features+=",top="+Math.round(window.screenTop+150);
	} else if (typeof(window.screenY)!="undefined"){
		features+=",top="+Math.round(window.screenY+((window.outerHeight-window.innerHeight)+150));
	}
	var popupWin=window.open(url,"popupWin",features);
	//if (popupWin.focus){popupWin.focus();}
}

// gets the value of the query string
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
}

navigator.userAgent.toLowerCase().indexOf('msie')!=-1?bb_ie=1:bb_ie=0;

function bb_o(o){return document.getElementById(o);}

function bb_l(o){return o.getElementsByTagName("li");}

//Dynamic CSS manipulation tools.
function setClassByID(objectID, newClass)
{
        var object = document.getElementById(objectID);
        object.className = newClass;
}

function setClassByObj(senderObj, newClass)
{
        senderObj.className = newClass;
}

//This function recursivelly finds a DIV in a parent element.
//It is needed because the mozilla and ie doms have different hierarchies.
//Called from hiLiteRow, a top11deeplink function.
function recurseDiv(el)
{
        if (el.nodeName == "DIV")
        {
                return el;
        }
        else if (el.hasChildNodes)
        {
                for (i = 0 ; i < el.childNodes.length; i++)
                {
                        if (el.childNodes[i].nodeName == "DIV")
                        {
                                return el.childNodes[i];
                        }
                        else if (el.childNodes[i].hasChildNodes)
                        {
                                var returnEl = recurseDiv(el.childNodes[i]);
                                if (returnEl) return returnEl;
                        }
                }
        }
        else
        {return null};
}

function rsiAdInit(segmax) {

    var segQS="";
    var segs_beg=document.cookie.indexOf('rsi_segs=');
    if(segs_beg>=0){
        segs_beg=document.cookie.indexOf('=',segs_beg)+1;
        if(segs_beg>0){
            var segs_end=document.cookie.indexOf(';',segs_beg);
            if(segs_end==-1)segs_end=document.cookie.length;
            rsi_segs=document.cookie.substring(segs_beg,segs_end).split('|');
            for (var i=0;i<Math.min(segmax,rsi_segs.length);i++){
                segQS+=rsi_segs[i].replace(/.*_(.*)/,"rsi=$1;");
            }
            adSetOthDclk(segQS);
       }
    }
}

/* temporary inline js */

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);

			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);