// front-end JS file for VNSNY

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

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

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

/* sIFR config for VNSNY */

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
});

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

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;
		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
});

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

//** COPYRIGHT 2005-2006 - WhosCalling, Inc. **

//!!Do not change variable names!!

// don't document.write in the middle of previewing. bad mojo. -amlw 4/20/09
if (new String(document.location).indexOf("preview") == -1 && new String(document.location).indexOf("admin") == -1) {

  var CPMACCOUNTID='200542';
  var CPMClientDir='AmpAgency';
  var CPMPhoneNumber='8889438435';

  var CPMUrl;
  if(location.protocol == 'https:'){
  	CPMUrl='https://analyticssl.clickpathmedia.com';
  } else {
  	CPMUrl='http://analytics.clickpathmedia.com';
  }

  function RenderPhoneText(num, pat) {
    document.write(GetOfficePhoneText(num, pat));
  }

  function RenderPhoneImage(num, dir) {
    var CPMClientWebserver=document.domain; // Change this variable to your webserver address ex: 'www.example.com'
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Sep1.gif" alt="-">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(0,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(1,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(2,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Sep2.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(3,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(4,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(5,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Sep3.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(6,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(7,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(8,1) + '.gif">');
    document.write('<img src="http://' + CPMClientWebserver +  '/' + dir + '/Number' + num.substr(9,1) + '.gif">');
  }

  function GetOfficePhoneText(num, pat) {
    var strResult = "";
    var intDigit = 0;

    for(var i=0;i<pat.length;++i){
  	if (pat.charAt(i) == "N") {
  		strResult = strResult + num.charAt(intDigit);
  		intDigit = intDigit + 1;
  	}
  	else {
  		strResult = strResult + pat.charAt(i);
  	}
    }

    if (intDigit < 10) {
  	strResult = strResult + num.substr(intDigit);
    }

    return strResult;
  }

  function DisplayPhoneText(pat) {
  	//For backward compatibility
  	RenderPhoneText(CPMPhoneNumber,pat);
  }

  function DisplayPhoneImage(dir) {
  	//For backward compatibility
  	RenderPhoneImage(CPMPhoneNumber,dir);
  }

  function GetPhoneText(pat) {
  	//For flash compatibility
  	return GetOfficePhoneText(CPMPhoneNumber,pat);
  }

  function GetPhoneTextOffice(num, pat) {
  	//For flash compatibility
  	return GetOfficePhoneText(num,pat);
  }

  document.write('<script type="text/javascript" LANGUAGE="javascript" src="');
  document.write(CPMUrl + '/JS/' + CPMClientDir + '/clickpathremote.js');
  document.write('"><\/sc' + 'ript>');

  document.write('<script type="text/javascript" language="javascript" src="');
  document.write('https://clicktotalk.whoscalling.com/makeClickToTalk.js');
  document.write('"><\/sc' + 'ript>');

  function clickToTalk(PhoneNumber)
  {
  	makeClickToTalk('https://clicktotalk.whoscalling.com/', PhoneNumber, CPGetSessionValue());
  	window.setTimeout('CPMLogTraffic(\'104\')', 2000);
  }

}

// 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);
}