YUI.add('bokugresizer', function(Y){    
    Y.Bokugresizer = Y.Base.create('bokugresizer', Y.Widget, [], { 
		initializer : function( config ) {
			
		},
		
		loadAndResize : function(config) {
			// determine current tab height
			var oldtabheight = Y.one('#' + config.olddiv).getComputedStyle('height');

			// move newdiv off screen so that we can measure its height
			Y.one('#' + config.newdiv).setStyles({overflow:'hidden',position:'absolute',display:'block'});				
			Y.one('#' + config.newdiv).removeClass('displaynone');							
			var newtabheight = Y.one('#' + config.newdiv).getComputedStyle('height');										

			// remove absolute positioning from newdiv, preset height
			Y.one('#' + config.newdiv).setStyles({position:'relative',height:oldtabheight});			

			// hide olddiv
			Y.one('#' + config.olddiv).setStyles({
				display:'none',
				height:''
			});	
			
			if (config.animDuration) {
				// use provided animDuration, overriding default
				this.set('animDuration', config.animDuration);
			}

			// start transition
			if (oldtabheight == newtabheight) {
				// no transition necessary, just show new element
				Y.one('#' + config.newdiv).setStyles({
					display:'block',
					visibility:'visible',
					height:''
				});												
			}
			else {
				Y.one('#' + config.newdiv).transition({
					easing:'ease-out',
					duration:this.get('animDuration'),
					height:newtabheight
				}, function() {
					// reveal contents
					Y.one('#' + config.newdiv).setStyles({
						display:'block',
						overflow:'visible',
						height:''
					});				
				});					
			}
		}	
	}, {
        ATTRS : { 
			animDuration : {
				value : 0.5
			}
		}
		
	});
    
}, '0.1', {requires: ['base-build', 'widget', 'node', 'transition']});

function webkit() {
	
	this.waitHTML = '<div class="waitHTML"></div>';
	this.lastbanner = 0;
	this.bannerspaused = false;	
	
	// user agent sniffing for IE 6 and 7
	this.isIE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
	this.isIE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
	this.isIE8 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 8;
	
	this.cursorLink = function() {
		webkit.Y.one(document.body).addClass('cursorLink');
	}

	this.cursorClear = function() {
		webkit.Y.one(document.body).removeClass('cursorLink');
	}
	
	this.cacheset = function(owner, datarequest, object) {
		// assigns object to webkitcache
		YUI().use('cache', 'node', function(Y) {
			if (!webkit.wkcache) {
				webkit.wkcache = new Y.Cache({max:10});
			}
			
			if (Y.one('#' + object)) {
				// cache request sent as dom ID rather than node object
				object = Y.one('#' + object);
			}
			
			webkit.wkcache.add(owner + '_' + datarequest, {
				id:object.get('id'),
				innerHTML:object.getContent()
			});
		})			
	}
	
	this.cacheget = function(owner, datarequest) {
		// checks to see if cache for datarequest exists
		
		if (webkit.wkcache && webkit.wkcache.retrieve(owner + '_' + datarequest)) {
			return true;
		}
		return false;
	}
	
	this.cacheoutput = function(owner, datarequest, object) {
		var cacheObj = webkit.wkcache.retrieve(owner + '_' + datarequest);
		webkit.Y.one('#' + cacheObj.response.id).setContent(cacheObj.response.innerHTML);
	}
	
	this.modinit = function(module, customCSS, callbackFunc, configVars) {
		var configObj = {
			modules: {
				'modalbox': {
					requires: ['modalboxcss'],
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/modalbox/modalbox.js?wk=' + webkit.moduleRevision)
				},
				'modalboxcss': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/modalbox/modalbox.css?wk=' + webkit.moduleRevision),
					type: 'css'
				},
				'swfobject': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/swfobject1-5/swfobject.js?wk=' + webkit.moduleRevision)
				},
				'photogallery': {
					requires: ['photogallerycss','lightwindow'],
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/gallery.js?wk=' + webkit.moduleRevision)
				},
				'photogallerycss': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/CSS/photogallery_defaults.css?wk=' + webkit.moduleRevision),
					type: 'css'
				},
				'galleryrotate': {
					requires: ['galleryrotatecss'],
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/galleryrotate.js?wk=' + webkit.moduleRevision)
				},
				'galleryrotatecss': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/CSS/galleryrotate_defaults.css?wk=' + webkit.moduleRevision),
					type: 'css'
				},
				'lightwindow': {
					requires: ['lightwindowcss'],
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/lightwindow/javascript/lightwindow.js?wk=' + webkit.moduleRevision)
				},
				'lightwindowcss': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/lightwindow/css/lightwindow.css?wk=' + webkit.moduleRevision),
					type: 'css'
				},
				'soundclips': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/soundclips.js?wk=' + webkit.moduleRevision)
				},
				'soundclips-mobile': {
					fullpath: (webkit.jsondata.basepath + 'nm_webkit/libs/soundclips.js?wk=' + webkit.moduleRevision)
				},
				'eventscalendar_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/user_CSS/' + customCSS + '?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'eventscalendar_defaultcss': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/eventscalendar_defaults.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'eventscalendar': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/calendar.js',
					requires: ['eventscalendar_css','eventscalendar_defaultcss?wk=' + webkit.moduleRevision]
				},
				'storeold_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/store_defaults.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'storeold': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/store.js?wk=' + webkit.moduleRevision,
					requires: ['storeold_css']
				},
				'store_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/store_defaultsnew.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'store': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/storenew.js?wk=' + webkit.moduleRevision,
					requires: ['store_css']
				},
				'lightbox_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/lightbox/css/lightbox.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'lightbox': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/lightbox/js/lightbox.js?wk=' + webkit.moduleRevision,
					requires: ['lightbox_css']
				},
				'mailinglist_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/mailinglist_defaults.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'mailinglist': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/mailinglist.js?wk=' + webkit.moduleRevision,
					requires: ['mailinglist_css']
				},
				'contact_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/contactform_defaults.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'contact': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/contact.js?wk=' + webkit.moduleRevision,
					requires: ['contact_css']
				},
				'links_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/links_defaults.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'links': {
					requires: ['links_css']
				},
				'ytgallery_css': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/ytgallery_defaults.css',
					type: 'css'
				},
				'ytgallery': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/ytgallery.js?wk=' + webkit.moduleRevision,
					requires: ['ytgallery_css']
				},
				'fbshare': {
					fullpath: 'http://static.ak.fbcdn.net/connect.php/js/FB.Share?wk=' + webkit.moduleRevision
				},
				'jplayer': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/jplayer/jquery.jplayer.min.js?wk=' + webkit.moduleRevision,
					requires: ['jquery', 'soundclips-mobile']
				},
				'jquery': {
					fullpath: 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js?wk=' + webkit.moduleRevision
				},
				'tinymce' : {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/tiny_mce/tiny_mce.js?wk=' + webkit.moduleRevision
				},
				'ckeditor' : {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/libs/ckeditor/ckeditor.js?wk=' + webkit.moduleRevision
				},
				'dbmanager_css': {
					fullpath: webkit.jsondata.basepath + 'styles/dbmanager.css?wk=' + webkit.moduleRevision,
					type: 'css'
				},
				'dbmanager': {
					fullpath: webkit.jsondata.basepath + 'js/dbmanager.js?wk=' + webkit.moduleRevision,
					requires: ['dbmanager_css']
				},
				'discography': {
					fullpath: webkit.jsondata.basepath + 'nm_webkit/CSS/discography_defaults.css',
					type: 'css',
					requires: ['lightbox']
				}
			}
		};
		
		switch (module) {
			case 'modalbox':
			YUI(configObj).use('modalbox', function(Y) {
				Y.log('init modalbox');
				if (callbackFunc) {
					callbackFunc();
				}
			});
			break;	
			case 'swfobject':
			YUI(configObj).use('swfobject', function(Y) {
				Y.log('init SWFObject');			
			});
			break;		
			case 'photogallery':
			YUI(configObj).use('photogallery', function(Y) {
				Y.log('init photogallery');	
				webkitgallery.galleryObservers();										
			});
			break;
			case 'galleryrotate':
			YUI(configObj).use('galleryrotate', function(Y) {
				Y.log('init rotating gallery');	
				galleryrotate.initRotation();										
			});
			break;
			case 'soundclips':
			YUI(configObj).use('soundclips', function(Y) {
				Y.log('init soundclips ' + webkit.jsondata.medialoaderID);
				soundclips.soundClipsListing();
				if (webkit.jsondata.medialoaderID) { 
					soundclips.mediaLoaderObservers(webkit.jsondata.medialoaderID); 
				}
			});
			break;
			case 'soundclips-mobile':
			YUI(configObj).use('soundclips-mobile', function(Y) {
				Y.log('init soundclips mobile');
				soundclips.soundClipsListingMobile();
				if (webkit.jsondata.medialoaderID) { 
					soundclips.mediaLoaderMobileObservers(); 
				}			
			});
			break;
			case 'lightbox':
			YUI(configObj).use('lightbox', function(Y) {
				Y.log('init lightbox');
				
				$$('#pagecontent .lightbox').each(function(o) {
					// cancel AJAX links function  
					o.stopObserving('click');
				});
				initLightbox();				
			});
			break;
			case 'lightwindow':
			YUI(configObj).use('lightwindow', function(Y) {
				Y.log('init lightwindow');
				lightwindowInit();
			});
			break;
			case 'eventscalendar':
			YUI(configObj).use('eventscalendar', function(Y) {
				Y.log('init eventscalendar');
				nmcalendar.initCalendar();
				if (typeof calCustomObservers == "function") {
					calCustomObservers();
				}
			});
			break;
			case 'store':
			YUI(configObj).use('store', function(Y) {
				Y.log('init store');
				nmstore.initObservers();
				if (callbackFunc) {
					callbackFunc(configVars);
				}
			});
			break;
			case 'mailinglist':
			YUI(configObj).use('mailinglist', function(Y) {
				Y.log('init mailinglist');
				mailinglist.initObservers();
				if (callbackFunc) {
					// invoke binded function
					callbackFunc;
				}
			});
			break;	
			case 'contact':
			YUI(configObj).use('contact', function(Y) {
				Y.log('init contact form/links');
				contact.initObservers();
				if (callbackFunc) {
					// invoke binded function
					callbackFunc;
				}
			});	
			break;
			
			case 'links':
			YUI(configObj).use('links_css', function(Y) {
				Y.log('init links');				
			});
			break;
			
			case 'ytgallery':
			YUI(configObj).use('ytgallery', function(Y) {
				Y.log('init YouTube gallery');
				ytgallery.ytGalleryInit(callbackFunc);				
			});
			break;
			
			case 'fbshare':
			YUI(configObj).use('fbshare', function(Y) {
				Y.log('init Facebook Share icons');
				FB.Share._onFirst();
			});
			break;
			
			case 'storeold':
			YUI(configObj).use('storeold', function(Y) {
				Y.log('init old store');
			});
			break;
			
			case 'jplayer':
			YUI(configObj).use('jplayer', 'node', 'transition', function(Y) {
				Y.log('jplayer loaded');
				if (!webkit.jsondata.mpsettings.playlist) {
					Y.log('error: no playlist found');
					return;
				}

				if (configVars && configVars.playerID) {
					var playerID = configVars.playerID;
				}
				else {
					// default to 1
					var playerID = 1;
				}
				
				var playlist = webkit.jsondata.mpsettings.playlist;
				var playlistorder = webkit.jsondata.mpsettings.playlistorder;				
				soundclips.playlistidx = 0;
				soundclips.trackID = webkit.jsondata.mpsettings.playlistorder[soundclips.playlistidx];
				
				var J = jQuery.noConflict();
				var jPlayerConfig = {
					playerID: playerID,
					trackID: soundclips.trackID,
					autostart:false
				}

				// init jPlayer
				webkit.initjPlayer(jPlayerConfig);
		
				// event listener to continue to next track when song has ended
				J('#jquery_jplayer_' + playerID).bind(J.jPlayer.event.ended, function(e) {
					if (soundclips.playAndStop) { return; }
					
					soundclips.playlistidx++;
					if (!webkit.jsondata.mpsettings.playlistorder[soundclips.playlistidx]) {
						// set back to beginning of playlist
						soundclips.playlistidx = 0;
					}
					soundclips.trackID = webkit.jsondata.mpsettings.playlistorder[soundclips.playlistidx];
					YUI().log('track ended, set track ID: ' + soundclips.trackID);
					jPlayerConfig.trackID = soundclips.trackID;
					jPlayerConfig.autostart = true;
					
					if (!Y.one('#jp_marquee_' + playerID).hasClass('displaynone')) {
						// fade track metadata
						Y.one('#jp_marquee_' + playerID).hide('fadeOut', {
							duration:0.5,
							on : {
								end : function() {
									webkit.jPlayerPlay(jPlayerConfig);
								}
							}
						});
					}
					else {
						webkit.jPlayerPlay(jPlayerConfig);						
					}
				});
				
				if (webkit.jsondata.medialoaderID && Y.one('#menublock #' + webkit.jsondata.medialoaderID)) {
					// init clip menu					
					soundclips.mediaLoaderMobileObservers(jPlayerConfig);
				}				
			});
			break;
			
			case 'tinymce':
			YUI(configObj).use('tinymce', function(Y) {
				Y.log('init TinyMCE');
				if (callbackFunc) {
					callbackFunc();
				}
			});
			break;
			
			case 'ckeditor':
			YUI(configObj).use('ckeditor', function(Y) {
				Y.log('init CKEditor');
				if (callbackFunc) {
					callbackFunc();
				}
			});
			break;
			
			case 'dbmanager':
			YUI(configObj).use('dbmanager', function(Y) {
				dbmanager.initObservers();	
			});
			break;
			
			case 'discography':
			YUI(configObj).use('discography', function(Y) {
				initLightbox();	
				Y.log('init discography');
			});
			break;
		}
	}
	
	this.initjPlayer = function(jPlayerConfig) {		
		var J = jQuery.noConflict();
		J("#jquery_jplayer_" + jPlayerConfig.playerID).jPlayer({
			ready: function () {
				webkit.jPlayerPlay(jPlayerConfig);
			},
			swfPath: "/nm_webkit/libs/jplayer/",
			supplied: "mp3, oga"
		});

		if (!webkit.Y.one('#jp_marquee_' + jPlayerConfig.playerID).hasClass('displaynone') && 
			typeof webkit.jsondata.mpsettings.playlist !== "undefined") {
			// event listener to show metadata on play
			J('#jquery_jplayer_' + jPlayerConfig.playerID).bind(J.jPlayer.event.play, function(e) {
				if (!soundclips.lastTrackID || soundclips.lastTrackID !== soundclips.trackID) {
					webkit.Y.one('#jp_marquee_' + jPlayerConfig.playerID).setStyle('opacity', '0');
					webkit.Y.one('#jp_marquee_' + jPlayerConfig.playerID).setContent('<span class="metadata trackname">' + webkit.jsondata.mpsettings.playlist[soundclips.trackID].name + '</span><span class="metadata trackartist">' + webkit.jsondata.mpsettings.playlist[soundclips.trackID].artist + '</span><span class="metadata trackalbum">' + webkit.jsondata.mpsettings.playlist[soundclips.trackID].album + '</span>');
					webkit.Y.one('#jp_marquee_' + jPlayerConfig.playerID).show('fadeIn', {
						duration:0.5
					});	
					soundclips.lastTrackID = soundclips.trackID;							
				}					
			});	
		}
		
		// show controls that should be visible
		webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-pause').setStyle('display', 'none');
		webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-pause').removeClass('displaynone');
		
		if (typeof webkit.jsondata.mpsettings.jplayersettings == "undefined") {
			return;
		}
		
		if (webkit.jsondata.mpsettings.jplayersettings.progressbar) {
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-progress').removeClass('displaynone');	
		}
		if (webkit.jsondata.mpsettings.jplayersettings.timedisplay) {
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-timedisplay').removeClass('displaynone');	
		}
		if (webkit.jsondata.mpsettings.jplayersettings.stop) {
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-stop').removeClass('displaynone');	
		}
		if (webkit.jsondata.mpsettings.jplayersettings.mute) {
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-mute').removeClass('displaynone');
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-unmute').setStyle('display', 'none');				
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-unmute').removeClass('displaynone');					
		}
		if (webkit.jsondata.mpsettings.jplayersettings.volume) {
			webkit.Y.one('#jp_interface_' + jPlayerConfig.playerID + ' .jp-volume-bar').removeClass('displaynone');	
		}
	}
	
	/*
	this.initClipMenu = function() {
		YUI().use('node-base', function(Y) {
			Y.all('#menublock #' + webkit.jsondata.medialoaderID + ' ul li a').each(function(node) {
				Y.on('click', function(e) {
					e.preventDefault();
					Y.log('click');
				}, node)
			});	
		})		
	}
	*/
	
	/*
	this.playjPlayerTrack = function(configVars) {
		// if called from nav menu, hide menu
		YUI().use('node', 'transition', function(Y) {
			Y.all('#menublock .active').each(function(node) {
				node.removeClass('active');
				node.one('ul').transition({
					opacity:0,
					duration:0.3,
					on : {
						end:function() {
							node.one('ul').setStyles({
								opacity:1,
								height:'0px',
								display:'none'
							})
						}
					}
				});
			});		
		});
		
		var J = jQuery.noConflict();
		
		if (configVars && configVars.playerID) {
			var playerID = configVars.playerID;
		}
		else {
			// default to 1
			var playerID = 1;
		}
		
		var jPlayerConfig = {
			J:J,
			playerID: configVars.playerID,
			trackID: configVars.trackID,
			autostart:true
		}
		
		webkit.jPlayerPlay(jPlayerConfig);
	}
	*/
	
	this.jPlayerPlay = function(jPlayerConfig) {
		if (!jPlayerConfig.trackID) {
			YUI().log('ERROR: no track ID provided');
			return;
		}						
		if (!jPlayerConfig.playerID) {
			// default to 1
			jPlayerConfig.playerID = 1;
		}
		var J = jQuery.noConflict();
			
		YUI().log('play: ' + webkit.jsondata.mpsettings.playlist[jPlayerConfig.trackID].filename + ' ' + webkit.jsondata.mpsettings.playlist[jPlayerConfig.trackID].oggfilename);
		J("#jquery_jplayer_" + jPlayerConfig.playerID).jPlayer('clearMedia');
		J("#jquery_jplayer_" + jPlayerConfig.playerID).jPlayer("setMedia", {
			mp3: '/nm_webkit/mediaplayer/hi/' + webkit.jsondata.mpsettings.playlist[jPlayerConfig.trackID].filename,
			oga: '/nm_webkit/mediaplayer/hi/' + webkit.jsondata.mpsettings.playlist[jPlayerConfig.trackID].oggfilename	
		});
		if (jPlayerConfig.autostart) {
			J("#jquery_jplayer_" + jPlayerConfig.playerID).jPlayer("play");
		}
	}
	
	this.YUIscrollTo = function(domid, callbackFunc, configObj) {
		YUI().use('anim', function(Y) {
			if (!configObj) { configObj = { } }
			
			if (!configObj.duration) {
				// set default
				configObj.duration = 0.75;
			}
			new Y.Anim({
				node: window.document,
				duration:configObj.duration,
				to: {
					scroll: function(node) {
						return [0, Y.one('#' + domid).getY()]
					}
				},
				on : {
					end: function() {
						if (typeof callbackFunc !== "undefined") {
							callbackFunc(configObj);
						}		
					}
				},	
				easing: Y.Easing.easeOut
			}).run();	
		})		
	}
	
	/*
	this.calcMenuDimensions = function(subMenu) {
		YUI().use('node', function(Y) {
			subMenu.setStyles({
				display: 'block',
				height:''
			});
			webkit.menuHeight = subMenu.getComputedStyle('height');							
			webkit.menuWidth = subMenu.getComputedStyle('width');
			subMenu.setStyle('display', 'none');		
		});
	}
	*/
	
	this.initNavMenus = function(configObj) {
		YUI({
			gallery:'gallery-2011.07.06-19-30'
		}).use('gallery-nmmenus', function(Y) {
			if (configObj.multipleMenus) {
				Y.log('init nmmenu widget - multiple');
				Y.each(configObj.multipleMenus, function(o) {
					configObj.menudivid = o;
					configObj.nmmenu = new Y.NMMenus(configObj);
				});
			}
			else {
				Y.log('init nmmenu widget');				
 				configObj.nmmenu = new Y.NMMenus(configObj);
			}
		});
	
		
		/*
		// set some defaults
		if (!configObj) {
			configObj = { }
		}
		
		if (!configObj.anim) {
			configObj.anim = "fade";
		}
		if (!configObj.inDuration) {
			configObj.inDuration = 0.35;
		}
		if (!configObj.outDuration) {
			configObj.outDuration = 0.25;
		}
		
		YUI().use('event-mouseenter', 'node', 'transition', function(Y) {
			// calculate menu heights for blind anim			
			var menuHeights = new Array();
			var menuWidths = new Array();
			Y.all('#menublock .hasSubMenu').each(function(thismenu, idx) {
				var menu = thismenu.get('parentNode').one('ul').setStyles({
					display: 'block',
					height:''
				});				
				var menuHeight = menu.getComputedStyle('height');
				var menuWidth = menu.getComputedStyle('width');				
				menu.setStyle('display', 'none');
				
				menuHeights[idx] = menuHeight;
				menuWidths[idx] = menuWidth;
			});	
			
			if (configObj.ajaxload) {
				// AJAX init for top level nav sections
				webkit.initAjaxLinks('menublock');	
			}
			
			// make sure that top level menu items are not erronously marked as active
			Y.all('#menublock .topLink').each(function(node) {
				if (!node.hasClass('hasSubMenu')) {				
					Y.on('mouseleave', function(e) {
						node.get('parentNode').removeClass('active');
					}, node);
				}
			});
		
			Y.all('#menublock .hasSubMenu').each(function(node, idx) {
				var topLi = node.get('parentNode');				
				var subMenu = topLi.one('ul');			
				
				if (configObj.ajaxload) {
					// add click observers					
					subMenu.all('li a').each(function(item) {
						if (!item.hasClass('noajax')) { 
							Y.on('click', function(e) {
								e.preventDefault();	
								configObj.page = 'page-' + item.get('pathname');
								configObj.topLi = topLi;
								configObj.subMenu = subMenu;												
								webkit.YUIpulsate(item.get('id'), null, webkit.ajaxLoadMenuItem, configObj);
							}, item)
						}
					});
				}								
																			
				Y.on('mouseenter', function(e) {
					//Y.log('mouse enter');												
					Y.all('#menublock .hasSubMenu').get('parentNode').removeClass('active');																																												
					
					// mark menu as active
					topLi.addClass('active');
					
					// update menu height in case menu contents have changed
					webkit.calcMenuDimensions(subMenu);
					if (webkit.menuHeight !== menuHeights[idx]) {
						menuHeights[idx] = webkit.menuHeight;
					}					
					
					switch (configObj.anim) {
						case 'fade':
						subMenu.setStyles({
							opacity:0,
							display:'block'
						});
						subMenu.transition({
							opacity:1,
							easing:'ease-out',
							duration:configObj.inDuration
						});	
						break;
						
						case 'blind':	
						subMenu.setStyles({
							height: '0px',
							display:'block',
							position:'absolute',
							top:node.getComputedStyle('height'),
							width:menuWidths[idx],
							opacity:1
						});
						subMenu.transition({
							height:menuHeights[idx],
							duration:configObj.inDuration,
							easing:'ease-out',
							on : {
								start:function() {
									subMenu.all('li').setStyles({
										visibility:'visible'										
									});
								},
								end:function() {									
									if (subMenu.hasClass('fluid')) {
										subMenu.setStyle('height', '');										
									}									
								}												
							}
						})
						break;
					}
				}, topLi);
				
				Y.on('mouseleave', function(e) {
					//Y.log('mouse leave');
					configObj.topLi = topLi;
					configObj.subMenu = subMenu;
					webkit.hideNavMenu(configObj);
				}, topLi);							
			});	
		})	
		*/	
	}	
	
	/*
	this.hideNavMenu = function(configObj) {			
		//configObj.topLi.removeClass('active');			
			
		switch (configObj.anim) {
			case 'fade':
			configObj.subMenu.transition({
				opacity:0,
				duration:configObj.outDuration,
				easing:'ease-out',
				on : {
					end:function() {
						configObj.topLi.removeClass('active');						
					}
				}									
			});	
			break;
			
			case 'blind':
			configObj.subMenu.transition({
				height:'0px',
				duration:configObj.outDuration,
				easing:'ease-out',							
				on : {
					start:function() {
						configObj.subMenu.all('li').setStyle('visibility', 'hidden');
					},
					end:function() {
						configObj.subMenu.all('li').setStyles({
							visibility:'visible'										
						});
						configObj.subMenu.setStyles({
							display: 'none',
							height:''
						});													
						configObj.topLi.removeClass('active');																																										
					}
				}
			})
			break;
		}
	}
	*/
	
	this.ajaxLoadMenuItem = function(configObj) {
		webkit.recordHistory('page-' + configObj.page);
	}
	
	this.ajaxLoadMenus = function(configObj) {
		if (!configObj.menudivid) {
			configObj.menudivid = "menublock";
		}			
		
		webkit.Y.all('#' + configObj.get('menudivid') + ' li a.topLink').each(function(node) {
			node = node.get('parentNode');

			webkit.Y.delegate('click', function(e) {
				if (this.get('href').match(/#$/) && this.hasClass('topLink')) {
					// cancel click
					e.preventDefault();
					return;
				}
				else if (webkit.Y.one('#' + this.get('id')).hasClass('noajax')) { 
					// abort, but do not cancel click
					return; 
				}
				e.preventDefault();
				if (this.hasClass('topLink')) {
					// top level link, do not init pulsate
					webkit.ajaxLoadMenuItem({
						page:this.get('pathname'),
						id:this.get('id')
					})
				}
				else {
					configObj.menuItemPulsate(this.get('id'), webkit.ajaxLoadMenuItem, {
						page:this.get('pathname'),
						id:this.get('id')
						});	
				}			
			}, node, 'a');		
		});
	}
	
	this.YUIpulsate = function(ID, configObj, callbackFunc, callbackArgs) {
		// mimics Script.aculo.us's Effect.Pulsate using YUI transition		
		
		if (!configObj) {
			configObj = { }
		}
		
		if (!configObj.pulses) {
			configObj.pulses = 2;
		}
		if (!configObj.duration) {
			configObj.duration = 0.3;
		}
		
		configObj.duration = configObj.duration / configObj.pulses;
		
		YUI().use('transition', 'node', function(Y) {
			Y.one('#' + ID).transition({
				opacity:0,
				duration:(configObj.duration / 2),
				on : {
					end: function() {
						Y.one('#' + ID).transition({
							opacity:1,
							duration:(configObj.duration / 2),
							on : {
								end:function() {									
									if (configObj.pulses > 1) {
										configObj.pulses--;
										webkit.YUIpulsate(ID, configObj, callbackFunc, callbackArgs)
									}
									else {
										if (callbackFunc) {
											Y.log('trigger callback');
											callbackFunc(callbackArgs);
										}	
									}								
								}
							}
						})
					}
				}
			})
		});
	}
	
	this.setupForLightbox = function() {
		YUI().use('node', function(Y) {
			Y.all('#pagecontent a img').get('parentNode').addClass('lightbox');
			Y.all('#pagecontent a img').get('parentNode').setAttribute('rel','lightbox');			
			webkit.modinit('lightbox');
		});
	}
	
	this.playsong = function (songID,playerID,callbackFunc) {
		// sends track load info to Flash mediaplayer
		
		if (!webkit.hasFlash) {
			// flash not installed (possibly iPad/iPhone/iPod Touch), exit
			return;
		}

		// make sure module has been inited
		webkit.modinit('soundclips');	

		if (typeof playsong_precallback !== "undefined") {
			playsong_precallback(playerID);
		}

		// set default playerID if not defined
		if (typeof playerID == "undefined") {
			playerID = 'mediaplayer';
		}
		
		// create/recreate JSON data object
		var mediaplayer = webkit.Y.JSON.parse(webkit.Y.one('#jsondata').get('value'));

		if (songID == 'inorder') {
			// playlist preserved in proper order
			var flashID = "global";
		}
		else if (songID == 'random') {
			// establish random playing order

			var flashID = "global";

			// create tmpPlaylist of playlist component of mediaplayer JSON object
			var tmpPlaylist = webkit.Y.JSON.parse(webkit.Y.JSON.stringify(mediaplayer.mpsettings.playlist));
			var tmpShuffle = [];
			$H(tmpPlaylist).each(function(pair,idx) {
				tmpShuffle[idx] = pair.key;
			});		
			tmpShuffle.sort(function() {
				return 0.5 - Math.random();
			});
			// create trackorder hash
			var trackorder = $H();
			var playlist = $H();
			tmpShuffle.each(function(o,idx) {
				trackorder.set(idx,o);
				playlist.set(o,mediaplayer.mpsettings.playlist[o]);
			});
			mediaplayer.mpsettings.trackorderJSON = trackorder.toJSON();
			mediaplayer.mpsettings.playlistJSON = playlist.toJSON();
		}
		else {
			// specific song
			
			var flashID = songID;
			
			mediaplayer.mpsettings.playlistJSON = "";
			if ($('replacecliplink_' + songID)) {
				var replacelink = $('replacecliplink_' + songID).innerHTML;
				var replaceclass = $('replacecliplink_' + songID).className.replace(/\s?replacecliplink\s?/,'');
			}
		}

		// stop all mediaplayers
		if ($(playerID) && $(playerID).className) {
			var clipClass = $(playerID).className;
			$$('.' + clipClass).each(function(o) {
				o.update('');				
			});	
		}

		if (mediaplayer.mpsettings.mpWidth) {
			var mpwidth = mediaplayer.mpsettings.mpWidth;
		}
		else {
			var mpwidth = $(playerID).getWidth();
		}
		if (mediaplayer.mpsettings.mpHeight) {
			var mpheight = mediaplayer.mpsettings.mpHeight;
		}
		else {
			var mpheight = $(playerID).getHeight();
		}

		// load into div tag	
		var flashObject = new SWFObject('/nm_webkit/mediaplayer/' + mediaplayer.mpsettings.mpMediaplayer, "mediaplayer_" + flashID, mpwidth, mpheight, "9", "");
		if (songID == "random" || songID == "inorder") {
			flashObject.addVariable("playlist", escape(mediaplayer.mpsettings.playlistJSON));
			flashObject.addVariable("trackorder", escape(mediaplayer.mpsettings.trackorderJSON));
		}
		else {		
			mediaplayer.mpsettings.mpFirstload = false;
			flashObject.addVariable("filename", mediaplayer.mpsettings.playlist[songID].filename);
			flashObject.addVariable("name", escape(mediaplayer.mpsettings.playlist[songID].name));
			flashObject.addVariable("artist", escape(mediaplayer.mpsettings.playlist[songID].artist));
			flashObject.addVariable("album", escape(mediaplayer.mpsettings.playlist[songID].album));	
			flashObject.addVariable("length", mediaplayer.mpsettings.playlist[songID].length);	
			//new Effect.ScrollTo(playerID, { duration:0.5});							
		}		
		flashObject.addParam("wmode", "transparent");
		flashObject.addVariable("firstload", mediaplayer.mpsettings.mpFirstload);
		flashObject.addVariable("width", mpwidth);
		if (mediaplayer.mpsettings.balloffset) {
			flashObject.addVariable("balloffset", mediaplayer.mpsettings.balloffset);
		}
		flashObject.write(playerID);
		
		if (typeof callbackFunc !== "undefined") {
			callbackFunc();
		}
	}
	
	this.emailformObservers = function() {
		if ($('contactname')) {
			$('contactname').focus();
		}

		if ($('contactclosebutton')) {
			$('contactclosebutton').observe('click', function(e) {
				Modalbox.hide();
			});
		}
		if ($('contactsendemail')) {
			$('contactsendemail').observe('click', function(e) {
				webkit.emailform();
			});
		}
		if ($('contactcontent')) {
			var origContent = $('contactcontent').getValue();
			$('contactcontent').observe('focus', function() {
				if ($('contactcontent').getValue() == origContent) {
					$('contactcontent').value = "";
				}
			});	
		}
	}
	
	this.emailform = function(formID,formpost) {
		// submit Modalbox email form

		if (formID) {
			var submitby = $(formID).submitby.value;
			var name = $(formID).name.value;
			var content = $(formID).content.value;
			var ref = $(formID).ref.value;
		}
		else {
			var submitby = $('contactsubmitby').getValue();
			var name = $('contactname').getValue();
			var content = $('contactcontent').getValue();
			if ($('ref')) {
				var ref = $('ref').getValue();				
			}
			else {
				var ref = "";
			}
		}

		if (!submitby || !name || !content) {
			if (!$('contactformfeedback')) {
				$('MB_content').insert({'bottom':'<div id="contactformfeedback"></div>'});
			}
			$('contactformfeedback').update('You are missing some fields, please correct this and try again');
			Modalbox.resizeToContent();
			return;
		}
		else if (!webkit.validEmail(submitby)) {
			if (!$('contactformfeedback')) {
				$('MB_content').insert({'bottom':'<div id="contactformfeedback"></div>'});
			}
			$('contactformfeedback').update('Invalid email address');
			Modalbox.resizeToContent();		
			return;
		}

		if (!formpost) {
			// set default
			var formpost = "/contact.php";
		}
		// look for shortname
		if ($('shortnameJSON')) {
			var shortnameJSON = webkit.Y.JSON.parse(webkit.Y.one('#shortnameJSON').get('innerHTML'));
			if (shortnameJSON.formpost) {
				// override formpost address
				var formpost = shortnameJSON.formpost;
			}
			if (shortnameJSON.name) {
				var shortname = shortnameJSON.name;
			}
		}

		var ajaxParameters = 'ajaxreload=1&formsubmit=true&submitby=' + submitby + '&name=' + name + '&content=' + content + '&ref=' + ref;
		if (typeof shortname !== "undefined") {
			ajaxParameters += '&shortname=' + shortname;
		}

		new Ajax.Updater('MB_content', formpost, {
			method: 'get',
			parameters: ajaxParameters,
			onComplete: function(transport) {
				Modalbox.resizeToContent();
				if ($('thanksclose')) {
					$('thanksclose').observe('click', function() {
						Modalbox.hide();
					});
				}
			}
		})
	}
	
	this.validEmail = function(addr) {
		if (!addr.match(/.+?@.+?\..+/)) {
			return false;
		}
		return true;
	}
	
	this.homeBanners = function(i, bannerClick) {
		if (!$('bannerconfig')) { 
			//YUI().log('ERROR: no banner JSON data found');
			return; 
		}
		webkit.stopBannerRotation();
		var banners = webkit.Y.JSON.parse(webkit.Y.one('#bannerconfig').get('value'));
		
		if ($('banneroverrides') && $('banneroverrides').innerHTML) {
			var banneroverrides = webkit.Y.JSON.parse(webkit.Y.one('#banneroverrides').get('value'));
		}	
		
		// hide all div blocks for HTML snippets (for YUI back button)
		$$('#homebanner_upper div').each(function(o) {
			if (o.id !== "homebanner_links" && !o.hasClassName('cnav')) {
				o.addClassName('displaynone');				
			}
		});
		
		if (!i) {
			// no rotate iteration set, start from beginning
			i = 0;
		}	

		var nexti = parseInt(i) + 1;
		if (nexti == banners.length) { nexti = 0; }
		
		if ($('homebanner_links') && !$('homebanner_links').innerHTML) {
			webkit.genHomebannerLinks();
			webkit.genBannerNavObservers();
		}
		
		if ($('homebanner_links')) {
			$$('#homebanner_links .bannerlinkwrapper .bannerlinks').each(function(o) {
				o.removeClassName('banneron');
			});
			$('bannerlink_' + i).addClassName('banneron');		
		}
		
		// set top and bottom layer images
		var thisImage = 'url(/styles/images/' + banners[i].pic + ')';
		var nextImage = 'url(/styles/images/' + banners[nexti].pic + ')';		

		$('homebanner_upper').setStyle({backgroundImage:thisImage});
		$('homebanner_lower').setStyle({backgroundImage:nextImage,display:'none'});
		
		if (banners[i].divblock && $(banners[i].divblock).hasClassName('displaynone')) {
			if (webkit.lastbanner == i) {
				// banner hasn't changed, don't redo appear of div block
				$(banners[i].divblock).removeClassName('displaynone');	
			}
			else {
				$(banners[i].divblock).setStyle({display:'none'});
				$(banners[i].divblock).removeClassName('displaynone');							
				new Effect.Appear(banners[i].divblock, {duration:0.6, afterFinish:function() {
					if (!webkit.lastbanner) { 
						// first banner shown, set to first in index to prevent redo appear of div block on first banner
						webkit.lastbanner = 0; 
					}					
				}});
			}
		}

		$('homebanner_upper').stopObserving('click');
		$('homebanner_upper').stopObserving('mouseover');
		$('homebanner_upper').stopObserving('mouseout');
		
		if (typeof banners[i].clickurl !== "undefined" && banners[i].clickurl !== "") {
			$('homebanner_upper').observe('click', function(e) {
				e.stop();		
				if (banners[i].clickurl.match(/^http:\/\//)) {
					// external redirect				
					window.location = banners[i].clickurl;
				}
				else {
					if (typeof bannerClick == "function") {
						bannerClick(banners[i].clickurl);
					}
					else {
						window.location = banners[i].clickurl;
					}
				}
			});
		}		
		$('homebanner_upper').observe('mouseover', function() {
			if (banners[i].clickurl) {
				webkit.cursorLink();
				$('homebanner_upper').addClassName('buttonover');
			}
			// cancel rotation
			clearTimeout(webkit.rotationtimer);	
			// cancel rotate pause tracker 
			clearInterval(webkit.rotatepausetimer);
		});
		$('homebanner_upper').observe('mouseout', function() {
			if (banners[i].clickurl) {
				webkit.cursorClear();
				$('homebanner_upper').removeClassName('buttonover');
			}
			if (!webkit.bannerspaused) {
				// resume banners
				webkit.homeBanners(i);				
			}
		});

		if (typeof banneroverrides !== "undefined" && banneroverrides.rotationtime) {			
			// use specified rotation time
			webkit.rotatetime = banneroverrides.rotationtime;
		}			
		else {
			// set default
			webkit.rotatetime = 5000;
		}
		
		if (!webkit.rotatepause) { webkit.rotatepause = webkit.rotatetime; }  // initial init
		
		
		if (webkit.bannerspaused == true) {
			// user clicked on a banner number in nav, don't init rotation
			return; 
		}
		
		webkit.rotationtimer = setTimeout(function() {					
			new Effect.Appear('homebanner_lower', { duration:1, afterFinish: function() {
				if (banners[i].divblock) {
					$(banners[i].divblock).addClassName('displaynone');					
				}
				// update link location
				i++;			
				if (i == banners.length) {
					i = 0;
				}
				webkit.homeBanners(i);
				// reset rotatepause tracker
				webkit.rotatepause = webkit.rotatetime;			
				webkit.lastbanner = i;
			}});
		}, webkit.rotatepause);
		
		// cancel existing rotatepause trackers so that there is only one running at any time
		clearInterval(webkit.rotatepausetimer);  
		
		webkit.rotatepausetimer = setInterval(function() {
			webkit.rotatepause -= 500;
			if (webkit.rotatepause < 0) { webkit.rotatepause = webkit.rotatetime; }
			//YUI().log('rotate pause ' + webkit.rotatepause);
		},500)
	}
	
	this.genHomebannerLinks = function() {
		var banners = webkit.Y.JSON.parse(webkit.Y.one('#bannerconfig').get('value'));	
		var bannerlinks = '<div class="bannerlinkwrapper" id="bannerlinkwrapper_pause"><a href = "" class="bannerlinks" id="bannerlink_pause" />pause</a></div><div class="bannerlinkwrapper" id="bannerlinkwrapper_play"><a href = "" class="bannerlinks" id="bannerlink_play" />play</a></div>';
		for (var i=0; i < banners.length; i++) {
			bannerlinks += '<div class="bannerlinkwrapper" id="bannerlinkwrapper_' + (i + 1) + '"><a href = "" class="bannerlinks" id="bannerlink_' + i + '" />' + (i + 1) + '</a></div>';			
		}
		var bannerlinks = '<div id="banneroncache" class="banneron displaynone"></div>' + bannerlinks;
		$('homebanner_links').update(bannerlinks);
	}
	
	this.genBannerNavObservers = function() {
		$$('#homebanner_links .bannerlinkwrapper .bannerlinks').each(function(o) {
			o.observe('mouseover', function() {
				if (!o.hasClassName('banneron')) {
					o.addClassName('bannerlinkover');
				}
			});
			o.observe('mouseout', function() {
				o.removeClassName('bannerlinkover');
			});			
			o.observe('click', function(e) {
				e.stop();
				$('bannerlink_pause').addClassName('pauseon');				
				webkit.bannerspaused = true;
				var gotobanner = o.id.replace(/^bannerlink_/,'');
				webkit.lastbanner = gotobanner;
				clearTimeout(webkit.rotationtimer);
				// cancel existing rotatepause trackers so that there is only one running at any time
				clearInterval(webkit.rotatepausetimer);
				webkit.homeBanners(gotobanner);
			});
		});
		
		$('bannerlink_pause').stopObserving('click');
		$('bannerlink_pause').observe('click', function(e) {
			e.stop();
			if (!$('bannerlink_pause').hasClassName('pauseon')) {
				// pause
				$('bannerlink_pause').addClassName('pauseon');				
				webkit.bannerspaused = true;
				clearTimeout(webkit.rotationtimer);
				// cancel existing rotatepause trackers so that there is only one running at any time
				clearInterval(webkit.rotatepausetimer);				
			}
			else {
				$('bannerlink_pause').removeClassName('pauseon');
				webkit.bannerspaused = false;
				webkit.homeBanners(webkit.currentHomeBanner());
			}	
		});
	}
	
	this.stopBannerRotation = function() {
		// hide banners
		$('homebanner_upper').setStyle({backgroundImage:''});
		$('homebanner_lower').setStyle({backgroundImage:''});		
	
		// remove banner observers
		$('homebanner_upper').stopObserving('mouseover');
		$('homebanner_upper').stopObserving('mouseout');		
		$('homebanner_upper').stopObserving('click');
		
		// hide banner links
		$$('#homebanner_upper .bannerhtml').each(function(o) {
			o.addClassName('displaynone');
		});
		
		// cancel rotation
		clearTimeout(webkit.rotationtimer);	
		// cancel rotate pause tracker 
		clearInterval(webkit.rotatepausetimer);
		
		// cancel nav observers
		$$('#homebanner_links .bannerlinkwrapper .bannerlinks').each(function(o) {
			o.stopObserving('mouseover');
			o.stopObserving('mouseout');
			o.stopObserving('click');			
		});
		
		if ($('bannerlink_pause')) {
			$('bannerlink_pause').stopObserving('click');
		}
	}
	
	this.currentHomeBanner = function() {
		var idx=0;
		var bannerfound = false;
		$$('#homebanner_links .bannerlinks').each(function(o) {
			if (o.hasClassName('banneron')) {
				bannerfound = true;
			}
			if (!bannerfound && o.id !== "bannerlink_pause" && o.id !== "bannerlink_play") {
				idx++;
			}
		});
		return idx;
	}
	
	this.ajaxPageload = function(page,queryString) {
		// loads target page in div tag rather than forcing a page reload that 
		// interrupts the global mediaplayer
		
		/*
		if (page == "_") {
			// no path, cancel function
			return;
		}
		else if (page == "/reloadhome") {
			// trigger to reload homepage
			if (typeof webkit.yuihome !== "undefined") {
				page = webkit.yuihome;
			}
			else {
				page = "/";				
			}
			var searchCache = "home";
		}
		else {
		
		*/
		
		if (!webkit.Y.one('#pagecontent')) {
			YUI().log('ERROR: pagecontent not found, aborting ajaxPageload func');
			return;
		}
		
		var searchCache = page.replace(/\//g,'_');
		page = page.replace(/_/g,'/');	
		if (!page.match(/^\//)) {
			page = '/' + page;
		}

		if (!page) {
			page = "index.php";
		}
		
		webkit.Y.log('fire precallback');
		webkit.customevent.fire('ajaxlinks:precallback', page);

		YUI().log('search cache for ' + searchCache);
		if (webkit.cacheget('ajaxnav', searchCache)) {
			YUI().log('outputting cache');
			webkit.cacheoutput('ajaxnav', searchCache, webkit.Y.one('#pagecontent'));
			if (webkit.Y.one('#ajax_calendar')) {
				nmcalendar.initCalendar();	
			}
			else {
			//	webkit.initAjaxLinks();
			}
			
			webkit.setPageTitles(page);
			
			webkit.customevent.fire('ajaxlinks:callback', page);		
			
			if (webkit.Y.one('#pagecontent') && !webkit.jsondata.disableajaxscroll) {
				webkit.YUIscrollTo('pagecontent');
				//new Effect.ScrollTo('pagecontent', { duration:0.5});
			}	
		}
		else {
			YUI().log('trigger AJAX load of ' + page);
			// make AJAX call
			
			webkit.Y.one('#pagecontent').addClass('contentloading');
			
			// add progress bar
			var pbHTML = '<div class="contentloadinganim"></div>';
			webkit.Y.one('#pagecontent').append(pbHTML);			
			// get X coordinate of progress bar
			var x = webkit.Y.one('.contentloadinganim').getX();
			// get Y coordinate of #pagecontent, plus arbitrary top offset of 20px
			var y = webkit.Y.one('#pagecontent').get('children').item(0).getY() + 20;
			// reposition
			webkit.Y.one('#pagecontent .contentloadinganim').remove();
			webkit.Y.one(document.body).append(pbHTML);
			webkit.Y.one('.contentloadinganim').setStyles({
				position:'absolute',
				left:x + 'px',
				top:y + 'px'
			})
			
			var ajaxParameters = 'ajaxreload=1';	
			if (typeof queryString !== "undefined") {
				ajaxParameters += '&' + queryString;
			}		
			
			var cfg = {
				method: 'POST',
				data:ajaxParameters,
				on : {
					complete:function(id, transport) {
						webkit.Y.one('#pagecontent').setContent(transport.responseText);
						
						webkit.Y.one('#pagecontent').removeClass('contentloading');

						// update cache
						webkit.cacheset('ajaxnav', searchCache, webkit.Y.one('#pagecontent'));

						if (webkit.Y.one('#ajax_calendar') && typeof nmcalendar == "object") {
							nmcalendar.initCalendar();
						}
						else {
						//	webkit.initAjaxLinks();	
						}

						webkit.setPageTitles(page);		

						webkit.customevent.fire('ajaxlinks:callback', page);
						
						// remove progress bar
						webkit.Y.one('.contentloadinganim').remove();					

						if (webkit.Y.one('#pagecontent') && typeof webkit.jsondata !== "undefined" && !webkit.jsondata.disableajaxscroll) {
						//	new Effect.ScrollTo('pagecontent', { duration:0.5});
							webkit.YUIscrollTo('pagecontent');						
						}
					}
				}
			}
			
			webkit.Y.io(page, cfg);
			
	
			/*
			new Ajax.Updater('pagecontent', page, {
				method: 'post',
				parameters: ajaxParameters,
				onComplete: function(transport) {
					$('pagecontent').removeClassName('contentloading');
					
					// update cache
					webkit.cacheset('ajaxnav', searchCache, $('pagecontent'));

					if ($('ajax_calendar') && typeof nmcalendar == "object") {
						nmcalendar.initCalendar();
					}
					else {
						webkit.initAjaxLinks();	
					}
					
					webkit.setPageTitles(origpage);		
					
					if (typeof ajaxpage_callback == "function") {
						YUI().log('invoking callback');
						ajaxpage_callback(origpage);
					}
					
					if (typeof Effect !== "undefined" && $('pagecontent') && !webkit.jsondata.disableajaxscroll) {
						new Effect.ScrollTo('pagecontent', { duration:0.5});
					}
				}
			});
			*/
		}
	}
	
	this.fileIcon = function(filetype) {
		// looks for links linking to filetype and adds class to these a tags
		$$('#pagecontent a').each(function(o) {
			var matchpattern = '\.' + filetype + '$';
			if (o.href.match(matchpattern)) {
				o.addClassName(filetype + 'icon');
			}
		});	 
	}
	
	this.setPageTitles = function(page) {
		// set page titles by first looking at top level menu items in menu JSON object, submenu,
		// and then custom JSON object set in controller
		
		/*
		if (page == "/yuistart") {
			page = "/" + webkit.startBodyClass;
		}
		*/
		
		// remove leading slash from page
		if (page.match(/^\/.+/)) {
			page = page.replace(/^\//,'');
		}
			
		if (webkit.Y.one('#jsondata') && webkit.Y.one('#jsondata').get('value')) {
			var menuData = webkit.jsondata;
			
			var menuMatch = "^" + page + "$";			
			//YUI().log('look for ' + menuMatch);
			var matchFound=false;
			for (var i in menuData.nm_menuItems) {
				if (matchFound) { break; }
				
				// remove leading slash from href
				if (menuData.nm_menuItems[i].href.match(/^\/.+/)) {
					menuData.nm_menuItems[i].href = menuData.nm_menuItems[i].href.replace(/^\//,'');
				}
				
				//YUI().log(menuData.nm_menuItems[i].href + ' ' + menuMatch);
				if (typeof menuData.nm_menuItems[i].href !== "undefined" && menuData.nm_menuItems[i].href && menuData.nm_menuItems[i].href.match(menuMatch)) {
					YUI().log('set page title to ' + i);							
					webkit.setBodyClass(i);	
					// 8226 = bullet character, do not leave this in ASCII or it will not be converted to proper char							
					document.title = menuData.nm_siteTitle.replace(/&#8226;/g, String.fromCharCode(8226)) + ': ' + menuData.nm_menuItems[i].title;		
					matchFound=true;
					break;
				}
				else if (menuData.nm_menuItems[i].submenu) {
					// search submenus
					//YUI().log('search submenu ' + i);
					var thisSubmenu = menuData.nm_menuItems[i].submenu;
					for (var s in thisSubmenu) {
												
						// remove leading slash from href
						if (typeof thisSubmenu[s].href !== "undefined" && thisSubmenu[s].href.match(/^\/.+/)) {
							thisSubmenu[s].href = thisSubmenu[s].href.replace(/^\//,'');
						}
						
						//YUI().log(thisSubmenu[s].href + ' ' + menuMatch);						
						if (thisSubmenu[s].href && thisSubmenu[s].href.match(menuMatch)) {
							YUI().log('set page title to ' + i);	
							webkit.setBodyClass(i);																		
							// 8226 = bullet character, do not leave this in ASCII or it will not be converted to proper char								
							document.title = menuData.nm_siteTitle.replace(/&#8226;/g, String.fromCharCode(8226)) + ': ' + menuData.nm_menuItems[i].title;		
							matchFound=true;
							break;
						}
					}
				}
			}
			
			if (!matchFound && webkit.Y.one('#nm_pageTitle')) {
				var pagedata = webkit.Y.JSON.parse(webkit.Y.one('#nm_pageTitle').getContent());
				webkit.setBodyClass(pagedata.thispage);
				document.title = menuData.nm_siteTitle + ': ' + menuData.nm_menuItems[pagedata.thispage].title;
			}
		}

	}
	
	this.setBodyClass = function(page) {
		$(document.body).classNames().each(function(o) {
			if (o.match(/^nm_currentPage_/)) {			
				$(document.body).removeClassName(o);
			}
		});
		$(document.body).addClassName('nm_currentPage_' + page);
	}
	
	this.recordHistory = function(token, callbackFunc) {
		if (token.match(/^page-/)) {
			// prohibit underscores in URL, convert to dashes
			page = token.replace(/_/g,'-');
			// replace slashes with underscores for token so that hash is readable
			page = page.replace(/\//g,'_');

			webkit.YUIhistory.add({
				page:page
			});	
		}
		else if (token.match(/^tab-/)) {
			webkit.YUIhistory.add({
				tab:token.replace(/^tab-/,'')
			});
		}
		else {
			webkit.YUIhistory.add({
				p:token
			});
		}
		
		if (callbackFunc) {
			callbackFunc;
		}
	}
	
	this.recordHistoryold = function(page, callbackFunc) {	
		YUI().use('history-deprecated', function(Y) {
			if (page.match(/^page-\//)) {
				// remove leading slash
				page = page.replace(/^page-\//,'page-');
			}
			page = page.replace(/\//g,'_');

			if (page == "page-") { 
				page = "page-home" ;
			}

			Y.History.navigate("p", page);

			if (callbackFunc) {
				callbackFunc;
			}	
		})	
	}
	
	this.loadContent = function(page, tokentype) {
		if (typeof webkit.localjsloaded == "undefined") {
			// local JS hasn't loaded yet, wait until it has
			webkit.Y.Global.on('localjs:init', function() {
				YUI().log('local JS loaded, trigger loadcontent for history token')
				webkit.loadContent(page, tokentype)
			});
			return;
		}
	
		webkit.customevent.fire('loadcontent:callback', page);		
		if (page.match(/^page-/) || typeof webkit.jsondata == "undefined") {
			if (page.match(/.+?\?.*/)) {
				// URL contains query string, capture query string
				var queryString = window.location.search.replace(/^\?/,'');
			}
			else {
				var queryString = '';
			}
			// remove page prefix
			page = page.replace(/^page-/,'');
			// convert underscores bach to slashes for AJAX loading
			page = page.replace(/_/g,'\/');
			webkit.ajaxPageload(page, queryString);
		}
		else if (page.match(/^photocollection-/)) {
			collection = page.replace(/^photocollection-/,'');

			if (!$('gallerywrapper')) {
				// switch to gallery page

				if (!webkit.jsondata.gallerybase) {
					// set default					
					webkit.jsondata.gallerybase = '/gallery';
				}
				webkit.ajaxPageload(webkit.jsondata.gallerybase);
			}

			YUI().log('queue load collection ' + collection);
			webkit.queueLoad(collection, 'photogallery');				
		}
		else if (typeof tokentype !== "undefined" && tokentype == "tab") {
			// callback queue for tabs

			webkit.customevent.fire('tab:switch', page);
		}
		else if (page.match(/^page-/) && pagecallbacks.length > 0) {
			// callback queue for pages
			page = page.replace(/^page-/,'');			
			pagecallbacks.each(function(callbackFunc) {
				callbackFunc(page);
			});
		}
	}
	
	this.loadContentold = function(page) {
		if (page.match(/^page-/) && (typeof webkit.jsondata == "undefined" || !webkit.jsondata.yuihomefunc)) {
			// don't bother with other checks if webkit.jsondata is not defined (legacy sites),
			// webkit.jsondata.yuihomefunc boolean indicates whether to use the customYUINav function
			// for yuistart requests
			if (page.match(/.+?\?.*/)) {
				// URL contains query string, capture query string
				var queryString = Object.toQueryString(o.href.toQueryParams());
			}
			else {
				var queryString = '';
			}
			page = page.replace(/^page-/,'');
			if (page == "home" || page == "yuistart") {
				page = "/reloadhome";
			}
			
			webkit.ajaxPageload(page, queryString);
		}
		else if (typeof customYUINav == "function") {
			// not a standard page load request, use overriding customYUINav function, if it exists

			customYUINav(page);			
		}
		else if (page.match(/^photocollection-/)) {
			collection = page.replace(/^photocollection-/,'');
			
			if (!$('gallerywrapper')) {
				// switch to gallery page
				
				if (!webkit.jsondata.gallerybase) {
					// set default					
					webkit.jsondata.gallerybase = '/gallery';
				}
				webkit.ajaxPageload(webkit.jsondata.gallerybase);
			}
			
			YUI().log('queue load collection ' + collection);
			webkit.queueLoad(collection, 'photogallery');				
		}
		else if (page.match(/^tab-/)) {
			// callback queue for tabs
			page = page.replace(/^tab-/,'');
			if (tabcallbacks.length == 0) {
				// no callbacks defined
				wkadmin.selectUploadTab(page, '', page + 'contents');
			}
			else {
				// custom callbacks
				tabcallbacks.each(function(callbackFunc) {
					callbackFunc(page);
				});	
			}		
		}
		else if (page.match(/^page-/) && pagecallbacks.length > 0) {
			// callback queue for pages
			page = page.replace(/^page-/,'');			
			pagecallbacks.each(function(callbackFunc) {
				callbackFunc(page);
			});
		}	
	}
	
	this.ajaxCIWPSearch = function() {
		YUI().use('node-base', function(Y) {
			Y.on('click', function(e) {
				e.preventDefault();
				var searchquery = Y.one('#s').get('value');
				webkit.loadContent('page-/search/' + searchquery, 'page');
			}, '#searchsubmit');	
		});	
	}
	
	this.queueLoadTimer = 0;
	this.queueLoad = function(ID, module) {
		// loads content once existence of class has been confirmed to prevent race conditions
		// with content dynamically loaded via YUI
		clearTimeout(webkit.queueLoadTimeout);
		webkit.queueLoadTimeout = setTimeout(function() {			
			switch (module) {
				case 'photogallery':
				if (typeof webkitgallery !== 'undefined') {
					// loaded, exit
					clearTimeout(webkit.queueLoadTimeout);
					YUI().log('show collection ' + ID);
					webkitgallery.showCollection(ID);
				}
				else {
					YUI().log('JS class not found');
					webkit.queueLoadTimer += 500;
					webkit.queueLoad(ID, module);
				}
				break;
			}
		}, webkit.queueLoadTimer);
	}
	
	this.initYUIHistory = function() {
		YUI().use('history', function(Y) {
			webkit.YUIhistory = new Y.HistoryHash();
			if (webkit.YUIhistory.get('page')) {
				// start page
				var page = webkit.YUIhistory.get('page');
				page = page.replace(/_/g,'\/');
				webkit.loadContent(page, 'page');
			}
			else if (webkit.YUIhistory.get('tab')) {
				var page = webkit.YUIhistory.get('tab');
				page = page.replace(/_/g,'\/');
				webkit.loadContent(page, 'tab');
			}
			else if (webkit.YUIhistory.get('photocollection')) {
				var page = webkit.YUIhistory.get('photocollection');
				page = page.replace(/_/g,'\/');
				webkit.loadContent(page, 'photocollection');
			}
			else if (webkit.YUIhistory.get('p')) {
				var page = webkit.YUIhistory.get('p');
				page = page.replace(/_/g,'\/');
				webkit.loadContent(page, 'p');
			}
			
			Y.on('history:change', function(e) {
				var changed = e.changed,
				removed = e.removed;			

				if (changed.page) {
					webkit.loadContent(changed.page.newVal, 'page');									
				}
				else if (changed.tab) {
					webkit.loadContent(changed.tab.newVal, 'tab');				
				}
				else if (changed.photocollection) {
					webkit.loadContent(changed.photocollection.newVal, 'photocollection');
				}
				else if (changed.p) {
					webkit.loadContent(changed.p.newVal, 'p');
				}
			})
		})
	}
	
	this.initYUIHistoryold = function() {	
		YUI().use('history-deprecated', function(Y) {			
			Y.log('init YUI history');

			// Register YUI history
			Y.History.initialize('#yui-history-field', '#yui-history-iframe');

			// determine and register start page
			var bookmarkedSection = Y.History.getBookmarkedState('p');
			var querySection = Y.History.getQueryStringParameter('p');		
			var initSection = bookmarkedSection || querySection || 'page-yuistart';
			Y.History.register("p", initSection).subscribe("history:moduleStateChange", webkit.loadContent);
			
			// find starting CSS class for body so that we can replace webkit.cacheToken "yuistart" with correct token
			// that matches the page initially loaded, change home -> '' for setPageTitles function
			$(document.body).classNames().each(function(o) {
				if (o.match(/^nm_currentPage_/)) {
					webkit.startBodyClass = o.replace(/^nm_currentPage_/,'');
					if (webkit.startBodyClass == "home") {
						webkit.startBodyClass = "";
					}
				}
			});

			// switch to start page										
			Y.History.subscribe("history:ready", function () {
				var startPage = Y.History.getCurrentState("p");
				Y.History.navigate("p", startPage);
				if (initSection !== "page-yuistart") {
					// don't trigger JS load content if no YUI token found
					webkit.loadContent(startPage);										
				}
			});
		});

	}
	
	this.initAjaxLinks = function(divtag, callbackFunc) {	
		// attaches event observers to all links in given divtag, passes to ajax()
		//YUI().log('invoke initAjaxLinks for ' + divtag);			
		webkit.metaKey();

		if (!divtag) {
			// default to #pagecontent
			divtag = "pagecontent";
		}
		var thisDomain = '^(http|https):\/\/' + window.location.hostname.replace('.','\.');
		
		webkit.Y.delegate('click', function(e) {
			if (this.get('href').match(/#$/)) {
				// cancel click
				e.preventDefault();
			}			
			else if (!this.get('href').match(/^(mailto|javascript):/) && !this.get('href').match(/^#/) && this.get('href').match(thisDomain) && !this.get('pathname').match(/\.(pdf|mp3|jpg|png|gif|m4a|zip)$/i) && !this.get('pathname').match(/^(\/wordpress\/wp-content\/uploads\/|\/nm_webkit\/)/) && !this.hasClass('noajax') && !this.hasClass('email') && !this.get('id').match(/^menu_/)) {
				//o.detach('click');
				e.preventDefault();	
				if (webkit.metaKeyPressed) { return; }
				if (this.hasClass('disableclick')) { return; }
				var page = this.get('pathname');
				// don't trigger for nav bar, nav bar may include custom event handlers
				webkit.recordHistory('page-' + page);																		

				// trigger callback
				if (callbackFunc) {
					callbackFunc;
				}		
			}
		}, '#' + divtag, 'a');
		
		/*
		webkit.Y.all('#' + divtag + ' a').each(function(o) {			
			if (o.get('href').match(/#$/)) {
				webkit.Y.on('click', function(e) {
					// cancel click
					e.preventDefault();
				}, o)
			}			
			else if (!o.get('href').match(/^(mailto|javascript):/) && !o.get('href').match(/^#/) && o.get('href').match(thisDomain) && !o.get('pathname').match(/\.(pdf|mp3|jpg|png|gif|m4a|zip)$/i) && !o.get('pathname').match(/^(\/wordpress\/wp-content\/uploads\/|\/nm_webkit\/)/) && !o.hasClass('noajax') && !o.hasClass('email') && !o.get('id').match(/^menu_/)) {
				o.detach('click');
				webkit.Y.on('click', function(e) {
					e.preventDefault();	
					if (webkit.metaKeyPressed) { return; }
					if (o.hasClass('disableclick')) { return; }
					var page = o.get('pathname');
					// don't trigger for nav bar, nav bar may include custom event handlers
					webkit.recordHistory('page-' + page);																		

					// trigger callback
					if (callbackFunc) {
						callbackFunc;
					}
				}, o);			
			}	
		});
		*/	
	}
	
	this.metaKeyPressed = false;
	this.metaKey = function() {
		document.observe('keydown', function(e) {
			var key = e.which || e.keyCode;
			if ((e.metaKey && navigator.platform.match(/^Mac/)) || (e.ctrlKey && navigator.platform.match(/^(Win|Linux)/))) {
				webkit.metaKeyPressed = true;
			}
			else {
				webkit.metaKeyPressed = false;
			}
		});
		
		document.observe('keyup', function(e) {
			webkit.metaKeyPressed = false;
		});
	}
	
	this.loadJSCSSfile = function(filename, filetype){
		if (filetype=="js"){ //if filename is a external JavaScript file
			var fileref=document.createElement('script')
			fileref.setAttribute("type","text/javascript")
			fileref.setAttribute("src", filename)
		}
		else if (filetype=="css"){ //if filename is an external CSS file
			var fileref=document.createElement("link")
			fileref.setAttribute("rel", "stylesheet")
			fileref.setAttribute("type", "text/css")
			fileref.setAttribute("href", filename)
		}
		if (typeof fileref!="undefined") {
			$$('head')[0].insert({'top':fileref});	
		}
	}
	
	this.show = function(domID, config) {
		if (webkit.Y.one(domID).getStyle('opacity') == 1 && !webkit.Y.one(domID).hasClass('displaynone')) {
			// item is already showing, exit
			return;
		}
		
		if (typeof config == "undefined") {
			// set defaults
			config = { };
			config.duration = 0.2;
		}
		
		webkit.Y.one(domID).setStyle('opacity', '0').removeClass('displaynone').show('fadeIn', {
			duration:config.duration
		});
	}
	
	this.hide = function(domID, config) {
		if (webkit.Y.one(domID).getStyle('opacity') == 0) {
			// item is already hidden, exit
			return;
		}
		
		if (typeof config == "undefined") {
			// set defaults
			config = { }; 
			config.duration = 0.3;
		}
	
		webkit.Y.one(domID).setStyle('opacity', '1').show('fadeOut', {
			duration:config.duration,
			on : {
				end:function() {
					webkit.Y.one(domID).setStyle('display', 'none');
				}
			}
		});
	}
	
	this.addTS = function(pathname) {
		// adds leading slash so that element.pathname in IE matches element.pathname in W3C browsers
		if (!pathname.match(/^\//)) {
			YUI().log('add trailing slash');
			return "/" + pathname;
		}
		else {
			return pathname;
		}
	}
	
	this.removeTS = function(pathname) {
		if (pathname.match(/\/$/)) {
			YUI().log('remove trailing slash');
			return pathname.replace(/(.+?)\/$/, '$1');
		}
		else {
			return pathname;
		}
	}
	
	this.buttonMouseEffect = function(button, state) {
		YUI().use('node-base', function(Y) {
			if (!Y.one('#' + button)) { return; }
			if (state == "over") {
				Y.one('#' + button).addClass('buttonover');				
			}
			else {
				Y.one('#' + button).removeClass('buttonover');				
			}
		});
		/*
		if (!$(button)) { return; }
		if (state == "over") {
			webkit.cursorLink();
			$(button).addClassName('buttonover');			
		}
		else {
			webkit.cursorClear();
			$(button).removeClassName('buttonover');
		}
		*/
	}
	
	this.setupButton = function(ID, clickFunction, funcArgs) {
		YUI().use('event-mouseenter', 'event-delegate', function(Y) {
			if (!Y.one('#' + ID)) { return; }
			Y.one('#' + ID).purge(true, 'click');
			
		
			if (typeof clickFunction !== "undefined") {
				if (typeof funcArgs !== "undefined" && funcArgs.noDelegate) {
					Y.one('#' + ID).purge(true);
					
					Y.on('click', function(e) {
						e.preventDefault();
						if (Y.one('#' + ID).hasClass('disabled')) { return; }
						webkit.buttonMouseEffect(ID, 'out');			
						clickFunction(funcArgs);
					}, '#' + ID);
				}
				else {
					Y.delegate('click', function(e) {
						e.preventDefault();
						if (Y.one('#' + ID).hasClass('disabled')) { return; }
						webkit.buttonMouseEffect(ID, 'out');			
						clickFunction(funcArgs);
					}, document.body, '#' + ID);
				}										
			}
			
			if (typeof funcArgs !== "undefined" && funcArgs.noDelegate) {
				Y.on('mouseenter', function() {
					if (Y.one('#link-' + ID) && (Y.one('#link-' + ID).hasClass('active') || Y.one('#link-' + ID).hasClass('disabled'))) { return; }
					webkit.buttonMouseEffect(ID, 'over');
				}, '#' + ID);
			}
			else {
				Y.delegate('mouseenter', function() {
					if (Y.one('#link-' + ID) && (Y.one('#link-' + ID).hasClass('active') || Y.one('#link-' + ID).hasClass('disabled'))) { return; }
					webkit.buttonMouseEffect(ID, 'over');
				}, document.body, '#' + ID);	
			}			
		
			if (typeof funcArgs !== "undefined" && funcArgs.noDelegate) {
				Y.on('mouseleave', function() {
					webkit.buttonMouseEffect(ID, 'out');
				}, '#' + ID);
			}
			else {
				Y.delegate('mouseleave', function() {
					webkit.buttonMouseEffect(ID, 'out');
				}, document.body, '#' + ID);				
			}
		});		
	}
	
	this.clickButton = function(ID) {
		if (!$(ID)) { return; }
		webkit.buttonMouseEffect(ID, 'out');			
		webkit.recordHistory('tab-' + ID); 				
	}
	
	this.tabMouseEffect = function(tab, state) {
		if (webkit.Y.one('#' + tab).hasClass('activeTab')) { return; }
		if (state == "over") {
			webkit.cursorLink();
			webkit.Y.one('#' + tab).addClass('tabover');			
		}
		else {
			webkit.cursorClear();
			webkit.Y.one('#' + tab).removeClass('tabover');
		}
	}
	
	this.makeTabActive = function(tab, olddiv, newdiv, taboptions) {
		YUI().use('node', 'bokugresizer', function(Y) {
			// make all other tabs inactive				
			
			if (Y.one('#MB_window')) {
				var wrapper = '#MB_content';
				var animDuration = 0.15;
			}
			else {
				var wrapper = '#pagecontent';
				var animDuration = 0.5;
			}

			if (typeof taboptions !== "undefined" && taboptions.tabwrapper) {
				var tabwrapper = taboptions.tabwrapper;
			}
			else {
				var tabwrapper = '.tabWrapper';
			}

			Y.all(wrapper + ' ' + tabwrapper).removeClass('activeTab');
			Y.one('#' + tab).addClass('activeTab');	
			
			Y.all(wrapper + ' ' + tabwrapper + ' div').removeClass('activeTabLeft');
			Y.all(wrapper + ' ' + tabwrapper + ' div').removeClass('activeTabCenter');
			Y.all(wrapper + ' ' + tabwrapper + ' div').removeClass('activeTabRight');						

			// make tab active			
			Y.all(wrapper + ' #' + tab + ' div').each(function(o) {
				if (o.hasClass('tabLeft')) {
					o.addClass('activeTabLeft');
				}
				else if (o.hasClass('tabCenter')) {
					o.addClass('activeTabCenter');
				}
				else if (o.hasClass('tabRight')) {
					o.addClass('activeTabRight');
				}
			});

			if (!olddiv) {
				// olddiv not provided, determine currently selected tab						
				Y.all(wrapper + ' .tabContents').each(function(o) {
					if (!o.hasClass('displaynone')) {
						olddiv = o.get('id');
					}
				})
			}

			if (Y.one('#MB_content')) {
				// release height of Modalbox
				Y.one('#MB_content').setStyle('height', '');			
			}

			if (typeof taboptions !== "undefined" && taboptions.animation) {
				// show animation to grow/shrink newdiv		
				var bokugresizer = new Y.Bokugresizer();
				bokugresizer.loadAndResize({
					olddiv:olddiv,
					newdiv:newdiv,
					animDuration:animDuration
				});	
			}
			else if (Y.one('#MB_window')) {
				// use Modalbox.resizeToContent to resize Modalbox

				if (olddiv !== newdiv) {
					Y.one('#' + olddiv).hide('fadeOut', {
						duration:animDuration,
						on : {											
							end:function() {
								Y.one('#' + olddiv).addClass('displaynone');
								Y.one('#' + newdiv).setStyles({opacity:0,display:'block'});
								Y.one('#' + newdiv).removeClass('displaynone');

								Y.one('#' + newdiv).show('fadeIn', {
									duration:animDuration,
									on : {																
										end:function() {
											webkit.showTabContents(taboptions);
										}
									}
								})
							}
						}
					})					
				}
				else {
					webkit.showTabContents(taboptions);
				}
			}
			else {
				// switch tab without any animation
				Y.one('#' + olddiv).addClass('displaynone');
				Y.one('#' + olddiv).setStyle('display', '');
				Y.one('#' + newdiv).removeClass('displaynone');			
				Y.one('#' + newdiv).setStyle('display', '');				
			}
		});
		
	}
	
	this.showTabContents = function(taboptions) {
		if (taboptions.editFileAttrs) {
			// display edit file attributes screen, disable insert button for current photo
			// that invoked dialog
			YUI().log('edit attrs for ' + taboptions.fileID + ' ' + taboptions.uploadID);
			wkadmin.editFileAttrs(taboptions.fileID, taboptions.uploadID, false);						
		}				
		else {
			YUI().log('resize to content');
			Modalbox.options.transitions = true;
			if (typeof taboptions.resizeCSSID !== "undefined") {
				// resize width as well as height
				Modalbox.resizeToContent({resizeCSSID:taboptions.resizeCSSID});				
			}
			else {
				Modalbox.resizeToContent();						
			}
			Modalbox.options.transitions = false;
		}
	}
	
	this.setupTab = function(ID, taboptions) {
		YUI().use('event-mouseenter', function(Y) {
			Y.on('mouseenter', function() {
				webkit.tabMouseEffect(ID, 'over');
			}, '#' + ID);
			
			Y.on('mouseleave', function() {
				webkit.tabMouseEffect(ID, 'out');
			}, '#' + ID);
			
			Y.on('click', function(e) {
				e.preventDefault();
				webkit.clickTab(ID, taboptions);
			}, '#' + ID);
		});
		
		/*
		$(ID).observe('mouseover', function() {
			webkit.tabMouseEffect(ID, 'over');
		});
		$(ID).observe('mouseout', function() {
			webkit.tabMouseEffect(ID, 'out');
		});		
		// capture clicks on both a tag and tab wrapper		
		var thistab = $(ID).select('.tabCenter a');
		thistab[0].observe('click', function(e) {
			e.stop();
			webkit.clickTab(ID);			
		});
		$(ID).observe('click', function(e) {
			e.stop();
			webkit.clickTab(ID);
		});
		*/
	}
	
	this.clickTab = function(ID, taboptions) {
		if (typeof taboptions == "undefined") {
			taboptions = {
				nohistory:false
			}
		}

		webkit.tabMouseEffect(ID, 'out');
		if (webkit.Y.one('#' + ID).hasClass('activeTab')) { return; }
		if (!webkit.Y.one('#MB_window') && !taboptions.nohistory) {
			// don't record history inside of Modalbox
			webkit.recordHistory('tab-' + ID); 							
		}
		else {
			webkit.loadContent(ID, 'tab');
		}		
	}
	
	this.initContactNavButton = function(ID, alturl, callback) {	
		if (!ID) { 
			// set default
			ID = 'nm_id_contact'; 
		}	
		if (webkit.Y.one('#' + ID) && webkit.Y.one('#' + ID).get('href')) {
			// submenu item
			webkit.Y.on('click', function(e) {
				e.halt();
				contact.invokeModalbox('', alturl, callback);
				// hide legacy submenus
				webkit.hideAllSubmenus();
			}, '#' + ID);		
		}
		else if (webkit.Y.one('#' + ID + ' a')) {
			// top level menu nav
			webkit.Y.on('click', function(e) {
				e.halt();
				contact.invokeModalbox('', alturl, callback);
				// hide legacy submenus
				webkit.hideAllSubmenus();				
			}, '#' + ID + ' a');			
		}		
	}		
	
	this.contactNavButton = function(ID, alturl, callback) {
		// load contact form assets
		webkit.modinit('contact', null, webkit.Y.bind(this.initContactNavButton(ID, alturl, callback)));
	}
	
	this.MBscrollbars = function() {
		if ((parseInt($('MB_window').getHeight()) + 10) > document.viewport.getHeight()) {
			var newheight = parseInt(document.viewport.getHeight()) - 110;
			$('MB_content').setStyle({height:newheight + 'px'});
			Modalbox.resizeToContent();
			YUI().log('window too tall, viewport is ' + document.viewport.getHeight() + ', setting to ' + newheight + 'px');
		}
	}
	
	this.initMoreLinks = function() {
		// Facebook/Twitter style "show more posts" links
		YUI().use('node', 'event-delegate', function(Y) {
			Y.delegate('click', function(e) {
				e.preventDefault();
				var foldnum = this.get('id').replace(/^foldlink_/,'');
				Y.one('#fold_' + foldnum).removeClass('displaynone');
				Y.one('#morewrapper_' + foldnum).addClass('displaynone');
				webkit.YUIscrollTo('fold_' + foldnum, null, {
					duration:0.5
				})
			}, document.body, '.morelink');
		});
	}
	
	this.initNewsCrawl = function(divblock) {
		webkit.newsCrawlPaused = false;
		if (typeof webkit.jsondata !== "undefined" && webkit.jsondata.newscrawlrotatetime) {
			var rotatetime = webkit.jsondata.newscrawlrotatetime;
		}
		else {
			var rotatetime = 5000;
		}
		var crawler = setInterval(function() {
			if (webkit.newsCrawlPaused) { return; }
			$$('#' + divblock + ' .newscrawl').each(function(o) {								
				if (!o.hasClassName('displaynone')) {				
					var nextID = parseInt(o.id.replace(/^newscrawl_/,'')) + 1;
					if (!$('newscrawl_' + nextID)) {
						nextID = 1;
					}
					new Effect.Fade(o.id, { duration:0.75, afterFinish:function() {
						$(o.id).addClassName('displaynone');
						$('newscrawl_' + nextID).setStyle({display:'none'});
						$('newscrawl_' + nextID).removeClassName('displaynone');
						new Effect.Appear('newscrawl_' + nextID, { duration:0.75})
					}});
				}
			});
		}, rotatetime);
		
		$(divblock).observe('mouseover', function() {
			webkit.newsCrawlPaused = true;
		});
		$(divblock).observe('mouseout', function() {
			webkit.newsCrawlPaused = false;
		});			
	}
	
	this.supportsVideo = function() {
	  return !!document.createElement('video').canPlayType;
	}
	
	this.supportsAudio = function() {
	  return !!document.createElement('audio').canPlayType;
	}
	
	this.supportsH264 = function() {
	  if (!webkit.supportsVideo()) { return false; }
	  var v = document.createElement("video");
	  return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
	}
	
	this.supportsMP3 = function() {
	  if (!webkit.supportsAudio()) { return false; }
	  var a = document.createElement("audio");
	  return a.canPlayType('audio/mpeg');
	}
	
	this.supportsOgg = function() {
	  if (!webkit.supportsVideo()) { return false; }
	  var v = document.createElement("video");
	  return v.canPlayType('video/ogg; codecs="theora, vorbis');
	}
	
	this.embedVideo = function(ID, supportOgg) {
		// test for h264/OGG support, fallback to flowplayer (Flash)
		if (!supportOgg && webkit.supportsOgg() && !webkit.supportsH264()) {
			// Firefox browsers, but no Ogg video argument sent (assuming because there is no Ogg video available),
			// disable video tag
			$(ID + '_videotag').remove();
			flowplayer(ID, "/nm_webkit/libs/flowplayer.swf", { accelerated:true });
		}
		else if (!webkit.supportsH264()) {
			// no support for h.264, fall back to Flash
			flowplayer(ID, "/nm_webkit/libs/flowplayer.swf", { accelerated:true });
		}
		else {
			// Webkit browser, support for HTML5 video tag via h.264 or Ogg, remove flowplayer hook
			$(ID).remove();
		}
	}
	
	this.hideAllSubmenus = function() {
		$$('#menublock .wrapper').each(function(o) {
			o.fade({
				duration:0.2
			});
			o.parentNode.removeClassName('active');
		});
	}

	return true;
}

// instantiate webkit
var webkit = new webkit();


/*
var loading = new Image();
loading.src = "images/loading.gif";
*/

//var waitHTML = '<div class="waitHTML"><img src = "' + loading.src + '"></div>';
var waitHTML = webkit.waitHTML;

// **** some DEBUGGING if necessary
function consoler(s) {
	/*
	if (window.console) {
		if (console.log) {
			console.log(s);
		}
	}
	*/
}

function ajax (page,queryString) {
	// legacy function
	webkit.ajaxPageload(page,queryString);
}

function initAjaxLinks(divtag) {
	// legacy function
	webkit.initAjaxLinks(divtag);
}

function webkit_playsong(songID,playerID) {
	webkit.playsong(songID,playerID);
}

function MBcontact(URL, title, width, overlayClose, recipient) {
	// invokes Modalbox contact form
	
	if (recipient) {
		URL += "?recipient=" + recipient;
	}
	
	Modalbox.show(URL, { title:title, width:width, overlayClose:overlayClose, afterLoad: function() {
		inspectMBheight();
	}});
}

var showscrollbar = 0;
function inspectMBheight() {
	// adjusts Modalbox sheet height to fit content, but unlike Modalbox provided function,
	// makes sure height does not exceed total browser height
	
	// make sure height is no larger than browser height minus offset, show scrollbar where necessary
	if ($('MB_content').getHeight() > browserheight() - 70) {
		// shrink window, add scrollbars if necessary
		var windowheight = browserheight() - 70;
		var contentheight = windowheight - 38;
		$('MB_window').setStyle({height: windowheight + "px"});
		$('MB_content').setStyle({overflow:"auto",height:contentheight + 'px'});
		showscrollbar = 1;
	}
	else if (showscrollbar) {
		// release constraints
		$('MB_window').style.height = "";
		$('MB_content').style.height = "";	
		showscrollbar = 0;	
		// make sure that height content has grown to with constraints gone does not exceed browserheight
		inspectMBheight();
	}
}

function emailform(formID) {
	webkit.emailform(formID);
}

function emailformObservers() {
	webkit.emailformObservers();
}

function browserheight() {
	// returns browser's height
	
	if (navigator.appName=="Netscape") {
	  winW = window.innerWidth;
	  winH = window.innerHeight;
	 }
	 if (navigator.appName.indexOf("Microsoft")!=-1) {
	  winW = document.body.offsetWidth;
	  winH = document.body.offsetHeight;
	 }
	return winH;
}

function check_address (ID, email, action) {
	// checks provided email address against Mailman list
	
	var ajaxParameters = 'ID=' + ID + '&email=' + email + '&action=' + action;
	
	new Ajax.Updater(ID, 'nm_webkit/templates/maillist_template_xhtml.php', {
		method: 'get',
		parameters: ajaxParameters,
		onComplete: function(transport) {
			if (transport.responseText && $('mailman_error')) {
				new Effect.Pulsate('mailman_error', {duration: 3, from:0.25, pulses:3});
			}
		}
	});
}

var rotatetimerheadline;
var paused_headline = 0;

function webkit_startrotateheadline() {
	clearTimeout(rotatetimerheadline);
	paused_headline = 0;
	rotatetimerheadline = setTimeout('webkit_rotateheadline()', headline_rotatespeed);
	return false;
}

function webkit_rotateheadline(nav) {
	var nextpic;
	var curpic;
	var lastpic;
	for (var x=0;$('crawler_' + x); x++) {
		
		if ($('crawler_' + x).style.display !== 'none') {
			// found current displayed pic		
			nextpic = x + 1;
			if (!$('crawler_' + nextpic) && headline_continuousrotation) {
				nextpic = 0;
			}
			curpic = x;
			lastpic = x - 1;
			if (lastpic < 0) { lastpic = 0; }
			
			if (nav == "pause") {
				// pause
				paused = 1;					
				clearTimeout(rotatetimerheadline);
			}
			else if ((nav && nav == "next" && !paused) || !nav) {
				new Effect.Fade('crawler_' + x, { duration:headline_fadeduration, afterFinish: function() {
					new Effect.Appear('crawler_' + nextpic, { duration:headline_fadeduration })									
					webkit_startrotateheadline();
					}});
			}	
			else if (nav && nav == "last" && !paused) {									
				new Effect.Fade('crawler_' + x, { duration:1, afterFinish: function() {
					new Effect.Appear('crawler_' + lastpic, { duration:headline_fadeduration })									
					webkit_startrotateheadline();
					}});
			}
		}
	}
}

function scrollto(anchor) {
	new Effect.ScrollTo(anchor, { duration: 0.5});
}

Element.addMethods({
	// rounded corner function
	
	corner: function( element, hash ) {
		element = $(element);
		var container = element.wrap( 'span', {'class' : 'rounderContainer'} );
		var width = hash.width;
		var height = hash.height;
		var spriteSource = hash.spriteSource;
		container.setStyle({
			margin : 0,
			padding : 0,
			position : 'relative',
			display: 'inline-block'
		});
		if (element.hasClassName('alignright')) {
			container.setStyle({float:'right'});
		}
		else if (element.hasClassName('alignleft')) {
			container.setStyle({float:'left'});
		}
		container.style.zoom = "1";
		if (container.style.display != "inline-block") {return;} // firefox2 fails here
		if (Prototype.Browser.IE) {
			var reIE = new RegExp("MSIE (\\d+\\.\\d+);"); // IE version number
			reIE.test(navigator.userAgent);
			var version = parseFloat(RegExp["$1"]);
			if (version < 7) { // if IE less than 7, exit
				return;
			}
		}
		['top left','top right','bottom right','bottom left'].each( function(corners, index) {
			var newCorner = new Element('div');
			var backgroundPosition = hash[corners.replace(/\s/,'')];
			newCorner.setStyle({
				margin: 0,
				padding: 0,
				display  : 'block',
				position : 'absolute',
				height :   height + 'px',
				width :    width  + 'px',
				backgroundImage :   'url(' + spriteSource + ')',
				backgroundRepeat :  'no-repeat',
				backgroundPosition : backgroundPosition 
			});
			$w(corners).each( function( flushTo ) {
				newCorner.setStyle(
					flushTo + ': 0'
				);
			});
			container.insert( newCorner );
		});
		return container;
	}
});

/* Author: Christopher E. Walker */

/*jslint browser: true, debug: true */
/*global $, $$, Effect, Position, Template, console */

function showEvent(e, ethis) {
	var temp = new Template("INFO: e.type: #{etype}; this: #{ethis}; e.element(): #{eelement}; e.relatedTarget: #{erelated};");
	var s = { etype: e.type,
		ethis: ethis.nodeName + "." + ethis.className,
		eelement: e.element().nodeName     + "." + e.element().className,
		erelated: e.relatedTarget.nodeName + "." + e.relatedTarget.className };
	consoler(temp.evaluate(s));
}
// **** end of DEBUG
function initDropDown(element, options) {
	// initialize dropdown menus
	
	element = $(element);
	var theID = element.identify();
	// **** Default transitions if none specified
	var reveal = (options && options.reveal) ? options.reveal : Effect.Appear.bindAsEventListener(Effect, {
		duration: 0.2
	});
	var disappear = (options && options.disappear) ? options.disappear : Effect.Fade.bindAsEventListener(Effect, {
		duration: 0.2
	});
	var revealDelay = (options && options.revealDelay) ? options.revealDelay : .3;

	if ( options.topLinkOnClick ) {
		element.select('.topLink').each( function(o) {
			o.observe( 'click', function(e) {
				options.topLinkOnClick(e);
			});
		});
	}
	else {
		element.select('.topLink').each( function(o) {
			o.observe( 'click', function(e) {
				if (o.href.match(/#$/)) {
					// don't show hash in address bar
					e.stop();
				}
			});
		});
	}

	if ( options.clickEffect ) {
		element.select('ul > li > ul a').each( function(o) {
			o.observe( 'click', function(e) {
				surroundList = o.up( '.wrapper');
				surroundList.parentNode.removeClassName( 'active' );
				options.clickEffect( o );
				e.stop();
			});
		});
	};
	// ******************************
	// **** wrap up in several <div>s
	var bottomUls = element.select("ul > li > ul.noJavaScript");
	bottomUls.each( function(bottomUl) {
		//bottomUl.wrap('div').wrap('div').wrap('div', {'class':'wrapper', 'style':'position:relative;'});
		bottomUl.removeClassName('noJavaScript');
		bottomUl.wrap('div').wrap('div').wrap('div');
        });
	// **** dynamically set static width (IE needs)
        element.select("ul > li > div").each( function(divWrapper) {
		divWrapper.addClassName('wrapper');
		if (window.dropdownBrowserIsIELessThan7) {
			divWrapper.select("ul")[0].style.width = (divWrapper.getWidth() + 2) + "px"; // for ie6
		}
		divWrapper.select('ul li a').each( function(a) {
			a.style.display = "block";
			a.style.position = "relative";
		});
                divWrapper.hide();
        });

	// mouseover and mouseout on the toplink <a> 
	var topLinks = $$('#' + theID + " > ul > li > a");
	topLinks.each( function(toplink) {
                toplink.addClassName('topLink');
		toplink.observe("mouseover", function(e) {
			// if coming up from lower wrapper:
			consoler('mouseover on A, deciding...');
			if (e.relatedTarget) {
				if ($(e.relatedTarget).descendantOf(this.parentNode) || (e.relatedTarget == this.parentNode) ) {
				    e.stop();
				    consoler('a toplink mouseover: e.relatedTarget =< this.parentNode \ncoming up from lower wrapper');
				    return;
                                }
			}
			if ($(this.parentNode).hasClassName("active")) {
			    e.stop();
			    consoler('a toplink mouseover: already active');
			    return;
			}
			$(this.parentNode).siblings().each( function(li) {
				if ($(li).hasClassName("active")) {
					disappear(li.select('.wrapper')[0]);
					consoler('remove active classname from sibling');
					$(li).removeClassName("active");
                                }
                        });
			this.parentNode.addClassName("active");
			var surroundList =  $($(this).nextSiblings()[0]);
			if (!surroundList) {
				consoler('has NO surroundlist, no reveal');
				return;
			}
			//surroundList.writeAttribute("style", "display: none; position: relative;");
			surroundList.style.display = "none";
			surroundList.style.position = "relative";
			surroundList.style.top = "0";
			surroundList.style.left = "0";
			surroundList.style.height = "auto";
			surroundList.style.width = "auto";
			consoler('let reveal');
			e.stop();

			/*new PeriodicalExecuter( function(pe) {
				if ( surroundList.parentNode.hasClassName( 'active' ) ) {
					reveal( surroundList );
				} else {
				}
				pe.stop();
			}, 2);*/

			setTimeout( function() {
				if ( surroundList.parentNode.hasClassName( 'active' ) ) {
					consoler( 'waited one sec? ');
					reveal( surroundList );
				}
			}, revealDelay * 1000 );

		}); 
		toplink.observe("mouseout", function(e) {
			var surroundList =  $(this.nextSiblings()[0]);
			if (!surroundList) {
				consoler('mouseout on upper A, but no wrapper so exit');
				$(this.parentNode).removeClassName("active");
				e.stop();
				return;
			}
			var x = e.pointerX();
			var y = e.pointerY();
			var bWithin = false;
			/*if (!Position.within(surroundList, x, y)) {
				disappear($(surroundList));
				consoler('DO: mouseout on topList A not in surroundList');
				$(surroundList.parentNode).removeClassName("active");
                        }*/
			if ($(e.relatedTarget).descendantOf(this.parentNode)) {
				consoler('descendant in surroundlist!!! \ncoming down from upper A');
				bWithin = true;
                        }
			if (!bWithin) {
				if ( $(surroundList.parentNode).hasClassName( 'active' ) ) {
					consoler( 'was active: ' + $(surroundList.parentNode).hasClassName( 'active' ) );
					$(this.parentNode).removeClassName("active");
					if (surroundList.style.display != "none" ) {
						disappear(surroundList);
					}
					consoler('mouseout on A: not within original surroundList');
				}
                        }
			e.stop();
		});
	});


	// **** mouseout on the lowerlevel <a> tags
	var topListItems = element.select("ul > li ul > li > a");
	topListItems.each( function(topListItem) {
		topListItem.observe("mouseout", function(e) {
			var surroundList = $(topListItem.parentNode.parentNode.parentNode.parentNode.parentNode);
			var topLink = surroundList.parentNode.select("A")[0];
			var x = e.pointerX();
			var y = e.pointerY();
			var bWithin = false;
			if (e.relatedTarget) {
				if ($(e.relatedTarget).descendantOf(surroundList)) {
					consoler('mouseout on lower As: inside surround DOM methods');
					bWithin = true;
				}
			}
			if (Position.within(topLink, x, y)) {
				consoler('mouseout on lower As: within method toplink');
				bWithin = true;
			}
			if (Position.within(surroundList.parentNode, x, y)) {
				consoler('mouseout on lower As: within method surroudList');
				bWithin = true;
			}
			surroundList.select('a').each( function(a) {
				if (Position.within(a, x, y)) {
					consoler('within method one of the <a>s');
					bWithin = true;
				}
			});
			if (e.relatedTarget) {
				if (e.relatedTarget.nodeName == "LI") {
					consoler('not in UL e.relatedTarget.nodeName == "LI"');
					bWithin = false;
				}
			}
			// if cursor not in UL:
			if (!bWithin) {
				if ( $(surroundList.parentNode).hasClassName( 'active' ) ) {
					consoler( 'was active: ' + $(surroundList.parentNode).hasClassName( 'active' ) );
					$(surroundList.parentNode).removeClassName('active');
					disappear(surroundList);
					consoler('mouseout on lower As');
				}
                        }
			e.stop();
		});
	});
	
	Event.observe(window, 'click', function() {
		// hide any visible menus
		webkit.hideAllSubmenus();
	});
}

function cursorLink() {
	webkit.cursorLink();
}

function cursorClear() {
	webkit.cursorClear();
}

function rotateContent(i) {
	if (!i) {
		// no rotate iteration set, start from beginning
		i = 0;
	}
	switch (rotatesettings.get('content')) {
		case 'image':
		// find next width and height
		nexti = parseInt(i) + 1;
		if (nexti == rotatecontentdata.length) { nexti = 0; }
		var thisWidth = rotatecontentdata[i][4] + 'px';
		var thisHeight = rotatecontentdata[i][5] + 'px';
		var nextWidth = rotatecontentdata[nexti][4] + 'px';
		var nextHeight = rotatecontentdata[nexti][5] + 'px';
		// set top and bottom layer images
		var thisImage = 'url(/nm_webkit/gallery_pics/' + rotatecontentdata[i][0] + ')';
		var nextImage = 'url(/nm_webkit/gallery_pics/' + rotatecontentdata[nexti][0] + ')';		

		$(rotatesettings.get('divID') + '_upper').setStyle({width:thisWidth,height:thisHeight,backgroundImage:thisImage});
		$(rotatesettings.get('divID') + '_lower').setStyle({width:nextWidth,height:nextHeight,backgroundImage:nextImage,display:'none'});
		if ($(rotatesettings.get('divID') + '_href')) {
			$(rotatesettings.get('divID') + '_href').setStyle({width:thisWidth,height:thisHeight});
		}
		
		switch (rotatesettings.get('effect')) {
			case 'crossfade':
			setTimeout(function() {			
				new Effect.Appear($(rotatesettings.get('divID') + '_lower'), { duration:1, afterFinish: function() {
					i++;
					if (i == rotatecontentdata.length) {
						i = 0;
					}
					rotateContent(i);
				}});
			}, rotatesettings.get('rotateDelay'));
			break;
			
			case 'fadeout':
			break;
			
			case 'slideup':
			break;
			
			case 'slidedown':
			break;
			
			case 'slideleft':
			break;
			
			case 'slideright':
			break;
			
			case 'blindup':
			break;
			
			case 'blinddown':
			break;
			
			case 'blindleft':
			break;
			
			case 'blindright':
			break;
		}
		
		break;
		
		case 'text':
		break;
	}
}

function loadJSCSSfile (filename, filetype){
	webkit.loadJSCSSfile(filename, filetype);
}


/***********************************/
/********* legacy functions ********/
/***********************************/

var dev;

/*
function ajax_regex (htmlcontent,divtag) {
	// convert hrefs to ajax links
	var swap_exp = /href(\s)*?=(\s)*?"([^"]+)"/im;                                                                   
	var search_page = htmlcontent;     
	// count number of instances
	//var exparray = swap_exp.exec(search_page);
	//alert (exparray[3] + exparray[4]);
	var swap;                                                                                                        
	var swap_check;                                                                                                  
	var ajax_page;                                                                                                   
	var swap_found = new Array(); 
	var search_iteration = 0;                                                                                   

	while (swap_check !== -1) { 
		search_iteration++;  
	//	if (search_iteration == 25) { alert ('overflow'); }                                                                                  
		swap_check = search_page.search(swap_exp);                                                               
		if (swap_check == -1 || search_iteration > 25) {                                                                                  
			// exit loop if no more links found, or break out of loop after 25 iterations                                                              
			break;                                                                                           
		}                                                                                                        
		swap = swap_exp.exec(search_page);  
		if (swap[3].substring(0,7) !== "http://" && swap[3].substring(0,8) !== "https://" && swap[3].substring(0,11) !== "javascript:" && swap[3].substring(0,7) !== "mailto:") { 
			// delete leading slash from URL, if necessary                                                   
			if (swap[3].substring(0,1) == "/") {
				// absolute link
			//	ajax_page = swap[3].substring(1);
				ajax_page = swap[3];
			}
			else {
				ajax_page = swap[3];
			}
			if (ajax_page) {
				htmlcontent = htmlcontent.replace(swap[0], "href=\"javascript:ajax('" + ajax_page + "')\"");
			}
			// delete from search string                                                                     
			search_page = search_page.replace(swap[0], "");
		}
		else {
			// external or AJAX link already processed, delete from search                                   
			search_page = search_page.replace(swap[0], "");
		}
		document.getElementById(divtag).innerHTML = htmlcontent;
	}
}
*/

function webkit_playsonglegacy (songID,playerID) {
	// sends track load info to Flash mediaplayer
	
	if (typeof playsong_precallback !== "undefined") {
		playsong_precallback();
	}
	
	// set playerID to default if not passed to function
	if (typeof playerID == "undefined") {
		if (typeof default_playerID !== "undefined") {
			playerID = default_playerID;	
		}
		else {
			// no default defined, use player 1
			playerID = 1;
		}
	}
	
	if (typeof mpsettings_1 !== "undefined") {
		// using hash for multiple mediaplayers
		
		// set mpsettings object to selected hash
		var mpsettings = eval('mpsettings_' + playerID);
		
		// determine how many players have been initialized
		for (x=1;$('mediaplayer_' + x);x++) { }
		var numPlayers = x-1;

		// stop any other players currently playing audio
		var thisQuerystring;
		var tmpMpsettings;
		for (x=1;x<=numPlayers;x++) {
			if (x !== playerID) {
				tmpMpsettings = eval('mpsettings_' + x);
				thisQuerystring = 'width=' + tmpMpsettings.get('mpWidth') + '&height=' + tmpMpsettings.get('mpHeight') + '&downloadbutton=' + tmpMpsettings.get('mpDlButton') + '&medialoader=' + tmpMpsettings.get('mpLoader') + '&firstload=1&altmediaplayer=' + tmpMpsettings.get('mpAltmediaplayer');
				
				// stop audio
				self.frames['mediaplayer_' + x].location.href='/nm_webkit/templates/mediaplayer.php?' + thisQuerystring;
				if (tmpMpsettings.get('mpScrollto') !== "undefined") {
					new Effect.ScrollTo('mediaplayerframe_' + x, { duration: 0.5});
				}
			}
		}
		
		// set defaults
		if (mpsettings.get('mpWidth') == "undefined") {
			mpsettings.set('mpWidth',400);
		}
		if (mpsettings.get('mpHeight') == "undefined") {
			mpsettings.set('mpHeight',40);
		}
		if (mpsettings.get('mpDlbutton') == "undefined") {
			mpsettings.set('mpDlbutton',false);
		}
		if (mpsettings.get('mpLoader') == "undefined") {
			mpsettings.set('mpLoader',true);
		}
		if (mpsettings.get('mpFirstload') == "undefined") {
			mpsettings.set('mpFirstload',true);
		}
		if (mpsettings.get('mpAltmediaplayer') == "undefined") {
			mpsettings.set('mpAltmediaplayer','');
			var mediaplayer = "mediaplayer.swf";
		}
		else {
			var mediaplayer = mpsettings.get('mpAltmediaplayer');
		}
		
		if (songID) {  
			var queryString = 'width=' + mpsettings.get('mpWidth') + '&height=' + mpsettings.get('mpHeight') + '&downloadbutton=' + mpsettings.get('mpDlButton') + '&medialoader=' + mpsettings.get('mpLoader') + '&firstload=' + mpsettings.get('mpFirstload') + '&altmediaplayer=' + mpsettings.get('mpAltmediaplayer') + '&songID=' + songID;
			
			if (mpsettings.get('mpDivTag')) {
				// insert music below div tag
				if ($('mediaplayerframe_' + playerID)) {
					// avoid duplicate players
					$('mediaplayerframe_' + playerID).remove();
				}
				$(mpsettings.get('mpDivTag')).insert('<div id = "mediaplayerframe_' + playerID + '"><iframe id = "mediaplayer_' + playerID + '" name = "mediaplayer_' + playerID + '" src = "/nm_webkit/templates/mediaplayer.php?' + queryString + '" width = "' + mpsettings.get('mpWidth') + '" height = "' + mpsettings.get('mpHeight') + '" scrolling = "no" marginwidth = "0" marginheight = "0" frameborder = "0"></iframe></div>');
			}
			else {
				// use iframe
				self.frames['mediaplayer_' + playerID].location.href='/nm_webkit/templates/mediaplayer.php?' + queryString;
				if (mpsettings.get('mpScrollto') !== "undefined") {
					new Effect.ScrollTo('mediaplayerframe_' + playerID, { duration: 0.5});
				}
			}
		}
	}
	else {
		// using global variables for single mediaplayer
		
		// set defaults
		if (typeof webkitMpWidth == "undefined") {
			webkitMpWidth = 400;
		}
		if (typeof webkitMpHeight == "undefined") {
			webkitMpHeight = 40;
		}
		if (typeof webkitMpDlButton == "undefined") {
			webkitMpDlButton = false;
		}
		if (typeof webkitMpLoader == "undefined") {
			webkitMpLoader = true;
		}
		if (typeof webkitMpFirstload == "undefined") {
			webkitMpFirstload = true;
		}
		if (typeof webkitAltmediaplayer == "undefined") {
			webkitAltmediaplayer = "";
		}
		if (songID) {   
			var queryString = 'width=' + webkitMpWidth + '&height=' + webkitMpHeight + '&downloadbutton=' + webkitMpDlButton + '&medialoader=' + webkitMpLoader + '&firstload=0&altmediaplayer=' + webkitAltmediaplayer + '&songID=' + songID;
			        
			if (typeof webkitMpDivtag !== "undefined") {
				// use div tag
				if ($('mediaplayerframe')) {
					// avoid duplicate players
					$('mediaplayerframe').remove();
				}
				$(webkitMpDivtag).insert('<div id = "mediaplayerframe"><iframe id = "mediaplayer" name = "mediaplayer" src = "/nm_webkit/templates/mediaplayer.php?' + queryString + '" width = "' + webkitMpWidth + '" height = "' + webkitMpHeight + '" scrolling = "no" marginwidth = "0" marginheight = "0" frameborder = "0"></iframe></div>');
			}
			else {
				// use iframe
				YUI().log('playerID: ' + playerID);
				self.frames['mediaplayer_' + playerID].location.href='/nm_webkit/templates/mediaplayer.php?' + queryString;
				if (webkitMpScrollto !== "undefined") {
					new Effect.ScrollTo('mediaplayer_frame', { duration: 0.5});
				}
			}
		}
	}

}

function ajax_regex (htmlcontent,divtag) {
	// converts standard hrefs into inline javascript ajax() calls, legacy purposes
	webkit.initAjaxLinks();
}

function checkrequired(which) {
	var pass=true;
	if (document.images) {
		for (i=0;i<which.length;i++) {
			var tempobj=which.elements[i];
			if (tempobj.name.substring(0,8)=="required") {
				if (((tempobj.type=="text"||tempobj.type=="textarea")&&
				tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&
				tempobj.selectedIndex==0)) {
					pass=false;
					break;
				}
			}
		}
	}
	if (!pass) {
		shortFieldName=tempobj.name.substring(8,30).toUpperCase();
		alert("There are missing fields in this form. Please make sure that all required fields are properly completed.");
		return false;
	}
	else
	return true;
}

function clearfield(textareaID) {
	if (textareaID) {
		if (document.getElementById(textareaID) && document.getElementById(textareaID).value == "enter the content of your email message here") {
			document.getElementById(textareaID).value = '';
		}
	}
	else if (typeof document.contact.requiredcontent !== "undefined" && document.contact.requiredcontent.value == "enter the content of your email message here") {
		document.contact.requiredcontent.value = '';
	}
}

function stopEventBubble (evt) {
	var e=(evt)?evt:window.event;
	if (window.event) {
		//alert ('cancel bubble');
		e.cancelBubble=true;
	} else {
		//alert ('stop propagation');
		e.stopPropagation();
	}
}

function hidemenus (menu) {
	// hide other menus that may be open
	var menunum = parseInt(menu.replace('menu',''));
	for (var m=1;m <= totalmenus;m++) {
		if (menunum !== m && document.getElementById("menu" + m) && document.getElementById("menu" + m).style.display == "block") {
			togglemenu ("menu" + m, "hide");
		}
	}
}

function togglemenu (menu, action, overColor, outColor) {
	overColor = "#" + overColor;
	outColor = "#" + outColor;
	
	if (action == "show") {
		// change link colors to accommodate :hover background color change
		var thismenuoption;
		for (var x=1;eval("document.getElementById('" + menu + "_" + x + "')");x++) {
			thismenuoption = menu + "_" + x;
			document.getElementById(thismenuoption).onmouseover = function () {
				this.firstChild.style.color = overColor;
			}
			document.getElementById(thismenuoption).onmouseout = function () {				
				this.firstChild.style.color = outColor;
			}
			document.getElementById(thismenuoption).onclick = function () {
				// load page after slight delay to prevent conflict with click of href link
			//	setTimeout("delayLoadPage(\"" + this.firstChild.href + "\")",100);
				window.location = this.firstChild.href;
			}
		}
	}
	
	var thisbutton = menu.replace('menu','butt');
	if (action == "show") {
		hidemenus(menu);  // hide any other menus that are currently visible
		document.getElementById(menu).style.opacity = 0.8;
		document.getElementById(menu).style.display = 'block';
		setTimeout('showmenu = 1', 1000);  // prevent conflict with window.onclick listener
	}
	else if (action == "hide") {
		new Effect.Fade(menu, { duration:0.25, afterFinish: function() {
			img_inact(thisbutton);
			showmenu = 0;
			}});
	}
}

/*
function delayLoadPage(page) {
	if (typeof loadingPage !== "undefined" && loadingPage == 0) { window.location = page; }
}
*/

/*
if (typeof totalmenus !== "undefined") {
	// clicking anywhere when menu is visible will hide all menus
	document.onclick=function(){
		for (m=1;m <= totalmenus;m++) {
			if (document.getElementById("menu" + m) && document.getElementById("menu" + m).style.display == "block" && showmenu) {
				togglemenu ("menu" + m, "hide");
			}
		}
	}
}
*/

if (typeof YUI == "undefined") {
	// force load YUI
	webkit.loadJSCSSfile('http://yui.yahooapis.com/combo?3.3.0pr3/build/yui/yui-min.js', 'js');
}

// init Webkit

var tabcallbacks = [];
var pagecallbacks = $A();

YUI().use('node', 'transition', 'event-custom', 'event-delegate', 'io-base', 'json-parse', 'json-stringify', 'swfdetect', function(Y) {
	Y.on('domready', function() {
		webkit.initYUIHistory(); 
		
		//for controlling YUI lazy loading caching
		webkit.moduleRevision = 2;
		
		// publish and fire event indicating webkit init
		webkit.customevent = new Y.EventTarget();
		//webkitevent.name = 'Webkit Init Event';

		webkit.customevent.publish('webkitevent:init', {
		    broadcast:  2,   // global notification
		    emitFacade: true // emit a facade so we get the event target
		});
		
		webkit.customevent.publish('localjs:init', {
			broadcast:  2,   // global notification
		    emitFacade: true // emit a facade so we get the event target
		});			
		
		// publish custom event for ajaxlinks callback and precallback
		webkit.customevent.publish('ajaxlinks:callback', {
		    broadcast:  2,   // global notification
		    emitFacade: true // emit a facade so we get the event target
		});
		webkit.customevent.publish('ajaxlinks:precallback', {
		    broadcast:  2,   // global notification
		    emitFacade: true // emit a facade so we get the event target
		});
		
		// publish custom event for loadcontent callback
		webkit.customevent.publish('loadcontent:callback', {
		    broadcast:  2,   // global notification
		    emitFacade: true // emit a facade so we get the event target
		});			
			
		webkit.hasFlash = Y.SWFDetect.getFlashVersion();			
		
		// fire Webkit init event
		webkit.customevent.fire('webkitevent:init');			
								
		// create shortcut to YUI node stuff
		webkit.Y = Y;			

		// hide all but the last jsondatablock

		// find total number of blocks
		/*
		var totaljsonblocks;
		$$('.jsondatablock').each(function(o,i) {
			totaljsonblocks = i;
		});

		// remove all but last block contents
		$$('.jsondatablock').each(function(o,i) {
			if (i !== totaljsonblocks && o.id == "jsondata") {
				o.remove();
			}
		});
		*/

		// init jsondata, set some safety defaults
		webkit.jsondata = { };
		webkit.jsondata.basepath = '/';
		
		if (Y.one('#pagecontent')) {
			// set cache on initial load (for sites that utilize AJAX navigation)
			if (location.pathname !== '/') {
				webkit.cacheToken = location.pathname.replace(/\//g,'_');				
			}
			else {
			//	webkit.cacheToken = "_yuistart";
			}

			webkit.cacheset('ajaxnav', webkit.cacheToken, webkit.Y.one('#pagecontent'));

			if (!Y.one('#jsondata')) {
				// JSON data block doesn't exist, create empty block
			//	Y.one('#pagecontent').insert('<div class="jsondatablock" id ="jsondata"></div>', 'after');
			}
			else {					
				webkit.jsondata = Y.JSON.parse(Y.one('#jsondata').get('value'));
			}
		}

		// init floating WordPress edit sidebar
		if (typeof webkit.jsondata !== "undefined" && webkit.jsondata.iswpdriven) {
			if (webkit.jsondata.iswppage) {
				var pagetype = "page";								
			}
			else {
				var pagetype = "post";							
			}
			Y.one('#pagecontent').append('<div id="nm_editwppagewrapper"><a id="nm_editwppage" href = "/wordpress/wp-admin/post.php?action=edit&post=' + webkit.jsondata.wppageid + '" target="new">Edit ' + pagetype + ' in WordPress</a></div>');			
		}

		// invoke all registered module init functions
		/*
		for (initFunc in webkit.initObservers) {
			Y.log('init: ' + initFunc);
			initFunc();
		}
		*/
		
		/*
		this.initobservers.each(function(initFunc) {
			initFunc();
		});			
		*/
		
		// init observers for other Webkit JS
		if (typeof nmstore !== "undefined" && typeof nmstore.initObservers !== "undefined") {
			// new store only
			Y.log('init store');
			nmstore.initObservers();
		}
	})
})

