// Requires jQuery 1.4.2
var hasCSS;

// Fix IE ABBR bug
document.createElement('abbr');
//

addLoadEvent(init);

function init(){
  addListClassNames();
}

// protect the onload event
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// cross browser event binding
// csAddEvent(obj,'mouseup',myFunctionName)
function csAttachEvent(obj,ev,fct){
  extEv='on'+ev;
  if(window.addEventListener){
    obj.addEventListener(ev, fct, false);
  }else if (window.attachEvent){
    obj.attachEvent(extEv, fct);
  }
}


// Add some classnames to list items
function addListClassNames() {
  if (document.getElementsByTagName) {
    var lists = document.getElementsByTagName('ul');
    for(i=0;i < lists.length;++i){
      sel = lists[i].getElementsByTagName('li');
      addClassName(sel[0],'first');
      addClassName(sel[sel.length-1],'last');
    }

    // implements zebra pattern for results-list;
    if (document.getElementById('result-list'))
    {
      if (document.getElementById('result-list').getElementsByTagName('ol').length > 0)
      {
        lists = document.getElementById('result-list').getElementsByTagName('ol')[0].getElementsByTagName('li');
        for (i=0;i < lists.length;++i)
        {
          if (i % 2 == 0)
            addClassName(lists[i],'odd');
        }
      }
    }
  }
}

// Return next sibling element
// -- this may have some bugs to do with non-elmenentNode siblings
function getNextElementSibling(obj) {
  var	obj = obj.nextSibling;
  while (obj.nodeType != 1 && obj.nextSibling != 'null')
  {
    obj = obj.nextSibling;
  }
  var state = (obj.parentNode) ? obj.parentNode : false;
  return state;
}

// Find ancestor with specific className
function getAncestorWithClass(obj,targetClassName) {
  while (!containsClassName(obj.parentNode,targetClassName))
  {
    obj = obj.parentNode;
  }
  var state = (obj.parentNode) ? obj.parentNode : false;
  return state;
}

// Find ancestor with specific className
function getAncestorElement(obj,targetTagName) {
  while (obj.parentNode.tagName.toLowerCase() != targetTagName)
  {
    obj = obj.parentNode;
  }
  var state = (obj.parentNode) ? obj.parentNode : false;
  return state;
}

// Handle adding & removing classNames cleanly
function addClassName(obj,newClassName){
  if (containsClassName(obj,newClassName)==true)
    return;
  var CLname = (obj.className == '') ? newClassName : obj.className+' '+newClassName;
  obj.className = CLname;
}

function removeClassName(obj,ClassName){
  var vRegX=new RegExp('\s*' +ClassName+ '*\\b');
  obj.className = obj.className.replace(vRegX, '');
}

function containsClassName(obj,ClassName){
  var vRegX=new RegExp('\s*' +ClassName+ '*\\b');
  var state = (obj.className.search(vRegX) >= 0) ? true : false;
  return state;
}

/*
 * INIT Feature Image
 */
function initMainFeature(jsondata, target){
  if ($(target).length>0) {
    var queue = jsondata.features.length;
    setMainFeature(queue,$(target),jsondata.features[Math.floor(Math.random()*queue)]);
  }
}

/*
 * SET Feature Image
 */
function setMainFeature(queue,feature,item) {
  if(item){
    var $feature = $(feature);
    $feature.empty();
    var $image = $('<img src="'+item.image+'" alt="'+item.alt+'" title="'+item.alt+'" />');
    var $link = $('<a href="'+item.link+'"></a>');

    if(item.body==undefined || item.body==""){
      // feature image only
      $feature.append($image);
      if(item.link && item.link!="") $image.wrap($link);
    }
  }
}

// Popup window code
function openModless(url,name,w,h,tBar,lBar,mBar,sBar) {
  var h = h || '800', w = w || '800', name = name || 'NewWindow';
  var tbar = tbar || 'no', lBar = lBar || 'no', mBar = mBar || 'no', sBar = sBar || 'no';
  var scrn=getScreenDimensions();
  sFeatures = 'height=' + h + 'px' + ',width=' + w + 'px';
  sFeatures += ',left=' + (scrn.sX-(w/2)) + 'px';
  sFeatures += ',top=' + (scrn.sY-(h/2)) + 'px';
  sFeatures += ',toolbar=' + tBar;
  sFeatures += ',location=' + lBar;
  sFeatures += ',menubar=' + mBar;
  sFeatures += ',status=' + sBar;
  sFeatures += ',resizable=yes,scrollbars=yes,copyhistory=no';
  var newWin = window.open(url,name,sFeatures,true);
  newWin.focus();
}

function getScreenDimensions() {
  var sh = screen.availHeight;
  var sw = screen.availWidth;
  var sx = sw/2;
  var sy = sh/2;
  return {
    sWidth:sw,
    sHeight:sh,
    sX:sx,
    sY:sy
  };
}


/* PLACEHOLDER  ================================== */
function supportsInputAttr(attrName){
  var i = document.createElement('input')
  return attrName in i
}

jQuery.fn.addPlaceholder = function(placeholder) {
  // If this client supports the HTML5 'placeholder' attribute
  // then we get the desired behaviour for free -- do no more.
  // If the client is old then we need to define the behaviour...

  //if (supportsInputAttr('placeholder')){
  //  if(placeholder!=undefined) $(this).attr('placeholder',placeholder);
  //}else{
  if(placeholder!=undefined && $(this).val()==="") $(this).val(placeholder);
  var str = $(this).attr('value');
  // field focus/blur
  $(this).focus(function(){
    if (this.value === str)
      this.value = "";
    // ..and just for IE6 & 7...
    $(this).toggleClass('focus');
  }).blur(function(){
    if (this.value === "")
      this.value = str;
    // ..and just for IE6 & 7...
    $(this).toggleClass('focus');
  });
//}
};
/* END PLACEHOLDER  ================================== */

$(document).ready(function(){
  /*	POPUP WINDOW BINDINGS
	 * This uses window.load to ensure all dom manipulations have been completed
	 * first, then alters the popup anchor tags
	 */
  $(window).load(function() {
    $('a[class*="should-popup"]').each(function(){
      var anc = $(this);
      var cn = this.className;
      var regex  = /should-popup\S*\w*/;
      var key = cn.match(regex)[0];
      var useTarget = false;
      var d = new Date();
      var wndName = "Westpac" + d.getTime();
      // Set some defaults
      var tBar = 'no',lBar = 'no', mBar = 'no',sBar='no';
      var w = 800;
      var h = getScreenDimensions().sHeight-80;

      switch(key) {
        case 'should-popup':
          // uses traditional TARGET attribute
          // instead of javascript new window
          anc.attr('target','_blank');
          useTarget = true;
          break;
        case 'should-popup-modless':
          w = 600;
          h = 800;
          break;
        case 'should-popup-help':
          w = 600;
          h = 800;
          break;
        case 'should-popup-basic':
          w = 800;
          h = 600;
          lBar = 'yes';
          break;
        case 'should-popup-pdf':
          w = 800;
          h = 800;
          break;
        case 'should-popup-600':
          w = 600;
          h = 600;
          lBar = 'yes';
          break;
        case 'should-popup-700':
          w = 700;
          h = 600;
          lBar = 'yes';
          break;
        case 'should-popup-fullscreen':
          w = getScreenDimensions().sWidth;
          h = getScreenDimensions().sHeight;
          break;
        default:
          var dims = key.toLowerCase().split('-')[2].split('x');
          if(!isNaN(dims[0])){
            if (isNaN(dims[1])) {
              w = dims[0];
            } else {
              w = dims[0];
              h = dims[1];
            }
          }
          break;
      }
      if(!useTarget){
        // bind event which opens the window
        anc.click(function(e) {
          openModless(anc.attr("href"),wndName,w,h,tBar,lBar,mBar,sBar);
          e.preventDefault();
          return false;
        });
      }
      // insert label for accessibility, if it doesn't exist
      anc.not(':has(span.wai)').append('<span class="wai"> (Opens in new window)</span>');
    });
  });

  $('#searchFld').addPlaceholder("I'm searching for...");

  // home feature rotation
  if(typeof mainFeaturesQueue  === 'object') {
    initMainFeature(mainFeaturesQueue,'#feature-main');
  }

});
