// front-end JS file for VNSNY

// ---------------------------------------------------------------------------

// fix IE
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}

// ---------------------------------------------------------------------------

/* sIFR config for VNSNY */
if (typeof(NOSIFR) === 'undefined') {
  var calvert = {
    'src': '/javascripts/sifr.calvert.swf',
    'ratios': [12,1, 13,1, 14,1, 15,1, 16,1, 17,1]
  };

  var avenir = {
    'src' : '/javascripts/sifr.avenir.swf',
    'ratios' : [12,1, 13,1, 14,1, 15,1, 16,1, 17,1]
  };

  sIFR.delayCSS  = true;

  sIFR.activate(avenir);
  sIFR.activate(calvert);

  sIFR.replace(avenir, {
    selector: ['.Partners H1.title'].join(","),
    css :[
    '.sIFR-root { color: #333333; }'
    ], wmode: 'transparent'
  });

  sIFR.replace(avenir, {
    selector: ['.Partners H2.title'].join(","),
    css :[
    '.sIFR-root { color: #333333; }'
    ], wmode: 'transparent'
  });

  sIFR.replace(calvert, {
    selector: ['#MainColumn H1.title', '#MainColumnHeader H1.title'].join(","),
    css :[
    '.sIFR-root { color: #333333; }'
    ], wmode: 'transparent'
  });

  sIFR.replace(calvert, {
    selector: ['#MainColumn H2.title', '#MainColumnHeader H2.title'].join(","),
    css :[
    '.sIFR-root { color: #333333; }'
    ], wmode: 'transparent'
  });

  sIFR.replace(calvert, {
    selector: ['H1.healthtitle'].join(","),
    css :[
    '.sIFR-root { color: #0d97cc; }'
    ], wmode: 'transparent'
  });
}

// ---------------------------------------------------------------------------

var SelectObserver = Behavior.create({
	initialize : function(){
		this.select_fieldset = this.element.up('FIELDSET');
		this.select_form = this.select_fieldset.up('FORM');
		if (!this.select_fieldset || !this.select_form)
			{ return; }
		this.select_fieldset.down('INPUT[type="submit"]').setStyle({ display : 'none' });
		this.element.observe('change', this.selectChangeHandler.bindAsEventListener(this));
	},
	selectChangeHandler : function(){
		this.select_form.submit();
	}
});

Event.addBehavior({	
	// Used on the Events filtering SELECT
	'.Event .pagination FORM SELECT#filter' : SelectObserver
});

// ---------------------------------------------------------------------------

var TextResizer = Behavior.create({
	initialize : function(font_sizes, target){
		this.font_sizes = font_sizes;
		this.maincolumn = $(target);
		this.buttons = this.element.select('.Link');
		if (!this.maincolumn || !this.font_sizes.length == 3 || !this.buttons.length == 3)
			{ return; }
		this.element.setStyle({ display : 'block' }); // show for js-enabled users
		for (x=0;x<3;x++) {
			this.buttons[x].observe('click', this.resizeText.bindAsEventListener(this, this.buttons[x]));
		}
	},
	resizeText : function(click, button) {
		if (!button.hasClassName('Selected')) {
			this.element.down('.Selected').removeClassName('Selected');
			button.addClassName('Selected');
			var type = button.id.split("_").last();
			switch(type) {
				case 'normal' :
					this.maincolumn.setStyle({ fontSize : this.font_sizes[0] });
					break;
				case 'larger' :
					this.maincolumn.setStyle({ fontSize : this.font_sizes[1] });
					break;
				case 'largest' :
					this.maincolumn.setStyle({ fontSize : this.font_sizes[2] });
					break;
				default :
					this.maincolumn.setStyle({ fontSize : this.font_sizes[0] });
					break;
			}
		}
	}
});

Event.addBehavior({
	'#sb_textsize' : TextResizer(['100%','115%','130%'], 'MainColumn')
});

// ---------------------------------------------------------------------------

var PrintLink = Behavior.create(PageWidget, {
	initialize : function(callback){
		this.initializeCallback = callback || Prototype.emptyFunction;
		this.link = $(this.element);
		if (!this.link) { return; }
		this.link.observe('click', function(e){ window.print(); return false; }.bind(this));
		this.initializeCallback();
	}
});

Event.addBehavior({
	'#sb_print' : PrintLink(function(){ this.element.setStyle({ display : 'block' }); }),
	'#health-cost-calculator #print-link' : PrintLink
});

// ---------------------------------------------------------------------------

var LightwindowMedia = Behavior.create({	
	initialize : function(){
		this.lightwindow_box = this.element.next('.lightwindow-box');
		if (typeof lightwindow == 'undefined' || !this.lightwindow_box)
			{ return; }
		this.lightwindow = new lightwindow;
		if (!this.lightwindow)
			{ return; }
		this.element.addClassName('Link').setStyle({ display : 'block' });
		this.element.observe('click', this.activateLightwindow.bindAsEventListener(this));
	},
	activateLightwindow : function(){
		this.lightwindow.activateWindow({
			xhtml : this.lightwindow_box.innerHTML.gsub('videotarget-',''),
			// since we replicate the html, we need to make sure the videotarget ID is unique in the lightwindow
			height : '300px',
			width : '730px',
			iframeEmbed: true,
			href : 'just_playing_nice_with_lightwindow'
		});
		this.activateSWF();
	},
	activateSWF : function(){
		var target = $('lightwindow_contents').down('.videotarget');
		var public_filename = target.down('.public_filename').innerHTML;
		var flashvars = { file : public_filename, bufferlength : "5" };
		var params = { allowfullscreen : "true", allowscriptaccess : "true", wmode : "opaque", menu : "false" };
		window.top.swfobject.embedSWF("/flash/player.swf", target.id, "267", "240", "9.0.0", "/flash/express_install.swf", flashvars, params);
	}
});

Event.addBehavior({
	'.Generic .lightwindow' : LightwindowMedia
});

// ---------------------------------------------------------------------------

var DHTMLMenu = Behavior.create(PageWidget, {
	initialize : function(config) {
		this.setOptions(config);

		this.submenus = { };

		// get all the top-level LIs in the menu and iterate over them, adding event handlers
		this.element.immediateDescendants().each(function(item){
			item.observe("mouseover", this.mouseoverHandler.bindAsEventListener(this, item));
			item.observe("mouseout", this.mouseoutHandler.bindAsEventListener(this, item));

			this.submenus[item.id] = item.down().next();
		}.bind(this));

	},

	initialized : false,
	node : null,              // holds the DOM node of the menu
	menu_hide_timeout : null, // the JS timeout ID for hiding the menu
	menu_show_timeout : null, // the JS timeout ID for showing the menu
	last_menu_on : null,      // the DOM object of the waiting to close

	mouseoverHandler : function(e, item) {
		// stop the menu from closing/opening (this gets called a lot)
		clearTimeout(this.menu_hide_timeout);
		clearTimeout(this.menu_show_timeout);

		// if we're mousing over the menu for the first time, set a timeout so the menu doesn't show up accidentally.
		if (this.last_menu_on == null) {
			this.menu_show_timeout = setTimeout(this.showMenu.bind(this, item),	this.CONFIG["menu_show_time"]);

		// if there's already a menu on, then we know the user is expecting to see another one, so show it immediately.
		} else if (this.last_menu_on != item) {
			this.showMenu(item);
		}
	},

	mouseoutHandler : function(e, item) {
		// clear the existing show/hide timeouts (this gets called a lot)
		clearTimeout(this.menu_hide_timeout);
		clearTimeout(this.menu_show_timeout);

		// only "close" the menu in a little bit if we're over a menu with submenus, otherwise, close it right now
		if (this.submenus[item.id]) {
			this.menu_hide_timeout = setTimeout(this.hideMenu.bind(this, item),	this.CONFIG["menu_hide_time"]);

		} else {
			this.hideMenu(item);
		}
	},

	// shows the menu
	showMenu : function(item) {
		// hide the last menu shown
		if (this.last_menu_on != null) { this.hideMenu(this.last_menu_on); }

		// adding the "hover" class turns on the menu
		item.addClassName(this.CONFIG['hover_class']);

		// insert the IFRAME for IE
		if (Prototype.Browser.IE6) {
			// get at the submenu for dimension info
			var submenu = this.submenus[item.id];
			if (submenu) {
				var iframe = submenu.next();

				if (submenu && !iframe) {
					this.createIframe(item, {
						'left'   : submenu.offsetLeft + "px",
						'height' : submenu.offsetHeight + "px",
						'width'  : submenu.offsetWidth + "px"
					});
				}
			}
		}

		// store the last item on
		this.last_menu_on = item;

	}, // END: showMenu()

	// hide the menu
	hideMenu : function(item) {
		// nothing to hide
		if (item == null) return;

		// removing the "hover" class turns off the menu
		item.removeClassName(this.CONFIG['hover_class']);

		// remove the IFRAME for IE
		if (Prototype.Browser.IE6) {
			var submenu = this.submenus[item.id];
			if (submenu) {
				var iframe = submenu.next();
				if (submenu && iframe) {
					item.removeChild(iframe);
				}
			}
		}

		this.last_menu_on = null;
	}, // END: hideMenu()

	// makes an IFRAME the exact size of the menu so elements underneath it are covered
	// (IE-only)
	createIframe : function(node, style) {
		node.insert({ 'bottom' : ('<iframe class="' + this.CONFIG['iframe_class'] + '" frameborder="0" scrolling="no" style="width: #{width}; height: #{height}; left: #{left};"><\/iframe>').interpolate(style) } );
	}
});

DHTMLMenu.CONFIG = {
	submenu_class : "SubMenu", // the DOM class of the menu container
	hover_class : "Hover", // the class to give the top-level LI to "activate" the menu
	menu_hide_time : 500, // time to keep the menus on after mouseout; in ms
	menu_show_time : 100, // threshold o
	iframe_class : "IframeFix"
};

fixWebKitInheritanceBug(DHTMLMenu);

Event.addBehavior({
	'.DHTMLMenu' : DHTMLMenu,
	'.DHTMLMenu LI .SubMenu .Content UL' : DHTMLMenu,
	'#SocialLinks UL' : DHTMLMenu
});

// ---------------------------------------------------------------------------
var ParseVideo = Behavior.create({
	initialize : function(){
		this.video_link = this.element.up('A');
		if (this.video_link && this.video_link.href.match(/.flv/)) {
			var meta = {
				file: this.video_link.href,
				height: 276,
				width: 469
			};
			var html = '';
			html += '<object width="' + meta.width + '" height="' + meta.height + '" type="application/x-shockwave-flash" data="/flash/player.swf">';
			html += '<param name="allowfullscreen" value="true">';
			html += '<param name="allowscriptaccess" value="true">';
			html += '<param name="wmode" value="opaque">';
			html += '<param name="menu" value="false">';
			html += '<param name="flashvars" value="file=' + meta.file + '&amp;bufferlength=5">';
			html += '</object>';
			this.video_link.replace(html);
		}
	}
});

Event.addBehavior({
	'#BodyWrapper.Home #CenterFeature A IMG' : ParseVideo
});

// ---------------------------------------------------------------------------

var SendToFriend = Behavior.create({
	initialize : function(){
		this.send_link = this.element.down('A');
		if (!this.send_link) { return; }
		this.send_location = this.send_link.href.toString().replace(/%20/g,'+');//replace %20 with + so that it doesn't get double encoded, turning into %2520
		this.send_link.removeAttribute('href');
		this.element.addClassName('Link');
		this.element.observe('click', this.openSendToFriend.bindAsEventListener(this));
	},
	openSendToFriend : function(){
		var popup = window.open(this.send_location, "SendToFriend", "width=600,height=600,toolbars=no,scrollbars=yes");
		popup.focus();
	}
});

Event.addBehavior({
	'#sb_send' : SendToFriend('/sendtofriend')
});

// ---------------------------------------------------------------------------

var GoogleAnalyticsDownloadTracking = Behavior.create({
	
	LINK_REGEX : /\.(zip|pdf|docx?|xlsx?|pptx?)(\?.*)?$/,
	
	initialize : function(config){
		if (!window["pageTracker"] || typeof window["pageTracker"]._trackPageview !== "function")
			return;
		Object.extend(this, config || {});
		
		var links = this.element.getElementsByTagName("A");
		var domain = new RegExp(document.domain + '$');
		
		for (var i = 0, link; link = links[i]; i++)
			if (link.href && link.hostname.match(domain) && link.href.match(this.LINK_REGEX))
				$(link).observe("click", this.trackingLinkClickHandler.bind(this, link.href));
	},
	
	trackingLinkClickHandler : function(href){
		window["pageTracker"]._trackPageview(href.split("?")[0]);
	}
	
});

Event.addBehavior({
	"body" : GoogleAnalyticsDownloadTracking
});

// ---------------------------------------------------------------------------

var PopupLink = Behavior.create({
	initialize : function(){
		this.target_href = this.element.getAttribute('href');
		this.element.addClassName("Link").removeAttribute('href');
		this.element.observe('click', this.popupClickHandler.bindAsEventListener(this));
	},
	popupClickHandler : function(e){
		var popup = window.open(this.target_href, this.element.title, "width=750,height=600,toolbars=no,scrollbars=yes");
		popup.focus();
		e.stop();
	}
});

Event.addBehavior({
	".PopupLink" : PopupLink
});

// ---------------------------------------------------------------------------

// Cookie handling from quirks

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
