


var Popup=null;
var NS4 = (document.layers) ? true : false;

function checkEnter(event)
{
	var code = 0;
	if (NS4)
		code = event.which;
	else
		code = event.keyCode;
	if (code==13){
		submitSearch();
	}
}

function submitSearch()
{
	var url ="<ptl:createPortalPageChangeURL pageName='search' doRedirect='false'/>";
	var intxt = document.bannersearch.search.value;
	var tempurl = url+"&param="+intxt
	if(intxt==""){
		alert("Please enter the search term.");
	}else{
		self.location=tempurl;
	}
}

function submitOnEnter(event, myObject){

    var code = 0;
    if (NS4)
        code = event.which;
    else
        code = event.keyCode;
    if (code==13){

        for (var i=0; i<document.forms.length; i++) {
            for (var j=0; j<document.forms[i].elements.length; j++)
            {
                 if (document.forms[i].elements[j] == myObject) {
                    document.forms[i].submit();
                    return true;
                 }
             }
        }
    }

    return false;
}

function leaveSite(obj){
	var tempLink = obj.href;
    if (tempLink.indexOf("extSite=") != -1) {
        tempLink = tempLink.substr(tempLink.indexOf("extSite="), tempLink.length);
        //alert(tempLink);        
    }
    // The order of these if statments matters!
	if (tempLink.indexOf("www.biogenidec.com")>-1){
		return confirm("You have clicked on a link that will take you out of this website");
	} else if (tempLink.indexOf("www.msleadersofhope.com")>-1){
		return confirm("You have clicked on a link that will take you out of this website");
	} else if (tempLink.indexOf("www.touchprogram.com")>-1){
		return confirm("You have clicked on a link that will take you out of this website");
	} else if(tempLink.indexOf("boss.streamos.com")>-1){
		return true;
	} else if(tempLink.indexOf("www.avonex.com")>-1){
		return confirm("You have clicked on a link that will take you out of the TYSABRI.com website");
	} else if(tempLink.indexOf("www.msactivesource.com")>-1){
		return confirm("You have clicked on a link that will take you out of the TYSABRI.com website");
	} else if(tempLink.indexOf("avonex/home")>-1){
		return confirm("You have clicked on a link that will take you out of the TYSABRI.com website");
	} else if(tempLink.indexOf("msas/home")>-1){
		return confirm("You have clicked on a link that will take you out of the TYSABRI.com website");
	} else if(tempLink.indexOf("medinfo.biogenidec.com")>-1){
		return confirm("You have clicked on a link that will take you out of the TYSABRI.com website");
	} else{
		return confirm("You are leaving TYSABRI.com. This link will take you to a website that is outside the control of Biogen Idec. We provide links as a public service and for informational purposes only. We do not make or imply any endorsement of external web sites.");
	}
}

/**
 * Strange name because Weblogic has its own openPopup method.
 **/
function openDefaultPopup(destination) {
    openPopup(645, 450, destination, 'yes', 'yes');
}

function openPopup(width,height,destination,scrollbars)
{
	openPopup(width,height,destination,scrollbars,"no");
}

function openPopup(width,height,destination,scrollbars,menu)
{
	LeftPosition=(screen.availWidth)?(screen.availWidth-width)/2:50;
	TopPosition=(screen.availHeight)?(screen.availHeight-height)/2:50;
	settings='width='+width+',height='+height+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scrollbars+',location=no,directories=no,status=no,menubar='+menu+',toolbar=yes,resizable=yes';
	Popup = window.open(destination,'popup',settings);
	Popup.focus();
}

/* *
 * Simple method used in a anchor to hide from spiders.
 * */
function hideLink(link){
    window.location = link;
}

function quicklinksgoto(form)
{
	var index = form.QuickLinks.selectedIndex;
	if (form.QuickLinks.options[index].value != "0")
	{
		location=form.QuickLinks.options[index].value;
	}
	//document.QuickLinks.submit();
}


//IPInfoDB javascript JSON query example
//Tested with FF 3.5, Opera 10, Chome 5 and IE 8
//Geolocation data is stored as serialized JSON in a cookie
//Bug reports : http://forum.ipinfodb.com/viewforum.php?f=7
function geolocate(timezone, cityPrecision, objectVar) {

var api = (cityPrecision) ? "ip_query.php" : "ip_query_country.php";
var domain = 'api.ipinfodb.com/v2/';
var url = "http://" + domain + "/" + api + "?output=json" + ((timezone) ? "&timezone=true" : "&timezone=false" ) + "&key=a3fc8bc87c9d388b26a729413891e6a9ad2f8e3f29db61db11fb2de9dc9b6f10 " +"&callback=" + objectVar + ".setGeoCookie";
var geodata;
var callbackFunc;
var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
  var t = typeof (obj);
  if (t != "object" || obj === null) {
    // simple data type
    if (t == "string") obj = '"'+obj+'"';
      return String(obj);
  } else {
  // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);
    for (n in obj) {
      v = obj[n]; t = typeof(v);
      if (t == "string") v = '"'+v+'"';
      else if (t == "object" && v !== null) v = JSON.stringify(v);
      json.push((arr ? "" : '"' + n + '":') + String(v));
    }
    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
  }
};

// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
  if (str === "") str = '""';
    eval("var p=" + str + ";");
    return p;
};

//Check if cookie already exist. If not, query IPInfoDB
this.checkcookie = function(callback) {
  geolocationCookie = getCookie('geolocation');
  callbackFunc = callback;
  if (!geolocationCookie) {
    getGeolocation();
  } else {
    geodata = JSON.parse(geolocationCookie);
    callbackFunc();
  }
}

//API callback function that sets the cookie with the serialized JSON answer
this.setGeoCookie = function(answer) {
  if (answer['Status'] == 'OK') {
    JSONString = JSON.stringify(answer);
    setCookie('geolocation', JSONString, 365);
    geodata = answer;
    callbackFunc();
  }
}

//Return a geolocation field
this.getField = function(field) {
  try {
    return geodata[field];
  } catch(err) {}
}

//Request to IPInfoDB
function getGeolocation() {
  try {
    script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);
  } catch(err) {}
}

//Set the cookie
function setCookie(c_name, value, expire) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expire);
  document.cookie = c_name+ "=" +escape(value) + ((expire==null) ? "" : ";expires="+exdate.toGMTString());
}

//Get the cookie content
function getCookie(c_name) {
  if (document.cookie.length > 0 ) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start != -1){
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end == -1) {
        c_end=document.cookie.length;
      }
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return '';
}
}

/********************************************************
 *  Event locator callout functionality on home page
 ********************************************************/
 
 $(function(){
	/** Link areas on home page for Event Location or Search **/
	defaultEventLink = "/tysbProject/tysb.portal/_baseurl/twoColLayout/SCSRepository/en_US/tysb/home/connect-with-people/ms-events-schedule.xml";
		$('#eventSearchLink').click(function(){
		callPixel();
		self.location.href = defaultEventLink;
		});
		$('.eventLink').attr('href', defaultEventLink);		
});

 
/********************************************************
 * Script to call tracking pixel
*********************************************************/
 
function callPixel() {

 var _dropTag=function() {
 var _qS='';
 var _rand=Math.random()+'';
 var _rs=document.location.protocol+'//';
 var xp1_qs=new Array();

 xp1_qs['_t']            = 'attendmscont';

 xp1_qs['_random'] = _rand*100000000000;
 for(var qsKey in xp1_qs){_qS += '&'+qsKey+'='+xp1_qs[qsKey];}
 document.write('<iframe src="'+_rs+'d.xp1.ru4.com/meta?_o=23323658'+_qS+'" width="0" height="0" frameborder="0" scrolling="no"></iframe>');}
 _dropTag();

}


/** Routine to parse out query string values during testing 	**/
/** name=value is: test=[e|t|f] (event, teleconference, fail) 	**/
/** 			use is: $.getQueryString('test')				**/

	
;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);
                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);
                return params;
            }
            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 
            return this.queryStringParams[name];
        }
    });
})(jQuery);


 
var responseData;

function getEvent(reqCity, reqState) {

	//console.log('reqCity = ' + reqCity + ', reqState = ' + reqState);
	var thetest = $.getQueryString('test');
	if(thetest == 't'){ reqCity = 'Phoenix'}  // force event in Phoenix
	if(thetest == 't'){ reqState = 'Arizona'}  // force event in Arizona
	
	if(thetest == 'e'){ reqCity = 'Boston'}  // force event in Phoenix
	if(thetest == 'e'){ reqState = 'Massachusetts'}  // force event in Arizona

	$.ajax({
	      url: "/tysbProject/portlet/events/getLocalEvent.do",
	      type: "POST",
	      data: {'city' : reqCity ,'state' : reqState, 'radius' : 20},
	      dataType: "json",
	      success: function(responseData){
	         //console.log(responseData);
	         updateEvent(responseData);
	      },
	      error: function(responseData){
	    	  //console.log(XMLHttpRequest + ', ' + textStatus + ', ' + errorThrown);
			  eventFail();
	      }
	});
}



function updateEvent(eventData) {

var thetest = $.getQueryString('test');
var eventErr;

	/** for testing [forcing] error state with query string "?test=f" **/	
	thetest == 'f' ? eventErr = 'error' : eventErr = eventData.error;
	

	if(!eventErr && (eventData.eventsList != undefined)){										// No errors reported during call to event search
	var eventsList = eventData.eventsList;				// Array of Events, if any
	var eventsLen = eventsList.length;					// Count Events Returned
	
		if(eventsLen > 0){								// At least one Event found
		var theEvent = eventsList[0];					// Use First Event in Array
		var eventState = theEvent.state.toUpperCase();	// The state data determines the type.  If it is "NA" then it is a teleconference, otherwise [MA,NC,HI, etc] it's a location.
		
		/** for testing [forcing] event or teleconference with query string "?test=e" or "?test=t" **/
		if(thetest == 'e'){ eventState = 'MA'}  // force event in Massachusetts
		if(thetest == 't'){ eventState = 'NA'}  // force teleconference
		
		if(eventState == "NA"){
		$('#eventImageView').attr('src','/en_US/tysb/site/images/callout-events-telephone.gif');	// Teleconference
		$('#home-rightcallout').css('background-image','url(/en_US/tysb/site/images/callout-events-bkgd.gif)');	// Background for whole callout when event is available
		}else{
		$('#home-rightcallout').css('background-image','url(/en_US/tysb/site/images/callout-events-bkgd.gif)');	// Background for whole callout when event is available
		$('#eventImageView').attr('src','/en_US/tysb/site/images/callout-events-event.gif');		// Location Event
		}
		
		/** Collect necessary data types for display **/
		var eventID = theEvent.id;			
		var eventUrl = '/tysbProject/tysb.portal?_nfpb=true&_pageLabel=twoColLayout&content_2_actionOverride=/portlet/events/eventDetails&_windowLabel=content_2&content_2eventId=';
		eventUrl += eventID;
		var eventTitle = theEvent.title;
		var eventCity = theEvent.city;
		var eventState = theEvent.state;
		var eventMap = theEvent.city + ', ' + theEvent.state;
		var eventLocation = eventMap;
		//var eventLocation = theEvent.eventDesc;  // func spec identifies event city and state for this field value, not description
		var eventDate = theEvent.startDt;								// In GMT Time milliseconds
		
		/** Date conversion from milliseconds given to us **/
		//var dumbdate = new Date();  									// dummy date just for getting out timezone offset below
		//var millioffset = dumbdate.getTimezoneOffset() * 60000;   		// get difference of milliseconds from GMT to local time
		//eventDate = eventDate - millioffset;							// reduce GMT time from server to local time
		var theDateObj = new Date(parseFloat(eventDate));
		var thedow = theDateObj.getDay();
		var theday = theDateObj.getDate();
		var themonth = theDateObj.getMonth();
		var monthArray = ['Jan','Feb','Mar','Apr','May','Jun','July','Aug','Sept','Oct','Nov','Dec'];
		var dowArray = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
		var eventDateString = dowArray[thedow] + ', ' + monthArray[themonth] + '. ' + theday ;	
		
		/** String Manipulations **/
		var maxtitlelength = 40;										// maximum character length for TITLE
		var maxloclength = 22;											// maximum character length for LOCATION
		var elipsis = "<span style='font-size:.8em;'>&#8230;<\/span>";	// "elipsis" (or equivalent) addition to truncated lines
		if(eventTitle.length > maxtitlelength){
		eventTitle = eventTitle.substr(0,(maxtitlelength - 1)); 		// Truncate Title to a specified length.
		eventTitle = eventTitle.replace(/^\s+|\s+$/g, '');				// Remove any spaces before or after the string
		eventTitle += elipsis;											// append an elipsis
		$('#eventTitle').attr('title', theEvent.title);					// Set title to full value for tooltip
		$('#eventTitle').css('cursor','help');							// Change cursor to arrow to reflect hover information
		}
		
		if(theEvent.eventDesc == 'Teleconference'){eventLocation = theEvent.eventDesc}
		if(eventLocation.length > maxloclength){
		eventLocation = eventLocation.substr(0, (maxloclength - 1));	// Truncate Location (description) to a specified length.
		eventLocation = eventLocation.replace(/^\s+|\s+$/g, '');		// Remove any spaces before or after the string	
		eventLocation += elipsis;										// append an elipsis
		$('#eventLocation').attr('title', eventMap);					// Set title to full value for tooltip
		$('#eventLocation').css('cursor','help');						// Change cursor to arrow to reflect hover information
		}
		
		/** Populate The Display Areas **/
		$('#eventTitle').html(eventTitle);
		$('#eventLocation').html(eventLocation);
		$('#eventDate').html(eventDateString);
		$('#viewEventLink').click(function() {callPixel();});
		$('#viewEventLink').attr('href', eventUrl);
		$('#eventInfoLinks').show();
		// Don't show "change location" link for teleconference
		eventState == "NA" ? $('#eventChange').hide() : $('#eventChange').show() ;
	
		
		}else{
			eventFail();		// Fallback during no events
		}
	
	}else{  					
		eventFail();			// Fallback during server error 
	}
	
	
}

function eventFail(){		
		//$('#eventTitle').html('No Events Found');
		$('#eventTitle').hide();
		$('#eventLocation').html('Learn about our Peer to Peer Teleconferences and any live events in your area.');
		$('#eventDate').hide();
		$('#eventInfoLinks').show();
}


