////////////////////////////// Browser-OS Sniffer //////////////////////////////
var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav6up = (is_nav && (is_major >= 5));
var is_nav6_1up = false;
if (is_nav6up){
  var N6index = agt.indexOf('netscape6');
  var N6ver = parseFloat(agt.substr(N6index+10,3));
  is_nav6_1up = (N6ver >= 6.1);
}
var is_firefox = (agt.indexOf("firefox")!=-1);
var is_safari = (agt.indexOf("safari")!=-1);
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie3 = (is_ie && (is_major < 4));
var is_ie4 = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie5up = (is_ie && !is_ie3 && !is_ie4);
var is_aol = (is_ie && (agt.indexOf("aol")!=-1));
var is_win = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
var is_mac = ( (agt.indexOf("mac")!=-1));
var is_win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));
var is_win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
var is_winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
var is_winxp = ((agt.indexOf("windows xp")!=-1) || (agt.indexOf("Windows NT 5.1")!=-1));
var is_win32 = (is_win95 || is_winnt || is_win98 || ((is_major >= 4) && (navigator.platform == "Win32")) || (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

document.getElementsByClassName = function(clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

////////////////////////////// Navigation //////////////////////////////
sfHover = function() {
  var BUA = navigator.userAgent;
  var BIE = BUA.indexOf("MSIE");
    if (BUA.indexOf("7.0")) {
      BIE = -1;
    }
  var BIsIE = BIE>=0;
  if (document.getElementById("site_nav")) {
    var sfEls = document.getElementById("site_nav").getElementsByTagName("LI");
  }  else {
    return;
  }

  for (var i=0; i<sfEls.length; i++) {
    sfEls[i].onmouseover=function() {
    this.className+=" sfhover";
    }
    sfEls[i].onmouseout=function() {
    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }

    //If we're using IE then this tells any first level item to have a width of 1px
    if (sfEls[i].parentNode == document.getElementById("site_nav") && BIsIE) {
    sfEls[i].style.width = '1px';
    }
  }
}

if (window.attachEvent) window.attachEvent("onload", sfHover);

////////////////////////////// Content Switcher //////////////////////////////
var triggerNames = new Array();

function change_class (containerProto, newClassName) {
  var container;
  // Container can be either an HTMLObject or a name
  if (typeof containerProto == "string") {
    container = document.getElementById(containerProto);
  } else {
    container = containerProto;
  }
  if (container) {
    container.className = newClassName;
  }
}

function getTriggerNames(containerProto, groupName) {
  if (groupName == null || groupName == '') {
    return;
  }

  var container;
  // containerProto can be either an HTMLObject or a name
  if (typeof containerProto == "string") {
    container = document.getElementById(containerProto);
  } else {
    container = containerProto;
  }
  if (container) {
    for (var i=0; i<=container.childNodes.length; i++) {
      var currentChild = container.childNodes[i];
      if (currentChild) {
        var elemId = currentChild.id;
        if (elemId != null && elemId.indexOf("_trigger") != -1) {
          var idParts = elemId.split("_"); // ids of form 'groupName_triggername_trigger'...
          if (idParts.length == 3)  {
            if (! triggerNames[groupName]) {
              triggerNames[groupName] = new Array();
            }
            triggerNames[groupName].push(idParts[1]);  // ...and we want 'triggername'
          }
        }
        getTriggerNames(currentChild, groupName);
      }
    }
  }
}

function getTriggerNamesTest(containerProto, groupName) {
  if (groupName == null || groupName == '') {
    return;
  }

  var container;
  // containerProto can be either an HTMLObject or a name
  if (typeof containerProto == "string") {
    container = document.getElementById(containerProto);
  } else {
    container = containerProto;
  }
  if (container) {
    for (var i=0; i<=container.childNodes.length; i++) {
      var currentChild = container.childNodes[i];
      if (currentChild) {
        var elemId = currentChild.id;
        if (elemId != null && elemId.indexOf("_trigger") != -1) {
          alert("hi" + elemId);
          var idParts = elemId.split("_"); // ids of form 'groupName_triggername_trigger'...
          if (idParts.length == 3)  {
            if (! triggerNames[groupName]) {
              triggerNames[groupName] = new Array();
            }
            triggerNames[groupName].push(idParts[1]);  // ...and we want 'triggername'
          }
        }
        getTriggerNamesTest(currentChild, groupName);
      }
    }
  }
}

function reveal(groupName, visDivName) {
  if (groupName == null || groupName == '') {
    return;
  }
  var items = triggerNames[groupName];
  if (items == null || items.length == 0) {
    return;
  }

  // Hide all
  for (var i=0; i<items.length; i++) {
    var hide_box = groupName + "_" + items[i] + "_content";
    change_class(hide_box, "hide_box");
    var blurTrigger = groupName + "_" + items[i] + "_trigger";
    change_class(blurTrigger, "blur_trigger");
  }

  // Show selected
  var show_class = "show_box";
  switch (groupName) {
    case "ap":
      show_class = "stories show_box";
      break;
    case "blogs":
      show_class = "blog_box show_box";
      break;
    case "searchtool":
      show_class = "searchtool show_box";
      break;
    default:
      show_class = "show_box";
      break;
  }
  var show_box = groupName + "_" + visDivName + "_content";
  change_class(show_box, show_class);
  var activeTrigger = groupName + "_" + visDivName + "_trigger";
  change_class(activeTrigger, "indicator");
}

function pickRandom(myArray) {
    var myArrayLen = myArray.length;

    var random_num = Math.round(Math.random() * (myArrayLen - 1));

    if ((random_num < 0) || (random_num > (myArrayLen - 1))) {
        return null;
    } else {
        return myArray[random_num];
    }
}

////////////////////////////// Font Size Switcher //////////////////////////////
function setActiveStyleSheet(linkId) {
  var i, linkObj;
  for (i=0; (linkObj = document.getElementsByTagName("link")[i]); i++) {
    if (linkObj.getAttribute("rel").indexOf("style") != -1 && linkObj.getAttribute("title")) {
      linkObj.disabled = true;
    }
  }
  linkObj = document.getElementById(linkId);
  if (linkObj != null) {
    linkObj.disabled = false;
  }
}

function getActiveStyleSheet() {
  var i, linkObj;
  for (i=0; (linkObj = document.getElementsByTagName("link")[i]); i++) {
    if(linkObj.getAttribute("rel").indexOf("style") != -1 && linkObj.getAttribute("title") && !linkObj.disabled) {
      return linkObj.id;
    }
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  } else {
    expires = "";
  }
  var s = name+"="+value+expires+"; path=/";
  document.cookie = s;
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') {
      c = c.substring(1,c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }
  }
  return null;
}

function onloadHandler () {
  return true;
}

function onunloadHandler () {
  var activeCSSId = getActiveStyleSheet();
  createCookie("activeCSSId", activeCSSId, 3650);
  return true;
}

var activeCSSId = readCookie("activeCSSId");
setActiveStyleSheet(activeCSSId);

////////////////////////////// New Window //////////////////////////////
function aasopen(w,h,t,p) {
  if (!w) w=600;
  if (!h) h=400;
  if (!t) t='_aas';
  if (!p) p=',resizable=1,scrollbars=1,menubar=1,status=1,toolbar=1,location=0';
  var newWin = window.open('',t,'width=' + w +',height='+ h + p);
  newWin.focus();
  return true;
}
////////////////////////////// Window Resize //////////////////////////////
function queryString() {
  this.params = new Object()
  this.get = queryStringGet;
  var qs = location.search.substring(1,location.search.length)

// Turn <plus> back to <space>
  qs = qs.replace(/\+/g, ' ')

// parse out name/value pairs separated via &
  var args = qs.split('&')

// split out each name=value pair
  for (var i=0; i < args.length; i++) {
    var value;
    var pair = args[i].split('=');
    var name = unescape(pair[0]);

    if (pair.length == 2) { value = unescape(pair[1]); }
    else                  { value = name; }

    this.params[name] = value;
  }
}

function queryStringGet(key, default_) {
// it may not make sense, but this line changes any UNDEFINED to NULL
  if (default_ == null)
    default_ = null;

  var value = this.params[key];
// if key does not have a value, you can specify a default
  if (value == null) { value = default_; }

  return value;
}

var qs = new queryString();

if(qs.get('resize') == 'true' && qs.get('w') && qs.get('h')) {
  window.resizeTo(qs.get('w'),qs.get('h'));
}

////////////////////////////// Image Swap //////////////////////////////
function SC_findObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=SC_findObj(n,d.layers[i].document); return x;
}
function SC_swapImage() {
  var i,j=0,x,a=SC_swapImage.arguments; document.SC_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=SC_findObj(a[i]))!=null){document.SC_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function SC_preloadImages() {
 var d=document; if(d.images){ if(!d.SC_p) d.SC_p=new Array();
   var i,j=d.SC_p.length,a=SC_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.SC_p[j]=new Image; d.SC_p[j++].src=a[i];}}
}

////////////////////////////// Misc //////////////////////////////
var ord = Math.floor(Math.random() * 10000000);

////////////////////////////// Nav Search Bar //////////////////////////////
function doNavSearch() {
  var search_form = document.cxSearchForm;
  var search_value = search_form.QueryText.value;
  if (search_form.searchby[2].checked) {
    window.location = 'http://www.newslibrary.com/nlsearch.asp?s_hidethis=no&search_mode=basic&REGION=AASB&search_text=' + search_value;
    return false;
  } else {
    search_form.submit();
  }
}

function doJavaWOEError() {
  if ((window.location.href.indexOf("woe") > 0) && document.getElementById("woeWrapper")) {
    if (document.getElementById("woeWrapper").innerHTML.indexOf("system encountered an error")) {
      var goBackWOE = confirm("Their was an error submitting your information to the server. \nPlease click OK to go back and resubmit or click Cancel to start over.");

      if (goBackWOE){
        history.back();
      } else {
      }
    }
  }
}

addLoadEvent(doJavaWOEError);

////////////////////////////// Cookie Handling //////////////////////////////
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// HIDE DIV FUNCTIONALITY FOR SOCIAL BOOKMARKING // - Andy Nguyen 2/14/2008
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
if(self.pageYOffset) {
	rX = self.pageXOffset;
	rY = self.pageYOffset;
	}
else if(document.documentElement && document.documentElement.scrollTop) {
	rX = document.documentElement.scrollLeft;
	rY = document.documentElement.scrollTop;
	}
else if(document.body) {
	rX = document.body.scrollLeft;
	rY = document.body.scrollTop;
	}
if(document.all) {
	cX += rX; 
	cY += rY;
	}
d.style.left = (cX+10) + "px";
d.style.top = (cY+10) + "px";
}
function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
dd.style.display = "block";
}

///// A content switcher designed for sitelife discovery

function classReplace(activeObj, inactiveElement, inactiveClass, activeClass){
	var container = activeObj.parentNode;
	var content = container.childNodes;
	for (var i = 0; i < content.length; i++) { 
    	content[i].className = inactiveClass;
		}
	activeObj.className = activeClass;
}

function tabs(tab, div){
	var listNode = tab.parentNode;
	classReplace(listNode, 'li', 'inactive', 'active');
	var divContent = document.getElementById(div);
	classReplace(divContent, 'div', 'hidden', 'visible');
}

///////////////////////////// PLUCK !!!!!!

// quick cookie checks to see that the current user is Logged In
// and returns the userId from either the at or hd cookie
function isPluckLoggedIn() {
            var userKey = null;
            var cookie = function(name){
                        var dc = document.cookie;// this returns/reads all cookies for the domain separated by a semicolon
                        var prefix = name + "=";// creates "hd=" ("hd" is passed in to the function)
                        var begin = dc.toLowerCase().indexOf("; " + prefix);// returns a -1 or whole number for position of "; hd"
                        if (begin == -1) { // "; hd" string does not exist - meaning that hd is the first cookie in the collection of cookies for the domain
                                    begin = dc.indexOf(prefix); //begin is 0 since prefix ("hd") is at the 0 position
                                    if (begin != 0) {
                                                return null;
                                    } //begin should be at index 0 - fail if not
                        }
                        else {
                                    begin += 2; // add 2 to current begin -- not sure why. perhaps this is useful if hd is not the first cookie for the domain
                        }
                        var end = document.cookie.indexOf(";", begin); // search the cookie collection for ";", start the search at begin
                        if (end == -1) { // end does not exist so there is only one cookie for the domain
                                    end = dc.length; // only one cookie for the domain so the end is the length
                        }
                        return unescape(dc.substring(begin + prefix.length, end)); // return the values between the end of "hd=" and the end of the cookie
            }
            var atCookieValue = function(query,param){
                  var keyValuePairs = new Array();
                    for(var i=0; i < query.split("&").length; i++) {
                      keyValuePairs[i] = query.split("&")[i];
                    }
                  var a = new Array(keyValuePairs.length);
                  for(var j=0; j < keyValuePairs.length; j++) {
                     a[j] = keyValuePairs[j].split("=")[0];
                  }
                  for(var j=0; j < keyValuePairs.length; j++) {
                    if(keyValuePairs[j].split("=")[0] == param)
                       return( keyValuePairs[j].split("=")[1]);
                    }
                        }
 
            var hd = cookie("hd");
            var at = cookie("at");
            if (hd != null)  // we have an HD cookie
                        userKey = unescape(hd.split("|")[0]);
            if (at != null) { // we have an AT cookie
                        userKey = atCookieValue(at,"u");
            }
    return userKey;
}

var UserIdForPluck = isPluckLoggedIn();
var theURLForPluck = "/sitelife/content/sitelife/persona.html?newspaperUserId=" + UserIdForPluck;


// *********** 360 Tab Switching ************** //
function switch_tab(tab){
     var activeTab = tab.parentNode;
     var container = activeTab.parentNode;
     var content = container.childNodes;
     for (var i = 0; i <content.length; i++){
         if (content[i].nodeType == '1'){
             content[i].firstChild.className = "";
         }
     }
     activeTab.firstChild.className = "indicator";
}
function switch_content(div, activeClass, inactiveClass){
     var activeDiv = document.getElementById(div);
     var container = activeDiv.parentNode;
     var content = container.childNodes;
     for (var i = 0; i <content.length; i++){
         if (content[i].nodeName == "DIV"){
             content[i].className = inactiveClass; 
         }
     }
     activeDiv.className = "searchtool " + activeClass;
}
function switchMe(tab, div){
     switch_tab(tab);
     switch_content(div, 'show_box', 'hide_box');
}

