// $Id$
// Copyright (c) 2006 IBM Corporation
// Owner: Corporate Webmaster (NUS_N_NIWWW)

function ibmIsv16() {
  	var meta = document.getElementsByTagName("meta");
	for (var i = 0; i < meta.length; i++) {
		if(meta[i].name.toLowerCase() == "source") {
			var c = meta[i].content;
			if(c.indexOf("v16") != -1) return true;
		}
	}
	if (document.getElementById("ibm-com")) return true;
	return false;
}

var ibmCreatePrintMastheadAttempts = 0;
var ibmCreatePrintMasthead = function () {
	var masthead = document.getElementById('ibm-masthead');
	if (masthead != null) {
		var img = document.createElement('img');
		img.setAttribute('src', '//www.ibm.com/i/v14/t/print-header.gif');
		img.setAttribute('width', '510');
		img.setAttribute('height', '32');
		img.setAttribute('id', 'ibm-print-masthead');
		masthead.insertBefore(img, masthead.firstChild);
	} else {
		// poll until the ibm-masthead DOM is ready
		if (ibmCreatePrintMastheadAttempts > 100) return;
		ibmCreatePrintMastheadAttempts++;
		window.setTimeout(ibmCreatePrintMasthead, 200);
	}
};
if (ibmIsv16()) ibmCreatePrintMasthead();

// Survey invitation
function ibmSurveySelect() {
	var dc = document.cookie;
	var prefix = 'ibmSurvey=';
	var begin = dc.indexOf(prefix);
	var now = new Date();
	if (begin == -1 || (begin > 0 && dc.indexOf("; " + prefix) == -1))
		if (window.location.href.indexOf(".ibm.com") > 0)
			document.cookie = prefix + now.getTime().toString() +
				"; path=/; domain=.ibm.com";
}
ibmSurveySelect();

// List of patterns for inclusion and exclusion from search keyword tracking
// The first matching rule applies (true = track, false = don't track)
var ibmSearchTermRules = [
	[ "/support/au/", false ],
	[ "//www.ibm.com/(.+/)?au/", true ],
	[ "/businesscenter/smb/(dk|fi|no|se)/", true ]
];
if (typeof RegExp != 'undefined' && typeof(encodeURIComponent) != 'undefined' &&
		typeof(document.forms['search-form']) == 'object') {
	for (var ibmSearchTermRule = 0; ibmSearchTermRule <
			ibmSearchTermRules.length; ibmSearchTermRule++) {
		var ibmSearchTermRegexp =
			new RegExp(ibmSearchTermRules[ibmSearchTermRule][0]);
        if (ibmSearchTermRegexp.test(window.location.href)) {
			if (ibmSearchTermRules[ibmSearchTermRule][1]) {
				document.forms['search-form'].onsubmit = function () {
					if (typeof sa_onclick == 'function' &&
							typeof sa_gif == 'string')
						sa_onclick("http://www.ibm.com/search/term/" +
							encodeURIComponent(
							document.forms['search-form'].q.value) + "/?re=" +
							encodeURIComponent(window.location.href));
					return true;
				};
			}
			break;
        }
	}
}

// Load OpenSearch description and feeds for compatible browsers
function ibmSearchOpensearchLink() {
	if (typeof document.createElement != 'undefined') {
		var head = document.getElementsByTagName('head');
		if (head.length > 0) {
			if (typeof window.external == 'object' &&
                                window.external &&
				typeof window.external.AddSearchProvider != 'undefined' &&
				window.location.hostname.indexOf('.ibm.com') != -1) {
				var link = document.createElement('link');
				link.setAttribute('rel', 'search');
				link.setAttribute('type',
					'application/opensearchdescription+xml');
				link.setAttribute('href',
					'http://www.ibm.com/search/opensearch/description.xml');
				link.setAttribute('title', 'IBM Search');
				head[0].insertBefore(link, head[0].firstChild);
			}
			// Restrict feeds to UTF-8 encoded searches
			if (window.location.href.toLowerCase().indexOf(
					'//www.ibm.com/search/?') != -1 &&
				window.location.href.toLowerCase().indexOf('en=utf') != -1) {
				var link = document.createElement('link');
				link.setAttribute('rel', 'alternate');
				link.setAttribute('type', 'application/rss+xml');
				link.setAttribute('href',
					'http://www.ibm.com/fscripts/search/opensearch/search.fcgi' +
					window.location.search + '&format=rss&startIndex=1');
				link.setAttribute('title', document.title + ' (RSS)');
				head[0].insertBefore(link, head[0].firstChild);
				var link = document.createElement('link');
				link.setAttribute('rel', 'alternate');
				link.setAttribute('type', 'application/atom+xml');
				link.setAttribute('href',
					'http://www.ibm.com/fscripts/search/opensearch/search.fcgi' +
					window.location.search + '&format=atom&startIndex=1');
				link.setAttribute('title', document.title + ' (ATOM)');
				head[0].insertBefore(link, head[0].firstChild);
			}
		}
	}
}

// New implementation of the ShareThis script.
//
// Usage: include the script and call the function just before the </body> tag
// 		ibmShareThis('digg,delicious');

// Call this like here:
//	ibmShareThisLoad(function(){
//			//defaults:
//			ibmShareThis();
//			//custom:
//			//ibmShareThis('digg,delicious', 0, 'ar', 'es');
//	});

function ibmShareThisLoad(func){
	if(document.getElementById('ibm-content-sidebar') &&
				document.getElementById('ibm-footer')) {
		func();
	}
	else {
		// poll until the ibm-masthead DOM is ready
		window.setTimeout(function(){ ibmShareThisLoad(func); }, 200);
 	}
}


var ibmShareThisServices = ''; // the selected services
var ibmShareThisPosition = -1; // position in the right nav
var	ibmShareArray = [];        // Information on all aggregators

// Main entry point
// Parameters:
//		services: 	string, defaults to 'digg,delicious'
//		postion: 	position in the leftnav, defaults to -1 (last item on page),
//                  indexed by 0!
//		cc: 		country code, if nothing is passed is read from metatags or
//                  defaults to us
//		lc: 		language code, if nothing is passed is read from metatags or
//                  defaults to en
//		encoding: 	encoding of page, if nothing is passed is read from page or
//                  defaults to utf8
function ibmShareThis(services, position, cc, lc, encoding)
{
	if(typeof encodeURIComponent == "undefined") {
		return; // do nothing for IE 5.01
	}

	// store the services
	ibmShareThisServices = services;
	ibmShareThisPosition = position;

	var tmp = ibmShareGetMetaInfo(cc, lc, encoding);
	var CC = tmp['CC'];
	var LC = tmp['LC'];
	var ENC = tmp['ENC'];
	if(ENC == 'utf8') ENC = '';

	// show wait indicator
	var sidebar = document.getElementById('ibm-content-sidebar');
	if(sidebar) {
		var img = document.createElement('img');
		img.setAttribute('src', '//www.ibm.com/i/common/content-loader.gif');
		img.setAttribute('id', 'ibm-sharethis-indicator');
		sidebar.appendChild(img);
	}

	var url = '//www.ibm.com/common/js/sharethis/' + CC + '/' + LC +
		'/shareThisConfig' + ENC + '.js';

	// load and do nothing, the loaded file does call our callback
	var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
	var head = document.getElementsByTagName('head');
	if (head.length > 0)
		document.getElementsByTagName('head')[0].appendChild(script);
}

// return language and country code based on the page information
function ibmShareGetMetaInfo(cc, lc, encoding)
{
	// defaults
	var CC;
	var LC;
	var ENC;

	// try to read from page
  	var meta = document.getElementsByTagName("meta");
	for (var i = 0; i < meta.length; i++) {
		if(meta[i].name == "DC.Language") {
			var lang = meta[i].content;
			if(lang.indexOf("_") != -1) {
				var items = lang.split("_");
				LC = items[0];
				CC = items[1];
			}
			else if(lang.indexOf("-") != -1) {
				var items = lang.split("-");
				LC = items[0];
				CC = items[1];
			}
			else if(lang != "") {
				LC = lang;
			}
		}
		if(meta[i].name == "IBM.Country") {
			var country = meta[i].content;
			if(country != "") {
				CC = country;
			}
		}
		if(meta[i].httpEquiv.toLowerCase() == "content-type") {
			var type = meta[i].content;
			if(type.indexOf("=") != -1) {
				ENC = type.substr(type.indexOf("=") + 1);
			}
		}
	}

	// nothing found? try passed defaults
	if(typeof cc != 'undefined' || typeof CC == 'undefined') {
		CC = typeof cc != 'undefined' ? cc : 'us';
	}
	if(typeof lc != 'undefined' || typeof LC == 'undefined') {
		LC = typeof lc != 'undefined' ? lc : 'en';
	}
	if(typeof encoding != 'undefined' || typeof ENC == 'undefined') {
		ENC = typeof encoding != 'undefined' ? encoding : 'utf8';
	}

  	CC = CC.toLowerCase();
	LC = LC.toLowerCase();
	ENC = ENC.toLowerCase();

	// Treat 'international' the same as 'US'
	if (CC == 'zz') CC	= 'us';
	if (ENC == 'utf-8') ENC = 'utf8';

	return { 'LC': LC, 'CC': CC, 'ENC': ENC };
}

function ibmShareGetCookie(name)
{
  var shareibmCheckdc = document.cookie;
  var shareibmCheckprefix = name + "=";
  var shareibmCheckbegin = shareibmCheckdc.indexOf("; " + shareibmCheckprefix);
  if (shareibmCheckbegin>=0)
  	shareibmCheckbegin += 2;
  else{
  	shareibmCheckbegin = shareibmCheckdc.indexOf(shareibmCheckprefix);
  	if (shareibmCheckbegin!=0){
  		return null;
  	}
  }
	shareibmCheckbegin += shareibmCheckprefix.length;
	var shareibmCheckend = shareibmCheckdc.indexOf(";", shareibmCheckbegin);
	return unescape((shareibmCheckend<0) ?
		shareibmCheckdc.substring(shareibmCheckbegin) :
		shareibmCheckdc.substring(shareibmCheckbegin, shareibmCheckend)
  );
}

// Constructor to create an aggregator object
function ibmShareMakeObject(code,name,imageUrl,url,title,info,wikiUrl)
{
  	this.code = code;
	this.name = name;
	this.imageUrl = imageUrl;
	this.url	= url;
	this.title = title;
	this.info = info;
	this.wikiUrl = wikiUrl;
}

function ibmShareToggleInfo()
{
	var info =
		ibmCommon.getElementsInClass(document.getElementById(
			'ibm-content-sidebar'), 'ibm-sharethis-info');
	for(var i = 0; i < info.length; i++) {
		if(info[i].style.display == "none") {
			info[i].style.display = "block";
		}
		else  {
			info[i].style.display = "none";
		}
	}
}

// This is the function point which is called by
// the JSON script that contains all translations and services
function shareBuildHtml(shareConfig)
{
	var services = typeof ibmShareThisServices != 'undefined' ?
		ibmShareThisServices : 'digg, delicious';
	var position = typeof ibmShareThisPosition != 'undefined' ?
		ibmShareThisPosition : -1;

	 // get data
	 var shareThisTitle = shareConfig.labels.shareThisTitle;
	 var moreInfoText = shareConfig.labels.moreInfoText;
	 var learnMoreText = shareConfig.labels.learnMoreText;
	 var empLearnText = shareConfig.labels.empLearnText;

	 var code,name,imageUrl,url,title,info,wikiUrl;

    // Build an array with the nodes
    var j = 0;
    for (var i=0;i<shareConfig.site.length;i++)
    {
      code = shareConfig.site[i].siteCode;
       // If the site is one the services indicated
       if(services.indexOf(code)!= -1){
          name = shareConfig.site[i].siteName;
          imageUrl = shareConfig.site[i].siteImageUrl;
          url = shareConfig.site[i].siteUrl;
          url += encodeURIComponent(window.location.href) + '&title=' +
			  encodeURIComponent(document.title);

	  title = shareConfig.site[i].siteTitle;
          info = shareConfig.site[i].siteInfo;
          wikiUrl = shareConfig.site[i].siteWikiUrl;
          ibmShareArray[j++] = new ibmShareMakeObject(code, name, imageUrl, url,
			  title, info,wikiUrl);
        }
    }

	// sort the array
	ibmShareArray.sort(function(a,b){
	    var x = a.name.toLowerCase();
	    var y = b.name.toLowerCase();
	    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });

	// build the module
	var txt = 	'<h2>' + shareThisTitle + '</h2>';
	txt = txt + '<div class="ibm-container-body"><ul class="ibm-link-list">';

	// build the link for each site
	var first = ' class="ibm-first"';
	for (i=0;i<ibmShareArray.length;i++){
		txt = txt + '<li' + first + '><a href="' + ibmShareArray[i].url + '" target="_blank" onclick="sa_onclick(\'http://www.ibm.com/externallink?sa_target=sharethis\'+this.href)"';
		txt = txt + ' style="background: url(' + ibmShareArray[i].imageUrl + ') no-repeat 4px 6px"';
		txt = txt + '>' + ibmShareArray[i].title + '</a></li>';
		first = "";
	}

	// add socialbooking info
	txt = txt + '<li><a class="ibm-forward-em-link" href="#" onclick="ibmShareToggleInfo(); return false;">' + learnMoreText + '</a></li>';
	for (var i=0;i<ibmShareArray.length;i++){
		txt = txt + '<li class="ibm-sharethis-info" style="display: none;"><p><b>' + ibmShareArray[i].name + '</b> ' + ibmShareArray[i].info + '</p>';
		txt = txt + '<a class="ibm-forward-link" href="' + ibmShareArray[i].wikiUrl + '" target="_blank" onclick="sa_onclick(\'http://www.ibm.com/externallink?sa_target=sharethis\'+this.href)">' + moreInfoText + '</a>' + '</li>';
	}

	// employee info
	if (ibmShareGetCookie('w3ibmProfile') != null) {
		txt = txt + '<li><a class="ibm-forward-em-link" href="http://w3.webmaster.ibm.com/innovation/sharethis/" target="_blank" onclick="sa_onclick(\'http://www.ibm.com/externallink?sa_target=sharethis\' + this.href)">' + empLearnText + '</a></li>';
	}

	txt = txt + '</ul>';

	// append it to the sidebar
	var sidebar = document.getElementById('ibm-content-sidebar');
	if(sidebar) {
		// hide wait indicator
		sidebar.removeChild(document.getElementById('ibm-sharethis-indicator'));
		// add text node
		var textnode = document.createElement('div');
		textnode.setAttribute('class', 'ibm-container');
		// this is for IE
		textnode.setAttribute('className', 'ibm-container');
		textnode.innerHTML = txt;

		if(sidebar.hasChildNodes() && position != -1) {
			var items = ibmCommon.getElementsInClass(sidebar, 'ibm-container');
			for(var i=0; i<items.length; i++) {
			if(i >= position) {
					sidebar.insertBefore(textnode, items[i]);
					return;	// we are done
				}
			}
		}

		// node was not added yet, add it at last item
		sidebar.appendChild(textnode);
	}

	return;
}

//
// ibmCommon Functions start here
//
String.prototype.normalizeSpace = function () {
	return this.replace(/\s+/g, ' ');
};

String.prototype.trim = function () {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
};

if (typeof ibmCommon != 'object' || ibmCommon == null) var ibmCommon = {};

ibmCommon.isDOM = (document.createElement && document.createTextNode &&
	document.getElementById && document.getElementsByTagName);
ibmCommon.closeBodyFuncs = [];
ibmCommon.hoverImages = [
	'//www.ibm.com/i/v16/buttons/add-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/arrow-primary-over.gif',
	'//www.ibm.com/i/v16/buttons/arrow-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/back-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/cancel-primary-over.gif',
	'//www.ibm.com/i/v16/buttons/cancel-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/cart-primary-over.gif',
	'//www.ibm.com/i/v16/buttons/cart-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/chat-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/customize-primary-over.gif',
	'//www.ibm.com/i/v16/buttons/customize-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/download-primary-over.gif',
	'//www.ibm.com/i/v16/buttons/download-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/email-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/go-over.gif',
	'//www.ibm.com/i/v16/buttons/pda-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/phone-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/refresh-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/remove-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/undo-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/video-secondary-over.gif',
	'//www.ibm.com/i/v16/buttons/view-primary-over.gif',
	'//www.ibm.com/i/v16/buttons/view-secondary-over.gif',
	'//www.ibm.com/i/v16/overlay/ibm-footer.gif',
	'//www.ibm.com/i/v16/overlay/ibm-footer.png',
	'//www.ibm.com/i/v16/overlay/ibm-masthead.gif',
	'//www.ibm.com/i/v16/overlay/ibm-masthead.png',
	'//www.ibm.com/i/v16/overlay/ibm-middle.gif',
	'//www.ibm.com/i/v16/overlay/ibm-middle.png',
	'//www.ibm.com/i/v16/t/geo-gradient-highlight.gif',
	'//www.ibm.com/i/v16/t/ibm-tab-hover-background.gif',
	'//www.ibm.com/i/v16/t/leftnav-overview-highlight.gif',
	'//www.ibm.com/i/v16/t/leftnav-selected.gif',
	'//www.ibm.com/i/v16/t/masthead-links-gradient-highlight.gif',
	'//www.ibm.com/i/v16/t/masthead-submit-highlight.gif',
	'//www.ibm.com/images/account/profile/animation.gif'
];
ibmCommon.onloadFuncs = [];

ibmCommon.addScript = function (url) {
	var nl = document.getElementsByTagName('head');
	if (nl.length < 1) return null;
	var s = document.createElement('script');
	s.id = ibmCommon.generateId();
	s.setAttribute('type', 'text/javascript');
	s.setAttribute('src', url);
	nl.item(0).appendChild(s);
	return s.id;
};

ibmCommon.classNamesToArray = function (el) {
	if (!el) throw 'Invalid argument.';
	if (typeof el.className != 'string') return [];
	return el.className.normalizeSpace().trim().split(' ');
};

ibmCommon.closeBody = function () {
	for (var i = 0; i < ibmCommon.closeBodyFuncs.length; i++)
		if (!ibmCommon.closeBodyFuncs[i].obj)
			ibmCommon.closeBodyFuncs[i].func(ibmCommon.closeBodyFuncs[i].args);
		else
			ibmCommon.closeBodyFuncs[i].func.call(
				ibmCommon.closeBodyFuncs[i].obj,
				ibmCommon.closeBodyFuncs[i].args
			);
};

ibmCommon.deleteClassName = function (el, cn) {
	if (!ibmCommon.inClass(el, cn)) return;
	var cns = ibmCommon.classNamesToArray(el);
	var ncns = [];
	for (var i = 0; i < cns.length; i++)
		if (cns[i] != cn) ncns[ncns.length] = cns[i];
	el.className = ncns.join(' ');
};

ibmCommon.generateId = function () {
	var nid;
	do {
		nid = 'gi-' + Math.round(Math.random() * 0xFFFFFFFF).toString(16);
	} while (document.getElementById(nid) != null);
	return nid;
};

ibmCommon.getElementsInClass = function (el, cn) {
	var nl = [];
	if (typeof el.nodeType == 'undefined') return nl;
	switch (el.nodeType) {
	// ELEMENT_NODE, DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE
	case 1: case 9: case 11:
		if (ibmCommon.inClass(el, cn)) nl[nl.length] = el;
		if (el.hasChildNodes())
			for (var i = 0; i < el.childNodes.length; i++)
				nl = nl.concat(ibmCommon.getElementsInClass(
					el.childNodes.item(i), cn));
		break;
	}
	return nl;
};

ibmCommon.getEventX = function (ev) {
	return (ev.clientX + document.body.scrollLeft -
		document.body.clientLeft) || ev.pageX;
}

ibmCommon.getEventY = function (ev) {
	return (ev.clientY + document.body.scrollTop -
		document.body.clientTop) || ev.pageY;
}

ibmCommon.inClass = function (el, cn) {
	if (typeof el.className != 'string') return false;
	var cns = el.className.trim().normalizeSpace().split(' ');
	for (var i = 0; i < cns.length; i++) if (cns[i] == cn) return true;
	return false;
};

ibmCommon.onload = function () {
	for (var i = 0; i < ibmCommon.onloadFuncs.length; i++)
		if (!ibmCommon.onloadFuncs[i].obj)
			ibmCommon.onloadFuncs[i].func(ibmCommon.onloadFuncs[i].args);
		else
			ibmCommon.onloadFuncs[i].func.call(
				ibmCommon.onloadFuncs[i].obj,
				ibmCommon.onloadFuncs[i].args
			);
};

ibmCommon.preloadHoverImages = function () {
	ibmCommon._loadImages = [];
	for (var i = 0; i < ibmCommon.hoverImages.length; i++) {
		var img = new Image;
		img.src = ibmCommon.hoverImages[i];
		ibmCommon._loadImages[ibmCommon._loadImages.length] = img;
	}
};

ibmCommon.putCloseBodyFunction = function (obj, func, args) {
	ibmCommon.closeBodyFuncs[ibmCommon.closeBodyFuncs.length] = {
		'obj': obj,
		'func': func,
		'args': args
	};
};

ibmCommon.putOnloadFunction = function (obj, func, args) {
	ibmCommon.onloadFuncs[ibmCommon.onloadFuncs.length] = {
		'obj': obj,
		'func': func,
		'args': args
	};
};

ibmCommon.setOnloadHandler = function () {
	if (typeof window.onload == 'function')
		ibmCommon.putOnloadFunction(null, window.onload, []);
	window.onload = ibmCommon.onload;
};

// back-compat
var IBMCommon = ibmCommon;

// this must always be the last thing in this script
//ibmCommon.setOnloadHandler();
ibmCommon.preloadHoverImages();
ibmSearchOpensearchLink();

