/******************************************************************************
 *	
 *	NAVIGATION OBJECT - niclas@bindows.net - 2007
 *	

 *	GENERAL TODO:s
 *	#1: add html index and autohide 
 *	#2: fix the other TODO:s :o)
 *	#3: add bindows compat test and message
 */
 
var NAV = {
	
	/**************************************************************************
	 *	
	 *	Namespaces for available hosts
	 *	
	 *	This is where you should define domains. Hosts and their aliases 
	 *	are defined in separate files, eg. www.bindows.com.js along with the 
	 *	structure for that host.
	 *	
	 */
	 com: {
		bindows: {},
		i_see: {},
		infiview: {},
		_1800mbt: {},
		sweeft: {}
	},
	net: {
		bindows: {},
		i_see: {},
		infiview: {},
		sweeft: {}
	},
	org: {
		sweeft: {}
	},

	/**************************************************************************
	 *	
	 *	Methods for NAV object
	 *
	 */
	 
	/*
	 *	HTML for top header, typically the main logo and link
	 */
	getTopHeader: function( sRootPath ) {
		return '<a href="'+this.sCurrentPath+this.MAIN_SITE+'"><img src="'+this.sCurrentPath+this.MAIN_SITE+'images/mb_logo.gif" alt="MB Technologies" border="0"/></a>';
    },

    MAIN_SITE: "mb.bindows.net/",

    /*
	 *	HTML for top navigation, used for company overall navigation
	 */
	getTopNav: function( sRootPath ) {
		// TODO: fetch from the MAIN site object (mb.bindows.net)
        return [
                '<div id="topNavStart"><img alt="" src="', this.sCurrentPath, this.domainPath, '/images/topNav-start.gif" border="0"></div>',
                '<div id="topNavContent">&nbsp;&nbsp;&nbsp;<a href="', this.sCurrentPath, this.MAIN_SITE, '" alt="About MB Technologies">Company</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="',
                this.sCurrentPath, this.MAIN_SITE, 'products"',
                this.nameSpaceRoot == this.net.bindows.mb ? '' : ' class="active',
                '">Products</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="',
                this.sCurrentPath, this.MAIN_SITE, 'news">News</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="',
                this.sCurrentPath, this.MAIN_SITE, 'contact">Contact</a>&nbsp;&nbsp;&nbsp;</div>'
            ].join("");
        //<div id="topNavEnd"><img alt="" src="http://localhost/bindows/Sites/new.bindows.net/images/topNav-end.gif" border="0"></div>\

	},

	/*
	 *	HTML for SITE sub header, typically the global payoff for site
	 */
	getTopSubHeader: function( sRootPath ) {

		return '<p>'+this.nameSpaceRoot.sDescription+'</p>';
	},

	/*
	 *	HTML for head block for navigation block, typically the site/product logo and link
	 */
	getNavHeader: function( sRootPath ) {

		// TODO: fetch link etc from the CURRENT site object
		return '<a href="'+sRootPath+'"><img src="' + this.sCurrentPath + this.domainPath +
				'/' + this.nameSpaceRoot.sImage +
				'" alt="'+ this.nameSpaceRoot.sDescription + '" border="0"/></a>';
	},

	/*
	 *	HTML for page footer
	 */
	getPageFooter: function( sRootPath ) {

		// TODO: fetch this from ???
		return ( [
			'<div class="pageFooter">',
			'<div style="text-align:left;"><p>Last updated: ', NAV.formatDate( new Date(document.lastModified) ),'</p></div>',
			'<div style="text-align:right;"><p>&copy;2003-2010 MB Technologies</p></div>',
			'</div>',
			'<div class="pageFooter2"><p>',
			'<a href="', this.sCurrentPath, this.MAIN_SITE, 'legal/index.html#RefundPolicy">Refund Policy</a>&nbsp;&nbsp;|&nbsp;&nbsp;',
			'<a href="', this.sCurrentPath, this.MAIN_SITE, 'legal/index.html#PrivacyPolicy">Privacy Statement</a>&nbsp;&nbsp;|&nbsp;&nbsp;',
			'<a href="', this.sCurrentPath, this.MAIN_SITE, 'legal/index.html#TransactionPolicy">Transaction Security</a></p>',
			'</div>'
		] ).join("");
	},

	/*
	 *	HTML for navigation node
	 */
	getNodeHtml: function( oNode, sUri ) {
		// set reusable uri
		oNode.sUriPart = (oNode.sUri.match('^http://')) ? oNode.sUri : sUri + oNode.sUri;
		// set reusable description
		oNode.nodeDesc = oNode.sDescription || oNode.sTitle;

		var classNameHtml;

		if ( this.localUri.match( '^' + oNode.sUriPart ) ) {
			classNameHtml = ' class="activeHref"';
			NAV.activeNode = oNode;
		}
		var n = [
			'<li><a href="', oNode.sUriPart, '"', classNameHtml, ' title="' + oNode.nodeDesc + '"','>',
			oNode.sTitle, '</a>', this.getChildNodes( oNode, oNode.sUriPart ),
			'</li>\n'
		];
		return n.join('');

	},

	/*
	 *	Child nodes
	 */
	getChildNodes: function( oNode, sUri ) {
		if ( this.nameSpaceRoot.sUri != this.localUri && oNode.bIsDefault || oNode.bHideChildren ) {
			return;
		}
		else if ( ( oNode.aChildren && this.localUri.match( oNode.sUri ) ) || this._allExpanded || oNode.bDefaultExpanded ) {
			var c = [ '<ul>' ];

			for ( var i = 0; i < oNode.aChildren.length; i++ ) {
				c.push( this.getNodeHtml( oNode.aChildren[i], sUri ) );
			}
			c.push( '</ul>\n' );
			return c.join('');
		}
	},

	/*
	 *	Navigation tree starting at node
	 // TODO: adjust this to not necessarily be the main method
	 */
	getNavTree: function ( sRootPath ) {

		// set up local uri
		this.localUri = sRootPath + window.location.toString().replace(/\S*[^\.\/]+\.[^\.\/]+\.[^\.\/]+\//,'');

		// TODO: reuse this or remove
		// set current root path
		this.rootPath = sRootPath;

		// create and return current navigation tree
		return this.getChildNodes( this.nameSpaceRoot, sRootPath );
	},

	/*
	 *	Zero fill dates
	 */
	formatDate: function (d) {
		function f(n) {
			return n < 10 ? "0" + n : n;
		}
		return d.getFullYear() + "-" + f(d.getMonth() + 1) + "-" + f(d.getDate());
	},

	/*
	 *	initalize
	 */
	init: function () {

		var u = window.location.toString();

		// replace any characters not suitable in js
		u = u.replace(/\-/,'_');
		u = u.replace(/(\.)(\d)/, "$1_$2")

		// regexp for extracting full host name / folder
		// TODO: improve this to also cover alternate number of levels
		var re = /(.*\/)([^\.\/]+)\.([^\.\/]+)\.([^\.\/]+)\//;

		// match and reverse
		var a = re.exec(u);

		// Set current path to top
		this.sCurrentPath = a[1];

		// set which host/domain we are using
		this.domainPath = a[2]+'.'+a[3]+'.'+a[4];

		// set which site is current root
		this.nameSpaceRoot = NAV[a[4]][a[3]][a[2]];
	},

	initBindowsLinks: function (/*sVersion*/) {
		if (this._bindowsPath) {
			alert("Bindows can only be included once.");
			return;
		}

		// TODO: Where will the Bindows dists be?
		this._bindowsPath = this.sCurrentPath + this.domainPath + "/bindows/html/";

		if (this.supportsBindows())
			document.write("<script type=\"text/javascript\" src=\"" +
						   this._bindowsPath + "/js/bilauncher.js\"></script>");
		else
			window.biExec = function () {
				alert("Bindows requires Internet Explorer 5.5+, Mozilla 1.4+ or Safari with at least WebKit 552+");
			};
	},
	writeLaunchLink: function (sAdf, sLinkText) {
		if (!this._bindowsPath)
			this.initBindowsLinks();

		document.write("<a href='#' onclick='biExec(\"" + this._bindowsPath + "\", \"" + sAdf + "\"); return false'>"
				+ sLinkText + "</a>");
	},

	/*
	 *	Magic property for expanding the whole tree for the current site
	 */
	_allExpanded: false,

	/*
	 *	Get related content
	 *	- create html for array of related pages.
	 *
	 *	Based on which properties are available for a node, select a template and create
	 *	the HTML for representing that page in the Related Content Area of the page.
	 */
	getRelatedContent: function ( aRelated, sTemplate, nMax ) {
		if (aRelated && aRelated.length > 0) {

			// define replace functionallity
			var sb = [];
			var testStr	=	"%%%([^%]+)%%%";
			var re = new RegExp(testStr,"g");

			var f = function( o ){
				return function(){
					return o[arguments[1]]
				}
			}

			// parse and populate template for each node
			var l = (nMax && nMax < aRelated.length) ? nMax: aRelated.length;
			for ( var i = 0; i < l ; i++ ) {

                var relatedItem = aRelated[i];
                var templateName = sTemplate;

                if (typeof relatedItem == "string") {
                    // Parse out template name
                    if (/(.*):(.*)/.test(relatedItem)) {
                        relatedItem = RegExp.$1;
                        templateName = RegExp.$2;
                    }
                }
                var o = (relatedItem instanceof Object) ? relatedItem : window[ 'item_' + relatedItem ];
                var t;

				// set url for links
				o.sUrl = (o.sRelUri.match('^http://')) ? o.sRelUri : this.sCurrentPath + o.sRelUri;

				// set standard fail-over properties
				o.sHighlightText		= o.sHighlightText	|| o.sDescription;
				o.sHighlightTitle		= o.sHighlightTitle	|| o.sTitle;
				o.sHighlightDescription	= o.sDescription	|| o.sTitle;

				// choose template
				if (templateName) {
					t = NAV.templates[templateName];
				}
				else {
					if (o.sHighlightImage) {
						o.sHighlightImage =  this.rootPath + o.sHighlightImage
						t = NAV.templates.highLightImage;
					}
					else {
						t = NAV.templates.highLight
					}
				}
				sb.push( t.replace( re, f(o) ) );
			}
			return sb.join('');
		}
		else {
			return '';
		}
	},

	// writeSupportedStyles copied from old web site

	/*
	 * Writes CSS information to hide "not supported" messages and show
	 * Bindows functionality identified by CSS class names.
	 * class=".not-supported" => hidden is supported
	 * class=".partial-support" => shown if WebService supported
	 * class="span.partial-support" => shown if WebService supported (used in text)
	 * class=".supported" => shown if at all supported
	 * class="span.supported" => shown if at all supported (used in text)
	 */
	writeSupportedStyles: function () {
		if (this.supportsBindows()) {
			document.write('<style type="text/css">' +
				".supported { display: block !important; }" +
				"span.supported { display: inline !important; }");
			if (!this.supportsWebService())
				document.write(".partial-support { display: block!important; }" +
					"span.partial-support { display: inline !important; }");
			document.write(".not-supported { display: none !important; }" +
				"</style>");
		}
	},
	/*
	 * Returns true is WebServices are supported (IE only)
	 * TODO: do we still not support the WebServices for Mozilla
	 */
	supportsWebService: function () {
		return navigator.product != "Gecko";
	},
	/*
	 * Returns true if Bindows is supported (IE or MOZ).
	 */
	supportsBindows: function () {
		if ( typeof BiLauncher == "function" )
		{
			var l = new BiLauncher;
			return l.getSupported();
		}

		var ua = navigator.userAgent;
		var opera = /opera/i.test(ua);
		if ( opera )
			return false;
		var ie = /msie/i.test( ua );
		var moz = navigator.product == "Gecko";
		var safari = /Safari\//i.test( navigator.userAgent );
		var p = navigator.platform.toLowerCase();
		var v;

		if ( ie )
		{
			/MSIE\s+([^\);]+)(\)|;)/.test( ua );
			v = RegExp.$1;
			return !(p != "win32" && p != "win64" || // Is win64 really supported?
			         v < "5.5");

		}
		else if (safari) {
			var versionRegExp = /WebKit\/([\.\d]+)/;
			versionRegExp.test(navigator.userAgent);
			var version = RegExp.$1;
			versionNumber = parseFloat(version);
			return versionNumber >= 522;
		}
		else if ( moz )
		{
			/rv\:([^\);]+)(\)|;)/.test( ua );
			v = RegExp.$1;
			return v >= "1.4";

		}

		return false;
	}
};

/*
 * Templates for related content
 */
NAV.templates = {

			highLightImage: '<a href="%%%sUrl%%%" title="%%%sDescription%%%"><h2>%%%sHighlightTitle%%%</h2></a>\
				<div><a href="%%%sUrl%%%" title="%%%sHighlightDescription%%%">\
				<img alt="%%%sDescription%%%" src="%%%sHighlightImage%%%" border="0">\
				</a></div>',

			highLight: '<a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"><h2>%%%sHighlightTitle%%%</h2></a>\
				<p>%%%sHighlightText%%%<a href="%%%sUrl%%%" \
				alt="%%%sDescription%%%"> &raquo;&raquo;</a></p>',

			subPage: '<a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"><h2>%%%sHighlightTitle%%%</h2></a>\
				<p>%%%sHighlightText%%% <a href="%%%sUrl%%%" \
				alt="%%%sDescription%%%">read&nbsp;more&nbsp;&raquo;&raquo;</a></p>',

			subPageDiv: '<div><a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"><h2>%%%sHighlightTitle%%%</h2></a>\
				<p>%%%sHighlightText%%% <a href="%%%sUrl%%%" \
				alt="%%%sDescription%%%">read&nbsp;more&nbsp;&raquo;&raquo;</a></p></div>',

			subCategory: '<a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"><h2>%%%sHighlightTitle%%%</h2></a>\
				<script type="text/javascript">\
					document.write( NAV.getRelatedContent( window["item_%%%nNodeId%%%"].aChildren, \'subCategoryPage\',10 ) );\
				</script>',
			
			subCategoryPage: '<p><a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%">%%%sHighlightTitle%%%</a></p>\
				<p>%%%sHighlightText%%% <a href="%%%sUrl%%%" \
				alt="%%%sDescription%%%"> &raquo;&raquo;</a></p><hr>',
			
			gaugeClock:	'<!-- A Gauge -->',
				
			googleAds: '<!-- Google Ads -->\
				<div class="widget AdSense">\
				  <div class="widget-content">\
				  <script type="text/javascript">\
				  google_ad_client = "pub-5872988685618509";\
				  google_ad_slot = "2955382697";\
				  google_ad_width = 245;\
				  google_ad_height = 250;\
				  </script>\
				  <script type="text/javascript"\
				  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">\
				  </script>\
				</div>\
				</div>\
				<p> </p>',
				
			newsFlash: '<h2>NEWSFLASH</h2>\
				<h3><a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%">%%%sHighlightTitle%%%</a></h3>\
				<p>%%%sHighlightText%%%\
				<a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"> &raquo;&raquo;</a>\
				</p>',

			latestNews: '<a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"><h2>Latest %%%sHighlightTitle%%%</h2></a>\
				<script type="text/javascript">\
					document.write( NAV.getRelatedContent( window["item_%%%nNodeId%%%"].aChildren, \'latestNewsPart\',10 ) );\
				</script>',
			
			latestNewsPart: '<p><a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%">%%%sHighlightTitle%%% &raquo;&raquo;</a></p><hr>',

			latestHotNews: '<a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%"><h2>Latest %%%sHighlightTitle%%%</h2></a>\
				<script type="text/javascript">\
					document.write( NAV.getRelatedContent( window["item_%%%nNodeId%%%"].aChildren, \'latestHotNewsPart\',3 ) );\
				</script>',
			
			latestHotNewsPart: '<p><a href="%%%sUrl%%%" alt="%%%sHighlightDescription%%%">%%%sHighlightTitle%%%</a></p>\
				<p>%%%sHighlightText%%% <a href="%%%sUrl%%%" \
				alt="%%%sDescription%%%"> &raquo;&raquo;</a></p><hr>'


};

NAV.writeSupportedStyles();
