// redefine siteroot in case it hasn't been set elsewhere
var siteroot = (typeof(fullsiteroot) == "function") && (typeof(sitehost) == "function") ? fullsiteroot().replace(sitehost(), "") : "/";

var filterVar = function(varvalue) {
	var newval = "";
	for (var i = 0; i< varvalue.length; i++) {
		var charcode = varvalue.charCodeAt(i);
		if (varvalue.charAt(i) != "\t" && varvalue.charAt(i) != "\n" && varvalue.charAt(i) != "\r\n" 
				&& (i != 0 || varvalue.charAt(i) != " ") && (i != (varvalue.length - 1) || varvalue.charAt(i) != " ")) {
			if (charcode <= 127) {
				newval += varvalue.charAt(i);	
			}
			else {
				if (charcode >= 192 && charcode <= 197) newval += "A";
				else if (charcode == 198) newval += "AE";
				else if (charcode == 199) newval += "C";
				else if (charcode == 199) newval += "C";
				else if (charcode >= 200 && charcode <= 203) newval += "E";
				else if (charcode >= 204 && charcode <= 207) newval += "I";
				else if (charcode == 208) newval += "D";
				else if (charcode == 209) newval += "N";
				else if (charcode >= 210 && charcode <= 214) newval += "O";
				else if (charcode >= 217 && charcode <= 220) newval += "U";
				else if (charcode >= 224 && charcode <= 229) newval += "a";
				else if (charcode == 230) newval += "ae";
				else if (charcode == 231) newval += "c";
				else if (charcode >= 232 && charcode <= 235) newval += "e";
				else if (charcode >= 236 && charcode <= 239) newval += "i";
				else if (charcode == 240) newval += "o";
				else if (charcode == 241) newval += "n";
				else if (charcode >= 242 && charcode <= 246) newval += "o";
				else if (charcode >= 249 && charcode <= 252) newval += "u";
				else if (charcode == 253) newval += "y";
				else if (charcode == 338) newval += "OE";
				else if (charcode == 339) newval += "oe";
				else if (charcode == 352) newval += "S";
				else if (charcode == 353) newval += "s";
				else if (charcode == 376) newval += "Y";
			}
		}
	}
	// strip tags
	newval = newval.toLowerCase().replace(/(<([^>]+)>)/ig,"").replace(/&#\d+/ig, "").replace(/&\w+;/ig,"");
	return newval;
}

var fixcase = function (stIn){
	if (stIn != null && typeof(stIn) != 'undefined')
		return stIn.toLowerCase();
	else
		return stIn;
}

var siteCatalystEmailSurgeon = function(ele,name,id) {
	s=s_gi(s_account);
	s.eVar20 = filterVar("(" + id + ") " + name);
	s.events = "event24";
	s.linkTrackVars = "prop50,eVar3,eVar20,eVar50,channel,events,pageName,server,hier3";
	s.linkTrackEvents = "event24";
	s.tl(true,'o','Surgeon Email Click');
}

var siteCatalystCTALink = function(ele){
	s=s_gi(s_account);
	var linktitle = findlinktitle(ele.innerHTML);
	s.eVar36 = filterVar(linktitle);
	s.linkTrackVars = "eVar36";
	s.tl(true,'o','Helpful tools link');
}

var findlinktitle = function (oldstring) {
// find the link by looking for <a </a. If cannot, then just return the text with html stripped out.
	var newString = "";
	var startpos = oldstring.toLowerCase().indexOf("<a");
	var endpos = oldstring.toLowerCase().indexOf("</a");
	if ((startpos<0) || (endpos<0) || (endpos < startpos)){
		return stripHTML(oldstring);
	}
	newString = oldstring.substring(startpos, endpos+3) +'>';
	return stripHTML(newString);
}

var siteCatalystBMI = function(bmi,qual,h,w) {
	s=s_gi(s_account);
	s.prop6 = h;
	s.prop7 = w;
	s.eVar10 = bmi;
	s.eVar11 = filterVar(qual);
	s.events = "event30";
	s.linkTrackVars = "prop6,prop7,prop50,eVar3,eVar10,eVar11,eVar50,channel,events,pageName,server,hier3";
	s.linkTrackEvents = "event30";
	s.tl(true,'o','BMI Calculator Result');
}

var siteCatalystPrint = function(islogged_in){
	window.print();
	s=s_gi(s_account);
	s.prop29 = s.prop50;
	if (s.prop29.indexOf('preparation_checklist') > -1) {
		s.events = "event16";
		s.linkTrackVars = "prop29,prop50,eVar3,eVar50,channel,events,pageName,server,hier3";
		s.linkTrackEvents = "event16";
		s.tl(true,'o','Print Preparation Checklist');
	} else if (s.prop29.indexOf('/recipe/') > -1) {
		if(islogged_in){
			s.events = "event6";
			s.eVar24 = "recipe tool - print a recipe"
			s.linkTrackEvents = "event6";
		}
		s.linkTrackVars = "prop29,prop50,eVar3,eVar24,eVar50,channel,events,pageName,server,hier3";
		s.tl(true,'o','Print a Recipe');
	} else {
		s.linkTrackVars = "prop29,prop50,eVar3,eVar50,channel,events,pageName,server,hier3";
		s.tl(true,'o','Print Page');
	}
}


var siteCatalystEvent6 = function(tool, action) {
	var interaction;
	if (tool != null)
	{
		if (action!=null)
			interaction = filterVar(tool + ' - ' + action);
		else
			interaction = filterVar(tool);
	} else {
		if (action!=null)
			interaction = filterVar(action);
		else
			return; //both are null, can't go on.
	}

	s=s_gi(s_account);
	s.events="event6";
	if (s.eVar24){
		var check = ";" + s.eVar24 + ";";
		if (check.indexOf (";" + interaction + ";") <0)
		{
			s.eVar24 = s.eVar24 + ';' + interaction;
		}
	}else
		s.eVar24 = interaction;  // eg:   Recipe Tool - Print a Recipe
	s.linkTrackVars = "eVar24,channel,events,pageName,server,hier3";
	s.linkTrackEvents = "event6";
	s.tl(true,'o', action); // eg:  Print a Recipe
	s.eVar24 = "";
}


var siteCatalystShare = function() {
	s=s_gi(s_account);
	s.prop30 = s.prop50;
	s.linkTrackVars = "prop30,prop50,eVar3,eVar50,channel,events,pageName,server,hier3";
	s.tl(true,'o','Share Page URL');
}

var siteCatalystLink = function(href,inner) {
	s=s_gi(s_account);
	var isPartner = '';
	href=fixcase(href);
	if (href.indexOf('mylapbandtlc') > -1) isPartner = 'Lindora';
	if (href.indexOf('carecredit') > -1) isPartner = 'CareCredit';
	if (href.indexOf('curvesdirect') > -1) isPartner = 'Curves';
	if ((href.indexOf('my-emmi.com') > -1) || (href.indexOf('emmisolutions.com') > -1)) isPartner = 'Emmi';
	//if (href.indexOf('lapbandcanada.ca/') > -1) isPartner = 'Lapband Canada';
	//if (href.indexOf('lapbandcentral.com') > -1) isPartner = 'Lapband Central';
	
	if (isPartner != ''){
		s.events = "event19";
		s.prop25 = filterVar(stripHTML(inner));
		s.prop26 = filterVar(href);
		s.eVar18 = filterVar(isPartner);
		s.eVar19 = filterVar(href);
		s.linkTrackVars = "prop25,prop26,prop50,eVar3,eVar18,eVar19,eVar50,channel,events,pageName,server,hier3";
		s.linkTrackEvents = "event19";
		if (isPartner == 'Curves'){
			s.eVar24 = filterVar("sign up with Curves");
			s.events += ",event6";
			s.linkTrackVars += ",eVar24";
			s.linkTrackEvents += ",event6";
		}
		else if (isPartner == 'Lindora'){
			s.eVar24 = filterVar("partner exit - Lindora");
			s.events += ",event6";
			s.linkTrackVars += ",eVar24";
			s.linkTrackEvents += ",event6";
		}
		else if (isPartner == 'Emmi'){
			s.eVar24 = filterVar($("hiddeneVar24").value);
			s.events += ",event6";
			s.linkTrackVars += ",eVar24";
			s.linkTrackEvents += ",event6";
		}

		s.tl(true,'o','Partnership Exit');
	} else {
		s.prop25 = filterVar(stripHTML(inner));
		s.prop26 = filterVar(href);
		s.linkTrackVars = "prop25,prop26,prop50,eVar3,eVar50,channel,pageName,server,hier3";
		s.tl(true,'o','Exit Link');
	}
}

var siteCatalystFiles = function(title,filename,url){
	
	s=s_gi(s_account);
	var thetitle=filterVar(title);
	s.prop27 = thetitle + ' - ' + filterVar(filename);
	s.prop28 = filterVar(url);
	if (url.indexOf('resource_center') > -1 || url.indexOf('resource_library') > -1) 
		s.prop18 =  thetitle;
	s.linkTrackVars = "prop18,prop27,prop28,prop35,prop50,eVar3,eVar50,channel,pageName,server,hier3";
	s.tl(true,'o','File Download');
	s.prop27 = "";
	s.prop28 = "";
	return true;
}

var videoNames = { 'adjustments_4_lapband.flv':'Getting LAP-BANDŽ System Adjustments',
					'choosing_a_surgeon_4_lapband.flv':'Choosing a LAP-BANDŽ Surgeon',
					'day_of_surgery_5_lapband.flv':'What to Expect: Day of Surgery',
					'first_few_weeks_diet_3_lapband.flv':'First few weeks: Diet',
					'first_few_weeks_recovery_lapband.flv':'Your First Few Weeks: Recovering from LAP-BANDŽ Surgery',
					'support_at_home_3_lapband.flv':'Support at Home',
					'support_in_the_community_3_lapband.flv':'Support in the Community',
					'green_zone_3_lapband.flv':'Understanding the Green Zone',
					'insurance_financing_3_lapband.flv':'LAP-BANDŽ Cost and Insurance',
					'history_3_lapband.flv':'The History of the LAP-BANDŽ System',
					'system_advantages4_lapband.flv':'LAP-BANDŽ System Advantages',
					'lap_band_system_safety4_lapband.flv':'Understanding LAP-BANDŽ Risks',
					'life_after_lap-band_5_lapband.flv':'Living with the LAP-BANDŽ System',
					'my_moment_of_truth_4_lapband.flv':'My Moment of Truth',
					'obesity_comorbidalities_lapband.flv':'Obesity and Your Health',
					'overcoming obstacles_lapband.flv':'Overcoming Obstacles',
					'changes_final.flv':'Changes',
					'in_the_spotlight_final.flv':'In the Spotlight',
					'lapband_infuse.flv':'LAP-BAND System Animation - InFuse',
					'seminar_final_lapband.flv':'benefits of a seminar'};


var siteCatalystVidStart = function(pathname) {
	setTimeout(function() {
		var file = filterVar(getFileName(pathname));
		s = s_gi(s_account);
		s.events = "event44";
		try
		{
			s.eVar9 = filterVar(videoNames[file]);	
		}
		catch (e) //the filename is not in the videoNames hash, use the filename
		{
			s.eVar9 = file;
		}
		s.linkTrackVars = "prop50,eVar3,eVar9,eVar50,channel,events,pageName,server,hier3";
		s.linkTrackEvents = "event44";
		s.tl(true,'o','Video Start');
	}, 1000);
}

var siteCatalystVidEnd = function(pathname) {
	var file = filterVar(getFileName(pathname));
	s=s_gi(s_account);
	s.events = "event45";
	try
	{
		s.eVar9 = filterVar(videoNames[file]);	
	}
	catch (e) //the filename is not in the videoNames hash, use the filename
	{
		s.eVar9 = file;
	}
	s.linkTrackVars = "prop50,eVar3,eVar9,eVar50,channel,events,pageName,server,hier3";
	s.linkTrackEvents = "event45";
	s.tl(true,'o','Video End');
}

var siteCatalystTipExpand = function() {
	var ele = $('tooltiptoggle');
	var tiptitle = ele.up().previous('.tiptitle').innerHTML;
	s=s_gi(s_account);
	s.prop33 = filterVar(stripHTML(tiptitle));
	s.linkTrackVars = "prop33,prop50,eVar3,eVar50,channel,pageName,server,hier3";
	s.tl(true,'o','Tip Expand');
}

var siteCatalystFAQ = function(ele) {
	var linktitle = stripHTML(ele.innerHTML);
	s=s_gi(s_account);
	s.prop34 = filterVar(linktitle);
	s.linkTrackVars = "prop34,prop50,eVar3,eVar50,channel,pageName,server,hier3";
	s.tl(true,'o','FAQ Click');
}


// This function will ajax an action on the sitecatalyst controll
// which will return a snipped of javascript populated with all of the sitecatalyst
// variables and events which may have been populated on the server side, and create a linktrack event.
// This is plugged into the Modal.close() action.
var siteCatalystFireServerSideVars = function(actionname) {
	s=s_gi(s_account);
	s.events = "";
	new Ajax.Request(siteroot + 'elements/layout_items/sitecatalyst/getscdata', {
			method: 'get',
			asynchronous: false
			}
	);

	s.prop50 = filterVar(location.pathname + location.search);   //path and querystring without servername
	s.eVar50 = filterVar(location.pathname + location.search);

	s.tl(true,'o',actionname || 'Modal Action');
}


var getModalPageName = function(url) {
	var returnurl = url.replace(/\/elements\/modals\//, ''); // remove un-needed paths
	returnurl = returnurl.replace(/\/elements\/widgets\//, '');
	//returnurl = returnurl.replace(/\/en\/sign_in\/(.+)$/, '$1');
	returnurl = returnurl.replace(/[?].*$/, ''); // remove query string
	returnurl = returnurl.replace(/index\/?/, '');  // remove index action
	returnurl = returnurl.replace(/\/[0-9]+$/, '/'); // remove action data
	returnurl = returnurl.replace(/(^[^\/])/, '/$1'); // make sure it starts with a slash 
	return  filterVar(returnurl);
}
// used specifically for modals
var siteCatalystFirePageView = function(url, sfunc, isNotModal) {

	s=s_gi(s_account);
	if(isNotModal){
		s.pageName = getModalPageName(url);
		s.hier3 = s.pageName.replace(/\//g, ',').replace(/,$/,'').replace(/^,/,'');
		s.channel = s.hier3.replace(/en,/, '').replace(/,.*$/, '');
	}else{
		s.pageName = "Modals:" +  getModalPageName(url);
		s.hier3 = "Modals";
		s.channel = "Modals";
	}

	s.events = "event80";
	// reset evars which were set in the parent page
	var evars_we_want = $A([3, 4, 47, 48, 49, 50]);
	$R(1,50).each(function(n){ // we only go up to 46, 47-50 we want to keep
			if(evars_we_want.indexOf(n) < 0){ 
				eval('s.eVar' + n + ' = "";');
			}
		});	

	// reset props which were set in the parent page
	var props_we_want = $A([50]);
	$R(1,50).each(function(n){ // we only go up to 46, 47-50 we want to keep
			if(props_we_want.indexOf(n) < 0){ 
				eval('s.prop' + n + ' = "";');
			}
		});	

	// the following ajax call will return javascript which will get evaluated setting events etc.
	new Ajax.Request(siteroot + 'elements/layout_items/sitecatalyst/getscdata', {
			method: 'get',
			asynchronous: false
			}
	);

	// PAGENAMING STUFF
	// see if a page suffix was set, of so, set it
	// this is for unique page naming
	s.pageName = s.pageName += s.pagenamesuffix;

	if(!isNotModal){ // this IS a modal
		// look for validation errors, this should catch most cases
		var errors = $$('#modalcontent .fielderror');
		var errors2 = $$('#modalcontent .error');
		var errors3 = $$('#modalcontent .showerror');
		var errors4 = $$('#modalcontent .validate-summary');
		if (errors4.length==0)
			errors4 = $$('#validate-summary'); //stupid hack for IE.
		var errors5 = $$('#modalcontent2 .showerror');  //this is for the server side error messages on the setup modals
		if(errors.length > 0 || errors2.length > 0 || errors3.length > 0 || errors4.length > 0 || errors5.length > 0 ){
			s.pageName = s.pageName + "_validationerror";
			s.hier3 = "validationerror";
			s.channel = "validationerror";
		}
	}

	// now normalize pagename
	s.pageName = s.pageName.replace(/\/_/, '_');
	if(s.pageName.match(/[^\/]$/))
			s.pageName += '/';


	if(sfunc)
		sfunc(s);

	s.t();
}

//
// This is even crazier then the above action...
// This will override Ajax.Updater so that if you are ajaxing to modalcontent, we will create a pageview.
Ajax.Updater = Class.create(Ajax.Updater, {
  initialize: function($super,  container, url, options) {

	  if(container.match(/(modalcontent|modalcontent2|callbackdiv|callback|WidgetsRecipeDiv)/)){
			options = Object.clone(options);
			var onComplete = options.onComplete;
			options.onComplete = (function(response, json) {
				// if we get redirected on the server side, our actual url might not be the url we asked for.
				// We can override this on the server side byt setting a custom header called RedirectedUrl which
				// will be picked up here.
				var redirectedurl = response.getHeader("RedirectedUrl");
			  siteCatalystFirePageView(redirectedurl || url);
			  if (Object.isFunction(onComplete)) onComplete(response, json);
			}).bind(this);
	  }
	  $super(container, url,  options);
  }
});

