// Fix background image flickering in IE
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) { }

/*
JSTarget function by Roger Johansson, www.456bereastreet.com
Adapted to use jQuery by Matt Vanderpol, matt@atre.net
*/
var JSTarget = {
	init: function() {
	    for (var i=0; i<arguments.length; i++) {
		$(arguments[i]).each( function() { JSTarget.makeClickable($(this)); } );
	    }
	},
	makeClickable: function(n) {
	    if ($(n).is('.clickBound')) return; // Don't bind multiple events
	    $(n).click(JSTarget.openWin).addClass("clickBound");
	},
	openWin: function(e) {
		var event = (!e) ? window.event : e;
		e.stopPropagation();
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
		else {
		    this.blur();
		  var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) oWin.focus();
				return false;
			}
			oWin = null;
			return true;
		}
	}
};

/* Feature Box Functionality */
var FeatureBox = {
    
    init: function() { 
	$('#sidebarSecondary div.featureBox div.s').click(FeatureBox.click); 
    },
    click: function(e) {
	var handled = false;
	$(this).find('a.clickBound').each( function() { $(this).click(); handled = true; } );
	if (! handled) {
	    var url = '';
	    $(this).find('a').each( function() { url = this.getAttribute("href"); } );
	    window.location.href = url;
	}
    }
};

var FlashBox = {
  init: function() {
 	if ($.meta) $.meta.setType("elem", "script");
	$('#sidebarSecondary div.flashBox a.trigger').click(this.openWin);
 	$('#sidebarSecondary div.flashBox').click(this.click); 
  },
  openWin: function(e) {
	this.blur();
	var event = (!e) ? window.event : e;
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
	else {
		var width = $(this).data().width;
		var height = $(this).data().height;
		var oWin = window.open(this.getAttribute('href'), 'larger_image', 'height=' + height + ',width=' + width + ',menubar=false,toolbar=false');
		if (oWin) {
			if (oWin.focus) oWin.focus();
				return false;
		}
		oWin = null;
		return false;
	}
  },
  click: function(e) {
  	e.stopPropagation();
  	$(this).find('a.trigger').click();
  	return false;
  }
};

var ExpandingSpace = {
    init: function() {
	$('.expandingSpace a.trigger.show').click(ExpandingSpace.click);
    },
    click: function(e) {
	$(this).toggleClass('expanded');
	$(this).siblings('.triggerContent').toggle();
	this.blur();
	return false;
    }
};

var TabbedInterface = {
    init: function() {
	if ($.meta) $.meta.setType("elem", "script");
	$('.tabbedInterface ul.nav a').click(TabbedInterface.click);
    },
    click: function(e) {
	// Deactivate other tabs
	$(this).parent().siblings().removeClass("a");
	// Activate this tab
	$(this).parent().addClass("a");
	// Deactivate tab content and activate the one for this tab.
	$(this).parents('.tabbedInterface').find('.tabContent').hide().filter('.content'+$(this).data().tabNum).show();
	this.blur();
	return false;
    }
};

var ContentImage = {
    init: function() {
	if ($.meta) $.meta.setType("elem", "script");
	$('.contentImage a.trigger').click(ContentImage.viewLarger);
    },
    viewLarger: function(e) {
	this.blur();
	var event = (!e) ? window.event : e;
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
	else {
	    var width = $(this).data().width + 20;
	    var height = $(this).data().height + 20;
	    var oWin = window.open(this.getAttribute('href'), 'larger_image', 'height=' + height + ',width=' + width + ',menubar=false,toolbar=false');
	    if (oWin) {
		if (oWin.focus) oWin.focus();
		return false;
	    }
	    oWin = null;
	    return false;
	}
    }
}
/* Special search behavior */
var Search = {
  prompt: "Search", // default value - should get real value from markup
  init: function() { this.prompt = $('#searchText').focus(this.focus).blur(this.blur).val(); },
  focus: function() { if (this.value == Search.prompt) { this.value = ''; } },
  blur: function() { if (this.value.length == 0) { this.value = Search.prompt} }
};

var GlobalMenu = {
  init: function() { $('#globalMenu').hover(
    function(){$('#globalSitesMenu').show();},
    function(){$('#globalSitesMenu').hide();}
  )}
};

/* Provide footnotes on printed pages */
var Print = {
  linkNum: 0,
  addArg: function(k,v) {
      var printPage = $('#printPage');
      if (! printPage) return; 
      printPage.attr('href', printPage.attr('href')+'&'+encodeURIComponent(k)+'='+encodeURIComponent(v));
  },
  urlExists: function(u) {
    if (this.links[u]) return true;
    return false;
  },
  addUrl: function(u) {
    if (this.urlExists(u)) return;
    this.links[u] = ++this.linkNum;
  },
  numForLink: function(u) {
    if (! this.urlExists(u)) this.addUrl(u);
    return this.links[u];
  },
  links: { },
  init: function() {
    $('body').addClass('print');
    var footnoteLinks = $('<ol id="footnoteLinks"></ol>');
    $('#content a').not($('.tabbedInterface ul.nav a'))
                   .not($('.expandingSpace a.trigger'))
                   .not($('.doNotPrint'))
                   .each(function(i) {
		       var u = $(this).attr('href');
		       if (! Print.urlExists(u))
			   $('<li>'+u+'</li>').appendTo(footnoteLinks);
		       $('<sup>['+ Print.numForLink(u) +']</sup>').insertAfter($(this));
		   });
    if (Print.linkNum > 0) {
      // Only add footnotes if we have links to footnote
      $('<h2 id="footnoteLinksTitle">Links</h2>').appendTo("#content");
      footnoteLinks.appendTo("#content");
    }
  }
}
$(function() {
  if ($.getURLParam("print")!=null) {
    Print.init();
    if (window.print && $.getURLParam("print")==1) 
      setTimeout("window.print()", 500); // dialog on demand - delayed so that page loads before dialog appears
    return true;
  }
  $('#sidebarSecondary div.list li[a.pdf]').append('<span class="label">PDF</span>');
  JSTarget.init('a[@rel*=external]', 
		'a.pdf', 
		'a.download', 
		'a.print', 
		'#contactSales',
		$('#body a[@href^=http://]').not($('#searchResults a')), // Fully qualified links except search results
		'#body a[@href$=.pdf]'); // PDFs by URL
  Search.init();
  GlobalMenu.init();
  FeatureBox.init();
  ExpandingSpace.init();
  TabbedInterface.init();
  ContentImage.init();
  FlashBox.init();
});


function CreateControl(classid, codebase, id, src, width, height)
{
    var additional_keys = new Array();
    if (arguments.length > 6) {
	for(var i = 6; i < arguments.length; i+=2) {
	    // Make sure we have a key/value pair
	    if (i+1 == arguments.length) { break; }
	    additional_keys[arguments[i]] = arguments[i+1];
	}
    }
    document.write('<object classid="' + classid + '" codebase="' + codebase + '" width="' + width + '" height="' + height + '" id="' + id + '" align="middle">');
    document.write('<param name="allowScriptAccess" value="sameDomain" />');
    document.write('<param name="movie" value="' + src + '" />');
    document.write('<param name="quality" value="high" />');
    document.write('<param name="wmode" value="transparent" />');
    for (key in additional_keys) {
	document.write('<param name="' + key + '" value="' + additional_keys[key] + '" />');
    }
    document.write('<embed src="' + src + '" quality="high" wmode="transparent" width="' + width + '" height="' + height + '" name="' + id + '" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"');
    for (key in additional_keys) {
	document.write(' ' + key + '="' + additional_keys[key] + '"');
    }
    document.write(' />');
    document.write('</object>');
}

function setCookie(name, value, expires, path, domain, secure) {
  if (expires) {
  // 'expire' can be either a date string or a number of days
    if (!isNaN(parseInt(expires))) {
      var date = new Date();
      date.setTime(date.getTime()+(expires*24*60*60*1000));
      expires = date;
    }
    expires = "; expires="+expires.toGMTString();
  } else { expires = ""; }
  if (!path) { path = ""; }

  document.cookie = 
    name + "=" + escape(value) + expires + "; path="+path;
}

// Read/Delete cookie code from: http://www.quirksmode.org/
function getCookie(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 unescape(c.substring(nameEQ.length,c.length));
  }
  return null;
}

function delCookie(name) {
  createCookie(name,"",-1);
}

//-----------------------------------------------------------------------------
// rememberWW
//  This fucntion sets the cookie 'preferredCountry' if a checkbox 'remember'
//  is present and checked, or if a parameter is passed forcing the setting of
//  the cookie.
// Two arguments:
//  1 - The value of the cookie, it should be a URL or path.
//  2 - A boolean.  1 -> set the cookie regardless of the checkbox.
function rememberWW(site, forceSet) {
    // if 'forceSet' is true, we set the cookie irrespective of the checkbox status
    var daysValid = 90; // Number of days the cookie remains active
    var check = document.getElementById('remember');
    if ((check && check.checked) || forceSet) {
      setCookie('preferredCountry', site, daysValid, "/");
    }
    return false;
}

// See if we were linked to from the Global Site menu
function fromSiteMenu()
{
    var queryString = window.location.search;
    if (queryString.indexOf("fsm") != -1)
        return true;

    return false;
}
