/**
 * @version $Id$ $Rev: 28421 $ $Date: 2008-10-14 13:59:58 -0700 (Tue, 14 Oct 2008) $
 */
/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   Description:

   	Uses css selectors to apply javascript behaviours to enable
   	unobtrusive javascript in html documents.

   Usage:

	var myrules = {
		'b.someclass' : function(element){
			element.onclick = function(){
				alert(this.innerHTML);
			}
		},
		'#someid u' : function(element){
			element.onmouseover = function(){
				this.innerHTML = "BLAH!";
			}
		}
	};

	Behaviour.register(myrules);

	// Call Behaviour.apply() to re-apply the rules (if you
	// update the dom, etc).

   License:

   	This file is entirely BSD licensed.

   More information:

   	http://ripcord.co.nz/behaviour/

*/

var Behaviour = {
	list : new Array,

	register : function(sheet){
		Behaviour.list.push(sheet);
	},

	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},

	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);

				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},

	addLoadEvent : function(func){
		var oldonload = window.onload;

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

Behaviour.start();

/*
   The following code is Copyright (C) Simon Willison 2004.

   document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }

    if (!currentContext[0]){
    	return;
    }

    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/

Behaviour._apply = Behaviour.apply;
Behaviour.apply = function() {
	if (this.applied) return;
	this.applied = true;
	this._apply();
};
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", function() {
		Behaviour.apply();
	}, false);
}
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script src=resources/js/getElementsBySelector_ie.js><"+"/script>");
	document.write("<script defer src=resources/js/ie_onload.js><"+"/script>");
/*@end @*/

if (document.evaluate) {
    document.write("<script src=resources/js/getElementsBySelector_xpath.js><"+"/script>");
}

/**
 * @version $Id$ $Rev: 54975 $ $Date: 2009-05-21 14:14:02 -0700 (Thu, 21 May 2009) $
 */
ToggleWidget = function ( el, closedImage, openImage, display, imagePlacement )
{
	this.element = null;
	this.openImage = openImage;
	this.closedImage = closedImage;
	this.display = (display) ? display : "inline";
	this.imagePlacement= (imagePlacement) ? imagePlacement : "left";
	this.labels = new Object();
	this.contents = new Object();
	this.toggles =new Object();
	this.labelContainer = null;
	this.contentContainer = null;
	this.togObj = null;
	this.count=0;
	this.init(el);
}

ToggleWidget.prototype.init = function( el )
{
	  if (typeof el == "string") {
		  var elId = el;
		  el = document.getElementById(el);
		  if (! el) {
			  el = document.createElement("DIV");
			  el.id = elId;
		  }
	  }
  
	  this.element = el;
	  var childNodes = this.element.childNodes;
	  if (childNodes) {
		 for(var i=0;child=childNodes[i];i++) {
		   if(child.nodeType == 1) {
			 if (child.className == "label") {
			 	this.count++;
			 	child.id=this.element.id+"toggle"+this.count ;
				this.labels[child.id ] = child;
			 } else if(child.className.indexOf("content") != -1) {
			 	child.id=this.element.id+"toggle"+this.count ;
				this.contents[child.id] = child;
			 }
		   }
		  }
		  for(var label in this.labels) {
			var toggle = new ToggleItem( label, this.labels[label], this.contents[label] );
			this.toggles[label] = toggle;
		  }
		  if(this.toggles) {
		  	this.render();
		  }
	  }
}
ToggleWidget.prototype.setDisplay = function(display)
{
	this.display = display; 
}	
ToggleWidget.prototype.setClosedImage = function(closedImage)
{
		this.closedImage = closedImage;
}
ToggleWidget.prototype.setOpenImage = function(openImage)
{
		this.openImage = openImage;
}
ToggleWidget.prototype.getImage = function(bool)
{
		if(bool) {
			return this.openImage;
		} else {
			return this.closedImage;
		}
}
ToggleWidget.prototype.hasImages = function()
{
		if(this.closedImage == null || this.openImage == null) {
			return false;
		}
		return true;
}
ToggleWidget.prototype.render = function() {
for(var t in this.toggles) {
	var toggleItem = this.toggles[t];
	//attach a Model to the DOM node
	toggleItem.label.togObj = this;
	toggleItem.label.onclick = this.toggle;
	toggleItem.label.style.display="inline";
	toggleItem.label.onmouseover = function() {
			this.style.cursor='pointer';
	}
	//set the image as a member of the toggleitem not the togglewidget
	if( this.hasImages() )	{
		tmpImage = document.createElement("IMG");
		tmpImage.src = this.getImage( toggleItem.state );
		tmpImage.id =  toggleItem.id;
		tmpImage.className =  "toggleImage";
		tmpImage.alt = '';
		tmpImage.togObj = this;
		toggleItem.image = tmpImage;
		toggleItem.image.onmouseover = function() {
					this.style.cursor='pointer';
		}
	}
	if(this.display == "inline") {
		if(this.labelContainer == null) {
			this.labelContainer = document.createElement("DIV");
			this.labelContainer.id = this.element.id+"Labels";
		}
		if(this.contentContainer == null) {
			this.contentContainer = document.createElement("DIV");
			this.contentContainer.id = this.element.id+"Contents";
		}
		this.labelContainer.style.display = this.display;
		try {
		  this.labelContainer.appendChild(toggleItem.label);
		  if(this.hasImages())  {
		  	var anchors = toggleItem.label.getElementsByTagName("A")
		  	if(anchors.length > 0)	{
				for (var i = 0; i < anchors.length; i++) { 
					var anchorElem = anchors[i];
					this.addImage( anchorElem, toggleItem.image, anchorElem.firstChild );
				}
			}
			else {
				toggleItem.image.onclick = this.toggle;
				this.addImage( this.labelContainer, toggleItem.image, toggleItem.label);
			}
		  }
		  this.element.appendChild(this.labelContainer);
		  this.contentContainer.appendChild(toggleItem.content);
		  this.element.appendChild(this.contentContainer);
		} catch (ex) {
			alert("ToggleWidget.render():inline display:"+ex.message);
		}
	} else {
		if( this.hasImages() ) {
			try{
				toggleItem.image.onclick = this.toggle;
				this.addImage( this.element, toggleItem.image);
			} catch( ex ) {
				alert("ToggleWidget.render():block display image:"+ex.message);
			}
		}
		try {
			this.element.appendChild(toggleItem.label);
			this.element.appendChild(toggleItem.content);
			this.element.appendChild(document.createElement("BR"));
		} catch( ex ) {
			alert("ToggleWidget.render():block display:"+ex.message);
		}
	}
	this.element.style.margin="0 0 1px 0px";
	this.element.style.display=this.display;
 }
}
ToggleWidget.prototype.addImage = function(parent, newElem, afterElem) {
  try {
	if(this.imagePlacement == "left" || afterElem) {
	  parent.insertBefore(newElem, afterElem );
	} else {
	  parent.firstChild.appendChild(newElem);
	}		  		
   } catch(ex) {
	 alert("ToggleWidget.render():toggle image:"+ex.message);
   }
}
ToggleWidget.prototype.toggle = function() {
	var my = this.togObj;
	var currentItem = my.toggles[this.id];
	for(var t in my.toggles) {
		var toggleItem = my.toggles[t];
		if(t != currentItem.id) {
			toggleItem.close( my.getImage( false ) );
		}
	}
	if(!currentItem.getState()) {
		currentItem.open( my.getImage( true ) );
	} else {
		currentItem.close( my.getImage( false ) );
	}
}
ToggleWidget.prototype.setOpenDisplay = function( index ) {
	var currentItem = this.toggles[this.element.id+"toggle"+index];
	if(!currentItem) return false;
	if(!currentItem.getState()) {
		currentItem.open( this.getImage( true ) );
	} else {
		currentItem.close( this.getImage( false ) );
	}
	return true;
}

ToggleItem = function (id, label,content) {
	this.id = id;
	this.label = label;
	this.content = content;
	this.content.id = id+"Content";
	this.className = this.label.className;
	this.image = null;
	this.state = false; //false=closed
}
ToggleItem.prototype.setState = function(state) {
	this.state = state;
}
ToggleItem.prototype.getState = function() {
	return this.state;
}
ToggleItem.prototype.close = function( img ) {
	if(img){
		this.image.src = img;
	}
	this.setState(false);
	this.content.style.position = "relative";
	this.content.style.display = "none";
	this.label.style.position = "relative";
	this.label.className = this.className+" closed";
}
ToggleItem.prototype.open = function( img ) {
	if(img){
		this.image.src = img;
	}
	this.setState(true);
	this.content.style.position = "relative";
	this.content.style.display = "block";
	this.label.style.position = "relative";
	this.label.className = this.className+" opened";
}
/**
 * @version $Id$ $Rev: 62886 $ $Date: 2009-07-07 07:50:56 -0700 (Tue, 07 Jul 2009) $
 */
function sendKeepAliveRequest(resetURL) {
	if(keepAliveCount < keepAliveMaxRequests)
	{
		dojo.io.bind({
			url: keepAliveURL,
			load: function(){ keepAliveCount++; },
			error:errorHandler,
			preventCache: true,
			mimetype: "text/plain"
		});
	}
	else
	{
		clearInterval(keepAliveTimerId);
		window.location = resetURL;
	}
	
}
function errorHandler( type, error ) 
{
    var msg = "Something went horribly wrong ...\n" +
        error.message;
}
function initKeepAlive(resetURL)
{
	if(keepAliveInterval > 0)
	{
		if(keepAliveTimerId)
		{
			clearInterval(keepAliveTimerId);
		}
		keepAliveTimerId = 
			setInterval('sendKeepAliveRequest(\''+resetURL+'\')',keepAliveInterval);
	}
}

var pagePosition = 0;
var overlayDisplay = false;
function overlayBack()
{
	if( !document.getElementById("overlay") )
	 {
		 var overElem = document.createElement("div");
		 overElem.setAttribute("id", "overlay" );
		 if(overlayDisplay)
		 	overElem.style.display = "";
		 else
		 	overElem.style.display = "none";
		try{	 	
			document.getElementsByTagName("body")[0].appendChild(overElem);
		}catch(ex){
			alert(ex+":"+ex.message);
		}
	 }
}
function hideOverlay()
{
	overlayDisplay = false;
	 var oOverLayDiv = document.getElementById("overlay");
	 oOverLayDiv.style.display = "none";
	 scroll(0,pagePosition);
}
function showOverlay()
{
     overlayDisplay = true;
	 var over = document.getElementById("overlay");
	 if(over)
	 	over.style.display = "";
	 pagePosition = document.body.scrollTop;
	 scroll(0,0);	
}
var hideDialog = new Object();
hideDialog.responseComplete = function(responseElements)
{
	hideOverlay();
}
var showDialog = new Object();
showDialog.responseComplete = function(responseElements)
{
	showOverlay();
}
function showAllItems(link)
{
	var itemName = link.hash.replace("#","");
	showMoreOverlay(itemName) ;
}
function hideAllItems(link)
{
	var itemName = link.hash.replace("#","");
	hideMoreOverlay(itemName) ;
}
function showMoreOverlay(sDivName)
{
	showOverlay();
	var oDiv = document.getElementById(sDivName);
	 var oCopy = oDiv.cloneNode(true);
	 oCopy.id = sDivName+"clone";
	 document.getElementsByTagName("body")[0].appendChild(oCopy);
	 document.getElementById(sDivName+"clone").className = "overlayContent";
	 document.getElementById(sDivName+"clone").style.display="";
}
function hideMoreOverlay(sDivName)
{
	 document.getElementById(sDivName+"clone").style.display="none";
	 hideOverlay();
}
  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return parseInt(curleft);
  }
 function makeImageMenu(obj)
 {
 	if(obj.ResultSet.Result.length > 0)
 	{
 		var div = document.getElementById("imagemenu");
 		var ul = document.createElement("UL");
		for(var i=0;result=obj.ResultSet.Result[i];i++)
		{
			var thumb = result.Thumbnail;
			if((typeof thumb== 'object') && (typeof result == 'object'))
			{
				var li = document.createElement("LI");
					li.style.position = "relative";
					li.style.zIndex = "1";
				li.onmouseover = function() {
					this.style.zIndex = "3";
				}
				li.onmouseout = function() {
					this.style.zIndex = "1";
				}
				var a = document.createElement("A");
					a.href = yahooURL;
					a.target = "_blank";
				var img = document.createElement("IMG");
					img.src = thumb.Url;
				img.onmouseover = function(){
					var imgXPos =  findPosX(this);
					var imgWidth = parseInt(thumb.Width);
					var totalWidth = imgXPos+imgWidth;
					var winWidth = parseInt(document.body.clientWidth);
					if(totalWidth > winWidth)
					{
						var rightMargin = (totalWidth - winWidth);
						this.style.left = "-"+rightMargin+"px";
					}				
					this.style.height= thumb.Height+"px";
					this.style.width= thumb.Width+"px";
					this.style.position = "absolute";
					this.style.zIndex = "3";
				}
				img.onmouseout = function(){
					this.style.left = "auto";
					this.style.height = "55px";
					this.style.width = "55px";
					this.style.position = "relative";
					this.style.zIndex = "1";
				}

				try{
					a.appendChild(img);
					li.appendChild(a);
					ul.appendChild(li);
				}catch(ex){
				  alert(ex);
				}
			}
		}
 		try{
 			div.appendChild(ul);
 		}catch(ex){
 			alert(ex)
 		}
	 }
 }
 
 function createAddReviewWindow( url )
{
	this.name = "catalog";
	resourceWindow = top.open( url, 'ResourceWindow','resizable=yes,scrollbars=yes,width=600,height=400');
	if( resourceWindow.opener == null )
		{
		resourceWindow.opener = window;
		}
	resourceWindow.focus();
	return false;
}

//Used to simulate maxWidth  css property for IE6.  This can be used for max-width properties that only need to be set once per page, lIke the Link+ logo. The property for the CSS expression will then get overwritten.
function  maxPixelWidth(elem, maxWidth) {
		elem.style.width =  elem.offsetWidth > maxWidth ?  maxWidth  + 'px'  :  elem.offsetWidth;
}

//Adjust dialog for IE6 (instantiate in a conditional comment for ie6)
function adjustDialogIE6() {
	dojo.lang.extend(dojo.widget.Dialog, {
		onShow: function() {
			this.animationInProgress=false;

			//Sets the height of the dialog box for IE6
			var height = dojo.html.getContentBox(this.domNode).height;
			var viewHeight = dojo.html.getViewport().height;
			this.domNode.style.height = height > viewHeight * .9 ? viewHeight *.9 + 'px' : height + 'px';

			this.checkSize();
		}

	});
}

//see call c1117016a
function toggleArea(areaId)
{	
	var area = document.getElementById(areaId);
    if (area == null)
        return;
        
    if (area.style.display == 'inline')
    {    
        area.style.display = "none";
    }
    else
    {
        area.style.display = "inline";
    }
}
