﻿var userAgent = navigator.userAgent.toLowerCase();
var Acceller =
{
    ApplicationName: "DLWA",
    TransactionID: 0,
	secureOrder: false, //set by BasePage.cs
	_pageName:null,
	getPageName: function()
	{
		if(!Acceller._pageName)
		{
			var endIdx = Math.min(location.href.lastIndexOf(location.search), location.href.lastIndexOf(location.hash))
			Acceller._pageName = location.href.substring(location.href.indexOf(location.pathname, 8)+1, endIdx).toLowerCase();
		}
		return Acceller._pageName; 
	},
	
	isPage: function(pageName)
	{
		return (Acceller.getPageName() == pageName.toLowerCase());
	},
	
	DetectXsltSupport: function()
	{
		try
		{
			var x = new XSLTProcessor();
		}
		catch(ex)
		{
		}
		
		if(x)
			 return true;
		else
			return false;
	},

	isFirefox: userAgent.include("firefox"),
	
	isIE8: userAgent.include("msie 8"),
	isIE7: userAgent.include("msie 7"),
	isIE6: userAgent.include("msie 6"),
	isIE: Prototype.Browser.IE,
	
	Alert: function(msg, options)
	{
		var alrt = new AccellerAlert(msg);
		alrt.Modal = true;
		alrt.Height = 150;
		if(options)
		{
			if(options.ok)
			{
				alrt.observe("ok", options.ok);
				delete options.ok;
			}
			if(options.cancel)
			{
				alrt.observe("cancel", options.cancel);
				delete options.cancel;
			}
		}
				
		Object.extend(alrt, options || {});
		alrt.Show();
		
		return alrt;
	},
	
	UnloadListener:
	{
		doUnload: true,
		HandlePageUnload: function()
		{
			//alert("doUnload: " + Acceller.UnloadListener.doUnload);
			if(Acceller.UnloadListener.doUnload)
				Acceller.UnloadListener.notify("unload");
			
			Acceller.UnloadListener.doUnload = true;
		},
		
		HandlePageClick: function(e)
		{
			var el = e.findElement('a');
			//alert("element: " + e.element());
			Acceller.UnloadListener.doUnload = (!el || el.href.include(".aspx"));
		}

	},
		
	AddUnloadListener: function(f)
	{
		Acceller.UnloadListener.observe("unload", f);
	},
	
	Loaded: false,
	LoadListener: function()
	{
		Acceller.Loaded = true;
		
	}
};
//from livepipe.js
if(typeof(Object.Event.extend) != 'undefined')
	Object.Event.extend(Acceller.UnloadListener);

Event.observe(window, "load", Acceller.LoadListener);
if(Prototype.Browser.Webkit)
	Event.observe(window, "unload", Acceller.UnloadListener.HandlePageUnload);
else
	Event.observe(window, "beforeunload", Acceller.UnloadListener.HandlePageUnload);
if(Prototype.Browser.IE)
	Event.observe(document, 'click', Acceller.UnloadListener.HandlePageClick);

///////////Basic UI Effects///////////
//Expand div element indicated by id.
function Expand( id, queue, options )
{
	try 
	{
		var opts = Object.extend({ scaleContent:false,scaleFromCenter:false,scaleTo:100,duration:0.3 }, (options || {}));
		if(queue)
			opts.queue = 'end';
		return new Effect.SlideDown( id, opts );
	}
	catch (e) {}
}

//Collapses div element indicated by id. 
function Collapse( id, queue, options )

{
	try 
	{
		var opts = Object.extend({ scaleContent:false,scaleFromCenter:false,scaleTo:0,duration:0.5 }, (options || {}));
		if(queue)
			opts.queue = 'end'
		return new Effect.SlideUp( id,  opts); 
	}
	catch (e) {}
}

//Highlights div element indicated by id.
function Highlight( id, queue, duration, options )
{
	try  
	{
		var opts = Object.extend({ startcolor:'#ffffdb', endcolor:'#ffffff', restorecolor:'#ffffff' },
						options || {});
		if(queue)
			opts.queue = 'end';
		if(duration)
			opts.duration = duration;
		new Effect.Highlight( id, opts );
	}
	catch( e ) {}
}

// Displays the wait indicator.   
function DisplayWait()
{
	var divWait = $('divWait');
	if(divWait)
	{
		if(navigator.userAgent.toLowerCase().indexOf("msie 6") != -1)
		{
			divWait.style.position = "absolute";
			divWait.style.top = (document.body.parentNode.scrollTop + 200) + "px";
		}
		
		divWait.style.zIndex = 200;
		divWait.style.display = "block";
	}
}

// Hides the wait indicator. 
function HideWait()
{
	var divWait = $('divWait');
	if(divWait) divWait.style.display = "none";
}

////////////////////////////////////////////////Event Handling////////////////////////////////////////////////
/*
function OnError( ajaxResponse )
{
	var error = ajaxResponse.Error;
	
	if( showAjaxErrors )
		alert( error.Message + "\n" + error.Type + "\n" + error.StackTrace );
}


function OnPreRequest( ajaxRequest )
{
	DisplayWait();
}

function OnPostRequest( ajaxRequest )
{
// ASK AARON ABOUT THIS.
//	if(!ajaxRequest.Asynchronous)
//		HideWait();
}

function OnPreCallback( ajaxResponse )
{
	HideWait();
}
*/
///////////Litebox Calls///////////
var DETAILS_LINK_TYPE =
{
	OfferNameLink:1,
	SelectedOfferNameLink:2,
	OfferDetailLink:3,
	SelectedOfferDetailLink:4,
	BonusDetailLink:5,
	SelectedBonusDetailLink:6,
	OfferFeaturesLink:7,
	BonusFeaturesLink:8,
	BuyflowOfferLink:9,
	OfferQuickView: 10,
	AtAGlancePriceLink: 11,
	BonusLogo: 12,
	OrderingInstructions: 13,
	AtAGlanceBonusLink: 14
}
////////////////////////////////////////////////Light box////////////////////////////////////////////////////
var box = null;

var Lightbox = Class.create(
{
	initialize: function(id)
	{
		this.id = id;

		this.Top = 80;
		this.Left = 40;
		this.Width = 400;
		this.Height = 225;
		this.Shadow = true;
		this.Modal = true;
		this.Draggable = false;
		this.InnerHTML = "";
		this.Overflow = "auto";
		this.Background = "#FFFFFF";
		this.Content = "Details";
		this.offsetX = 0;
		this.offsetY = 0;
		this.Scroll = false;
		this.ClassName = "";
		
		this.includeClose = true;
		this.includePrint = true;

		this.messageBox = null;
		this.mask = null;
		this.onClose = null;
		this.inited = false;
		
		this.Fix = this.FixPosition.bind(this);
		this.Unfix = this.UnfixPosition.bind(this);	
	},
		
	Init: function()
	{
		if(!this.inited)
		{
			this.InnerHTML = '<div style="text-align:center;"><img src="images/ajax-loader.gif" /><br />Loading...</div>';
			var bodyWidth = document.viewport.getWidth();
			this.offsetX = Math.floor(((bodyWidth/2)-(this.Width/2)));
			var windowHeight = document.viewport.getHeight();
			this.Height = Math.min((windowHeight*0.9), this.Height); //constrain to no taller than 90% of viewport
			
			if(this.Top == "middle" || this.Top == "center")
				this.offsetY = Math.floor((windowHeight/2)-(this.Height/2));
			else
				this.offsetY = this.Top;

			//create elements
			this.messageBox = this.createMessageBox();
			
			var viewportOffsets = document.viewport.getScrollOffsets();
			var top = viewportOffsets.top + this.offsetY;
			var left = (viewportOffsets.left + this.offsetX);
			
			var ondrag = this.dragHandler.bind(this);
			this.win = new Control.Window(this.messageBox, { draggable: this.navBar, onDrag: ondrag, position: [left, top], iframeshim: Prototype.Browser.IE, constrainToViewport: true });
			
			if(this.Modal)
			{
				this.win.observe("onInitDrag", this.Unfix);
				this.mask = this.createOverlay();
			}
			
			this.inited = true;
		}
	},
	
	dragHandler: function()
	{
		var osets = this.win.container.viewportOffset();
		this.offsetY = osets.top;
		this.offsetX = osets.left;		
	},
		
	createOverlay: function()
	{
		var overlay = new Element('div');
		overlay.className = "lightbox-modal-overlay";
		overlay.id = 'light' + this.id;
		overlay.style.height = document.body.getHeight() + "px";
		overlay.style.width = document.body.getWidth() + "px";
		overlay.style.top = "0px";
		overlay.style.left = "0px";
		overlay.style.display = "none";

		return overlay;
	},
	
	createMessageBox: function()
	{
		var messageBox = new Element('div');
		messageBox.id = "messageBox" + this.id;
		messageBox.className = "lightbox";
		messageBox.style.backgroundColor = this.Background;
		messageBox.style.display = "none";
		if(this.Shadow)
			messageBox.addClassName("lightboxshadow");
		if(this.ClassName)
			messageBox.addClassName(this.ClassName);

		var nav = new Element("div");
		nav.className = "lightbox-titlebar"
		messageBox.insert(nav);
		
		this.navBar = nav;
		
		if(this.includeClose)
		{
			var closeBtn = new Element("div");
			closeBtn.className = "lightbox-close-btn lightbox-nav-btn"
			Event.observe(closeBtn, "click", this.Close.bind(this));
			closeBtn.innerHTML = '<img src="images/icon-close.gif" width="14" align="absmiddle" height="13" border="0" />Close Window'
			nav.insert(closeBtn);
		}
		
		if(this.includePrint)
		{
			var printBtn = new Element("div");
			printBtn.className = "lightbox-print-btn lightbox-nav-btn"
			printBtn.id = "print_link";
			printBtn.innerHTML = '<img src="images/icon-print.gif" border="0" align="absmiddle" /> Print Page';
			nav.insert(printBtn);
		}
					
		var content = new Element("div");
		content.className = "lightbox-content";
		if(this.Scroll)
			content.style.overflow = "auto";
		this.contentDiv = content;
		messageBox.insert(content);	
		
		return messageBox;
		
	},
		
	ShowMask: function()
	{
		if( this.Modal )
		{
			this.scrollHandler = this.handleScroll.bind(this);
			Event.observe(window, 'scroll', this.scrollHandler);
		}
	},
	
	handleScroll: function()
	{
		this.EnsurePosition();
	},
		
	ShowMessageBox: function()
	{
			var fx = [];	
			var opts = { duration: 0.4 };	
	        
			opts.afterFinish = this.FinishShowMessageBox.bind(this);
			
			this.messageBox.style.height = this.Height + ((this.Height=='auto')?"":"px");
			this.messageBox.style.width = this.Width + "px";
			
			//adjust content height
			if(this.Scroll)
			{
				var navPT = parseInt(this.navBar.getStyle("paddingTop")) || 0;
				var navPB = parseInt(this.navBar.getStyle("paddingBottom")) || 0;
				var navHT = parseInt(this.navBar.getStyle("height")) || 0;
				var ctPT = parseInt(this.contentDiv.getStyle("paddingTop")) || 0;
				var ctPB = parseInt(this.contentDiv.getStyle("paddingBottom")) || 0;
				var pad = navPT + navPB + navHT + ctPT + ctPB + 2;
				this.contentDiv.style.height = (this.Height - pad) + "px";
			}
			
			this.win.open();
			this.win.updateIFrameShimZIndex();
					        
			if(this.mask)
			{
				fx.push(new Effect.Appear( this.mask, { sync: true, from: 0.0, to: 0.5 }));			
			}
	    
			this.openFX = new Effect.Parallel(fx, opts);
			this.Update();
				
	},
		
	FinishShowMessageBox: function()
	{
		this.openFX = null;
			
		if(this.autoSize)
			this.AutoSize();
		else if(this.Modal)
			this.FixPosition();
			
		this.notify("open");
	},
		
	AutoSize: function()
	{
		try
		{
			if(this.openFX) // || !this.InnerHTML)
			{
				return false;
			}
			
			var fx = [];
			
			var content = this.contentDiv.childElements()[0];
			var contentHeight = content.getHeight();
			
			var margins = (parseInt(this.contentDiv.getStyle("paddingTop")) || 0) + (parseInt(this.contentDiv.getStyle("paddingBottom")) || 0);
			contentHeight += margins;
			if(Acceller.isIE7) //hack for IE7
				contentHeight += 25;

			var navPT = parseInt(this.navBar.getStyle("paddingTop")) || 0;
			var navPB = parseInt(this.navBar.getStyle("paddingBottom")) || 0;
			var navHT = parseInt(this.navBar.getStyle("height")) || 0;
			var navHeight = navPT + navPB + navHT;
			
			var totalHeight = contentHeight + navHeight;

			//check height of window, do not exceed
			if(this.Top == "middle" || this.Top == "center")
			{
				var dimensions = document.viewport.getDimensions();
				var windowHeight = dimensions.height;
				var scrollOffsets = document.viewport.getScrollOffsets();
				var offsetTop = scrollOffsets.top;
				var maxHeight = Math.floor(windowHeight * 0.9); //90% of window height

				if(totalHeight > maxHeight)
				{
					totalHeight = maxHeight;
					contentHeight = maxHeight - navHeight - margins - 2;
					this.contentDiv.style.overflow = "auto";
				}
				

				var oy = Math.floor((windowHeight - totalHeight)/2) + offsetTop;
				this.offsetY = oy - offsetTop;
				if(oy < 0) oy = 0;
				var ox = this.messageBox.cumulativeOffset().left;
				this.offsetX = ox;
				fx.push(new Effect.Move(this.messageBox, { sync: true, y: oy, x: ox, mode: 'absolute' }));
			}
			
			if(this.win.iFrameShim)
			{
				this.win.iFrameShim.element.style.height = totalHeight + "px";
			}
			this.contentDiv.style.height = contentHeight + "px";
			this.messageBox.style.height = totalHeight + "px";
			
			
			var pct = Math.floor((totalHeight/this.messageBox.getHeight())*100);
			var w = this.win;
			var afterUpdate = this.win.iFrameShim?function() { w.updateIFrameShimZIndex(); }:Prototype.emptyFunction;
			fx.push(new Effect.Scale(this.messageBox, pct, {sync: true, scaleX: false, scaleFromCenter: false, scaleContent: false, afterUpdate: afterUpdate}));
			
			var opts = { duration: 0.3 };
			opts.afterFinish = this.FinishAutoSize.bind(this);
			this.FinishAutoSize();
			
			if(this.scaleFX) this.scaleFX.cancel();
			
			//this.scaleFX = new Effect.Parallel(fx, opts);
		}
		catch (ex)
		{
			//alert(ex.message);
		}
		
		return true;
	},
		
	FinishAutoSize: function()
	{
		this.scaleFX = null;
		
		if(this.Modal)
			this.FixPosition();
	},
	
	FixPosition: function()
	{
		if(!Acceller.isIE6)
		{
			this.messageBox.setStyle({position: "fixed", top: this.offsetY + "px", left: this.offsetX + "px"});
			
			Event.stopObserving(document, "mouseup", this.Fix);
		}
	},
	
	UnfixPosition: function()
	{
		if(!Acceller.isIE6)
		{
			var osets = document.viewport.getScrollOffsets();
			var t = this.offsetY + osets.top;
			var l = this.offsetX + osets.left;
			this.messageBox.setStyle({position: "absolute", top: t+"px", left: l+"px" });
			
			Event.observe(document, "mouseup", this.Fix);
		}
	},
		
	EnsurePosition: function()
	{
		if(Acceller.isIE6)
		{
			var offsets = document.viewport.getScrollOffsets()
			var top = offsets.top;
			var left = offsets.left;

			var styles = { top: (this.offsetY + top)+"px", left: (this.offsetX+left)+"px" };	
			
			this.messageBox.setStyle(styles);
			if(this.win.iFrameShim)
			{
				this.win.iFrameShim.element.setStyle(styles);
			}
		}		
	},
		
	Show: function()
	{
		this.Init();
		if(!this.open) this.Open();
		
		this.EnsurePosition();
		
		this.ShowMask();
		this.ShowMessageBox();
	},
		
	Close: function()
	{
		try
		{
			if(!this.open) return; 
			
			if( this.messageBox)
			{
				this.win.close();
				document.body.removeChild( this.messageBox );
				Acceller.UnloadListener.doUnload = false;
			}
			
			if( this.mask ) 
			{
				this.mask.style.display = "none";
				document.body.removeChild( this.mask );
			}
			
		
			this.open = false;

			if(this.Modal)
				Event.stopObserving(window, 'scroll', this.scrollHandler);
			this.scrollReverter = null;
			
			if(this.onClose)
				this.onClose(this);
				
			this.notify("close");
			
		}
		catch(ex){}
	},
		
	Open: function()
	{
		if(this.messageBox) document.body.appendChild(this.messageBox);
		if(this.mask) document.body.appendChild(this.mask);
		this.open = true;
	},
		
	Update: function()
	{
		if(this.InnerHTML)
		{
			this.contentDiv.innerHTML = this.InnerHTML;
			
			if(this.autoSize)
				window.setTimeout(this.AutoSize.bind(this), 50);
		}
	},
	
	clear: function()
	{
		if(this.contentDiv)
			this.contentDiv.innerHTML = "";
		this.InnerHTML = "";
	},

	appendChild: function(element)
	{
		this.contentDiv.insert(element);
		element.style.display = "";
		
		if(this.autoSize)
			this.AutoSize();
	}
});
//from livepipe.js
if(typeof(Object.Event.extend) != 'undefined')
	Object.Event.extend(Lightbox);

var AccellerAlert = Class.create(Lightbox,
{
	initialize: function($super, messages)
	{
		$super('Alert');
		if(typeof(messages) == 'string')
			this.messages = [messages];
		else
			this.messages = messages;
		this.showOkBtn = true;
		this.showCancelBtn = false;
		this.Height = 200;
		this.Width = 400;
		this.Top = "middle";
		this.Modal = false;
		this.Shadow = true;
		this.Content = 'Alert';
		this.includeClose = false;
		this.includePrint = false;
		this.CancelButtonText = "Cancel";
		this.OkButtonText = "OK";
		
		this.HandleKeys = this.KeyObserver.bindAsEventListener(this);
	},
	
	Show: function($super)
	{
		if(AccellerAlert.current)
		{
			AccellerAlert.queue.push(this);
			return;
		}
		
		$super();
	
		this.clear();
		
		this.autoSize = false;
		var div = new Element("div");
		var iterator = this.BuildMessage;
		this.messages.each(function(msg) { div.insert(iterator(msg)) });
		this.messageDiv = div;
		this.appendChild(div);
		
		var btndiv = new Element("div");
		this.btnDiv = btndiv;
		btndiv.setStyle({ textAlign: "center",height: "20px", width: "100%"});
		if(this.showOkBtn)
		{
			var okbtn = new Element("input");
			okbtn.type = "button";
			okbtn.value = this.OkButtonText;
			okbtn.style.width = "150px";
			okbtn.observe('click', this.OnOk.bindAsEventListener(this));
			btndiv.insert(okbtn);
		}
		if(this.showCancelBtn)
		{
			var cancelbtn = new Element("input")
			cancelbtn.type = "button";
			cancelbtn.value = this.CancelButtonText;
			cancelbtn.style.width = "150px";
			cancelbtn.observe('click', this.OnCancel.bindAsEventListener(this));
			btndiv.insert(cancelbtn);
		}
		
		Event.observe(document, 'keypress', this.HandleKeys);
				
		div.insert(btndiv);
		
		AccellerAlert.current = this;
		
		this.autoSize = true;
		
		this.AutoSize();
	},

	Close: function($super)
	{
		$super();
		this.messageDiv = null;
		this.btnDiv = null;
		AccellerAlert.current = null;
		
		Event.stopObserving(document, 'keypress', this.HandleKeys);
		
		if(AccellerAlert.queue.length)
		{
			var next = AccellerAlert.queue.shift();
			next.Show();
		}
	},
		
	OnOk: function()
	{
		this.Close();
		this.notify('ok');
	},

	OnCancel: function()
	{
		this.Close();
		this.notify('cancel');
	},

		
	BuildMessage: function(message)
	{
		var div = new Element("div");
		div.className = "blue_contain";
		div.insert("<div class=\"blue_contain_top\"><div class=\"tl blue_contain_corner\"></div><div class=\"tr blue_contain_corner\"></div></div>" +
			"<div class=\"blue_contain_body\"><img src=\"/images/searchpanelerror-ex.gif\" style=\"float:left;\" /></div>" +
			"<div class=\"MessageControlText\">" + message + "</div></div>" +
			"<div class=\"blue_contain_bottom\"><div class=\"bl blue_contain_corner\"></div><div class=\"br blue_contain_corner\"></div></div>")
			
		return div;

	},
	
	KeyObserver: function(e)
	{
		var keyCode = e.keyCode || e.which;
		if(keyCode == 13 && this.showOkBtn)
		{
			this.OnOk();
		}
		else if(keyCode == 27)
		{
			if(this.showCancelBtn)
				this.OnCancel();
			else if(this.showOkBtn)
				this.OnOk();
		}
		
	}
	
});
//from livepipe.js
if(typeof(Object.Event.extend) != 'undefined')
	Object.Event.extend(AccellerAlert);	

AccellerAlert.queue = [];
AccellerAlert.current = null;

////////////////////////////////////////////////Global Functions////////////////////////////////////////////////////

var OPERATION_CODE =
{
	NoOffersAvailable:2,
	IncompleteInformation:4,
	OfferIncompatible:8,
	OneClickSuccess:16,
	OneClickFailure:32
}

//Open the print page and display the selected offer details.
function PrintDetailEvent(offerID)
{
    box.Close();
    window.open('Print.aspx?type=details&id=' + offerID);
}

//Open the print page and display the selected learning center article.
function PrintArticleEvent(article)
{
    box.Close();
    window.open('Print.aspx?type=article&issue=' + article);
}

//Open the print page and display the selected company information.
function PrintInfoEvent( article )
{
	box.Close();
    window.open('Print.aspx?type=info&page=' + article);
}

var NotMyAddressClickID =
{
	NotMyAddress:1,
	StartOver: 2
}

var NotMyAddressBox = null;
function NotMyAddressEvent( clickID )
{
	if(SearchPanelControl.Instance)
		SearchPanelControl.Instance.Show(clickID);
}

function SearchPanelControl(address, phone, ddlStateID)
{
	this.id = 'searchPanelControlDiv';
	if (address)
	{
	    this.address = address.AddressLine1 || "";
	    this.apt = address.Unit || "";
	    this.city = address.City || "";
	    this.state = address.State || "";
	    this.zip = address.ZipCode || "";
	}
	if (phone)
	{
	    this.area = phone.AreaCode || "";
	    this.prefix = phone.Exchange || "";
	    this.suffix = phone.Station || "";
	}
	
	this.ddlStateID = ddlStateID;
	
	this.box = null;
}

SearchPanelControl.Instance = null;

SearchPanelControl.prototype.Show =
function(clickID)
{
	this.Init();
	
    var el = $(this.id);
	if(el)
	{
		el.remove();
		this.box.clear();
		this.box.appendChild(el);
    }
	
	box = this.box;
	box.messageBox.style.height = "0px";
	box.messageBox.style.width = "0px";
	box.Show();
	
	$('addressInput').setValue(this.address);
	$('apartmentInput').setValue(this.apt);
	$('cityInput').setValue(this.city);
	$(this.ddlStateID).setValue(this.state);
	$('zipCodeInput').setValue(this.zip);
	$('areaInput').setValue(this.area);
	$('prefixInput').setValue(this.prefix);
	$('suffixInput').setValue(this.suffix);
	
    var activity = new Activity(ActivityManager.ActivityType.NotMyAddress);
	activity.ClickID = clickID;
	ActivityManager.Instance.LogActivity(activity);
}

SearchPanelControl.prototype.Init =
function()
{
	if(this.inited) return;
	var NotMyAddressBox = new Lightbox('AddressBox1')
	NotMyAddressBox.Width = 320; 
	NotMyAddressBox.Height = 300;
	NotMyAddressBox.Modal = true;
	NotMyAddressBox.Shadow = false;
	NotMyAddressBox.Content = "Default";
	NotMyAddressBox.includePrint = false;
	NotMyAddressBox.Init();
	NotMyAddressBox.Open();

	this.box = NotMyAddressBox;
	var div = $("searchPanelControlDiv");
	Event.observe(div, "keypress", this.handleKeyPress.bindAsEventListener(this));
	Event.observe($('areaInput'), "paste", this.handlePaste.bind(this));
	this.inited = true;
}

SearchPanelControl.prototype.handlePaste =
function(e)
{
	var input = $("areaInput");
	input.value = "";
	input.maxLength = 100;
	this.processPaste.defer();
}

SearchPanelControl.prototype.processPaste =
function()
{
	var area = $("areaInput");
	
	var num = area.value.replace(/\D/g, "");
	
	if(num.length >= 3)
		area.value = num.substr(0, 3);
	if(num.length > 3)
	{
		var prefix = $("prefixInput");
		prefix.value = num.substr(3, 3);
	}
	if(num.length > 6)
	{
		var suffix = $("suffixInput");
		suffix.value = num.substr(6,4);
	}
	
	area.maxLength = 3;
}

SearchPanelControl.prototype.handleKeyPress =
function(e)
{
   var keyCode = e.keyCode || e.which;
   if(keyCode==13)
   {
      SubmitAddress();
   }
}

var Articles = new Hash();

function ArticleEvent( file, isCompanyInfo )
{
	if( box != null )
		box.Close();
	
	chosenArticle = file;
    box = new Lightbox('article1');
    box.Left = 25;
    box.Height = 602;
    box.Width = 701;
    box.Modal = true;
    box.Shadow = true;
    box.Draggable = true;
    box.Scroll = true;
    box.Shadow = true;
    box.Show();
    if(isCompanyInfo)
		Event.observe( $('print_link'), 'click', PrintInfoEvent.bind(window, file) );
	else
	    Event.observe( $('print_link'), 'click', PrintArticleEvent.bind(window, file) );
    
    var article = Articles.get(file);
    if(article)
    {
		box.InnerHTML = article;
		box.Update();
    }
    else
    {

		var src;
		if(isCompanyInfo)
			src = "/dynamiccontent/supplemental/" + file;
		else
			src = "/dynamiccontent/articles/" + file;
		
		var callback = RenderArticleCallback.curry(file);
		AjaxManager.Call(null, null, callback, { Method: "get", ResponseType: AjaxManager.ResponseType.Literal, onSuccess: callback, onFailure: RenderArticleFailure, CallbackPage: src});
		
	}

	if(!isCompanyInfo)
	{
		var activity = new Activity(ActivityManager.ActivityType.LearningCenter);
		activity.ArticleFile = file;
		ActivityManager.Instance.LogActivity(activity);
	}
}

function RenderArticleCallback(file, response){	
	if(response)
	{
		Articles.set(file, response);
		box.InnerHTML = response;
		box.Update();
	}
}

function RenderArticleFailure(ajaxResponse)
{
	box.InnerHTML = "An error has occurred";
	
	box.Update();
}

function CompanyInfoEvent( file )
{
	ArticleEvent(file, true);
}

var MSSCtrlModes =
{
	Summary:1,
	Details:2
}


function MySelectionSummaryControl(id, mode)
{
	this.id = id;
	this.mode = mode;
	this.bundleProviders = new Array();
	
	Event.observe(window, "load", this.FixNames.bind(this));
}

MySelectionSummaryControl.Instance = null;

MySelectionSummaryControl.prototype.Update =
function(html)
{
	var mySelectionSummaryDiv = $("offer_builder");
	if( mySelectionSummaryDiv )
		mySelectionSummaryDiv.innerHTML = html;
}

MySelectionSummaryControl.prototype.showBundles =
function()
{
	if(this.bundleProviders.length == 0) return;
	
	var pc = PersonalizationControl.Instance;
	if(pc.mode == OfferManager.DisplayMode.Provider)
	{
		var categoryID;
		if(this.bundleProviders.length)
			categoryID = OfferManager.Instance().Categories.get(this.bundleProviders[0]);
		if(categoryID)
		{
			//if(pc.filterChbx.values().without(false).length != 0 && !pc.filterChbx.get(category.ID))
			if(!pc.IsFiltered(categoryID))
			{
				pc.observeOnce("updated", this.AutoFilter.bind(this, categoryID));
				pc.ClearFilters();
				
			}
			else
				this.AutoFilter(categoryID);
				//category.Open(category.AutoFilter.bind(category,"Bundle_DoublePlay,Bundle_TriplePlay,Bundle_QuadPlay"));
		}
	}
	else
	{
		var category = OfferManager.Instance().Categories.get(OfferManager.DisplayCategories.Bundle);
		if(category)
		{
			category.observeOnce("onopen", category.ScrollIntoView.bind(category, true));
			// GEMINI DL-11002 - clear filters before jumping to bundles
			pc.ClearFilters();
			category.Open();
		}
	}
	
	var activity = new Activity(ActivityManager.ActivityType.BundleLink);
	ActivityManager.Instance.LogActivity(activity);
}

MySelectionSummaryControl.prototype.AutoFilter =
function(category)
{
	category.ScrollIntoView(true);
	category.observeOnce("onopen", category.AutoFilter.bind(category, "Bundle_DoublePlay,Bundle_TriplePlay,Bundle_QuadPlay", true, true));
	category.observeOnce("onopen", HideWait);
	DisplayWait();
	category.Open();
}

MySelectionSummaryControl.prototype.FixNames =
function()
{
	var mySelectionSummaryDiv =  $("MySelectionSummaryDiv");
		
	var nameDivs = mySelectionSummaryDiv.select(".offer-name");
	nameDivs.each(function(div)
		{
			var a = div.down("a");
			AddEllipsis(div, a, div.innerHTML, 'offer-name-tooltip', true);
		});
	
	if(Prototype.Browser.IE)
	{
		var providerLogos = mySelectionSummaryDiv.select(".offer-provider-logo img");	
		providerLogos.each(function(logo)
		{
			if(!logo.hasClassName("offer-provider-small-logo") && logo.height > 50)
			{
				logo.hide();
				logo.next().style.display = "block";
			}
		});
	}

}

function Lightbox_Callback( ajaxResponse )
{
    if( box != null )
    {
		if( !ajaxResponse.HasError )
		{
			box.InnerHTML = ajaxResponse.Output;
			box.Update();
		}
		else
		{
			box.InnerHTML = ACCELLER_AJAX_LIGHTBOX_ERROR;
			box.Update();
		}
    }
    else
		alert( ACCELLER_AJAX_LIGHTBOX_ERROR );
}


////////////////////////////////////////////////SearchPanelControl.ascx////////////////////////////////////////////////////
function NewPhoneTabOver( currentEvent, elementLength, nextElement )
{
	var element = Event.element(currentEvent);
	var chr = currentEvent.charCode || currentEvent.keyCode;

	if(chr == 9 || chr == 16) return; //ignore tab and shift key
	if( element.value.length == elementLength )
	{
    	var input = $(nextElement);
    	if (input != null) {
       	    input.focus();
	        if(input.type == "text" && input.select)
		        input.select();
		}
	}
}
function PhoneTabOver(e)
{
	var element = Event.element(e);
	var chr = e.charCode || e.keyCode;
	if(chr == 9 || chr == 16) return; //ignore tab and shift key
	switch( element.id )
	{
		case "areaInput" :
			if( element.value.length == 3 )
			{
				selectInput("prefixInput");
			}
			break;
		case "prefixInput":
			if( element.value.length == 3 )
			{
				selectInput("suffixInput");
			}
			break;
		case "suffixInput":
			if( element.value.length == 4 )
			{
				var emailPanel = $("emailPanel");
				if(emailPanel.style.display != "none")
					selectInput("emailInput");
				else
					selectInput("searchNowBtn");
			}
			break;
		default :
			break;
	}
}

function selectInput(inputID)
{
	var input = $(inputID);
	input.focus();
	if(input.select && input.type != "button")
		input.select();
}
    
 function SwapPanels()
 {
     if ( $("phone").style.display == "block" )
     {
         $("address").style.display = "block";
         $("phone").style.display = "none";
         $("swapLink").innerHTML = SEARCH_PANEL_USE_PHONE_TEXT;
     }
     else
     {
         $("address").style.display = "none";
         $("phone").style.display = "block";
         $("swapLink").innerHTML = SEARCH_PANEL_USE_ADDRESS_TEXT;
     }
 }
     
function IsValid()
{
	var valid = true;
	var phoneShowing = ($("phone").style.display == "block");
	var phoneValid = true;
	var addressShowing = ($("address").style.display == "block");
	var addressValid = true;
	var phone = $("areaInput").value + $("prefixInput").value + $("suffixInput").value;
	
	if(phoneShowing )
	{
		if(!IsPhoneValid(phone, !addressShowing))
		{
			$("phoneMarker").style.display = "inline";
			//valid = false;
			phoneValid = false;
			alert(GENERAL_INVALID_PHONE_NUMBER);
		}
	}
	
	if(phoneValid && addressShowing)
	{
		addressValid = addressValid && ValidateAddressField("address", IsAddressValid, !(phoneValid && phone != ""), GENERAL_INVALID_ADDRESS);
		addressValid = addressValid && ValidateAddressField("zipCode", IsZipValid, !(phoneValid && phone != ""), GENERAL_INVALID_ZIPCODE);
		
		
		addressValid = addressValid && ValidateAddressField("apartment", IsApartmentValid, false, SEARCH_PANEL_INVALID_APT, "apt");
		addressValid = addressValid && ValidateAddressField("city", IsCityValid, false, GENERAL_INVALID_CITY);
		
		var stateDDLID = $("stateDDLID");
		if(stateDDLID)
		{
			var stateDDL = $(stateDDLID.value);
			if(stateDDL)
			{
				if(!IsStateValid($F(stateDDL)), false)
				{
					$("stateMarker").style.display = "inline";
					addressValid = false;
					alert(GENERAL_INVALID_STATE);
				}
				else
				{
					$("stateMarker").style.display = "none";
				}
			}
		}
	}
	
	valid = phoneValid && addressValid;
	
	var email = $F("emailInput"); 
	var emailrequired =   ( $("emailMarker").style.display == "block" ); 
	if(emailrequired)
	{
		if (email) valid = false;
	}
	else if(email && !IsEmailValid(email))
	{
		valid = false;
	}

    return valid;
}

function ValidateAddressField(fldID, validationFunction, required, errMsg, markerID)
{
	var valid = true;
	markerID = markerID || fldID;
	var fld = $(fldID + "Input");
	if(!fld)
	{
		valid = !required;
	}
	else
	{
	    fld.value = fld.value.strip();
	
		if(!validationFunction($F(fld), required))
		{
			$(markerID + "Marker").style.display = "inline";
			valid = false;
			alert(errMsg);
		}
		else
		{
			$(markerID + "Marker").style.display = "none";
		}
	}
		
	return valid;
}

//10 digit string returns true
function IsPhoneValid(phone, required)
{
	if(phone.length == 0 && !required)
		return true;
		
	if(required && phone.length == 0)
		return false;
	else if(isNaN(phone))
		return false;
	else if(phone.length != 10)
		return false;
	
	return true;
}

function IsApartmentValid(apt, required)
{
	if(apt.length == 0 && !required)
		return true;
		
	if(required && apt.length == 0)
		return false;
	else
	{
		var exp = /^[A-Za-z0-9][\s\-A-Za-z0-9]*$/;
		return (apt.length==0 || exp.test(apt));
	}
}

//5 digit string returns true
var zipRegex = /^\d{5}$/;
function IsZipValid(zip, required)
{
	if(zip.length == 0 && !required)
		return true;
		
	if(required && zip.length == 0)
		return false;
	else if(isNaN(zip))
		return false;
	else if(zip.length != 5)
		return false;
		
	return zipRegex.test(zip);
}

//non-empty string returns true
function IsAddressValid(addr, required)
{
	if(addr.length == 0)
		return !required;
	
	return true;
}

function IsCityValid(city, required)
{
	//GEMINI DL-10814 - change to accept "." and "-"
	var cityRegex = /^[A-Za-z \.\-]+$/;
	if(!cityRegex.test(city))
		return !required;
		
	return true;
}

function IsStateValid(state, required)
{
	if(state.length == 0)
		return !required;
		
	return true;
}

function IsEmailValid(email, required)
{
	if(email.length == 0 && !required)
		return true;
		
	if(required && email.length == 0)
		return false;
	else if(email.length > 0)
		return (emailRegex.test(email));
	else
		return true;
		
}

var emailRegex = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;

function ClearData()
{
    $("areaInput").value = "";
    $("prefixInput").value = "";
    $("suffixInput").value = "";
    $("addressInput").value = "";
    $("apartmentInput").value = "";
    $("cityInput").value = "";
    $("zipCodeInput").value = "";
    $("emailInput").value = "";
    $($("stateDDLID").value).selectedIndex = 0;
}

function SubmitAddress()
{
	if( IsValid() )
	{
		var queryVars = new Hash();
		if( $("phone").style.display == "block" )
		{
			var phone = $("areaInput").value + $("prefixInput").value +$("suffixInput").value;
			if(phone)
				queryVars.set("phone", phone);
		}
		
		if($("address").style.display == "block")
		{
			var addressFld = $("addressInput");
			var addr = addressFld?$F(addressFld):null;
			if(addr) queryVars.set("address", addr);
			var aptFld = $("apartmentInput");
			var apt = aptFld?$F(aptFld):null;
			if(apt) queryVars.set("apt", apt);
			var cityFld = $("cityInput");
			//GEMINI: DL-10225
			var cityStateVisible = (cityFld && cityFld.up(".searchPanelRow").visible());
			var city = (cityFld && cityStateVisible)?$F(cityFld):null;
			if(city) queryVars.set("city", city);
			var stateDDLID = $("stateDDLID");
			if(stateDDLID)
			{
				var stateDDL = $(stateDDLID.value);
				var state = (stateDDL && cityStateVisible)?$F(stateDDL):null;
				if(state) queryVars.set("state", state);
			}
			
			var zipFld = $("zipCodeInput");
			var zip = zipFld?$F(zipFld):null;
			if(zip) queryVars.set("zip", zip);
		}
		
		var email = $F("emailInput");		
		if(email && (emailRegex.test(email)))
		{
			if(email) queryVars.set("email", email);
		}
		
		GetCampaignCustomizations(queryVars);
		
		var querystring = queryVars.toQueryString();
			
		CallDispatch( querystring );
	}
}

function GetCampaignCustomizations(vars)
{
	var keys = ["promoid", "originatorid", "source", "campaign", "affiliateid", "option1", "option2", "option3", "option4", "option5", "option6", "feature", "exsvc", "sourceplatformid"];
	var ccs = [];
	//var tch = getTransactionCookieHash();
	var campaign = $H(CampaignInfo);
	for(var i=0; i<keys.length; i++)
	{
		var val = campaign.get(keys[i])
		if(val) vars.set(keys[i], val);
	}
}
     
function CallDispatch(querystring)
{
    location.href = "/Dispatch.aspx?" + querystring;
}

///////////////////////////////////////////////Default.aspx//////////////////////////////////////////////
function Enter_Input()
{
    var emailEnter = $("emailInput");
    var zipEnter = $("zipCodeInput");
    if(emailEnter != null)
    {
        Event.observe(emailEnter, "keypress", OnEnterSubmitAddress);
    }
    if(zipEnter != null)
    {
        Event.observe(zipEnter, "keypress", OnEnterSubmitAddress);
    }
}

function OnEnterSubmitAddress(e)
{
   var keyCode = e.keyCode || e.which;
   if(keyCode==13)
   {
      SubmitAddress();
   }
}

///////////////////////////////////////////////Dispatch.aspx///////////////////////////////////////////////
function Phone(phoneNumber)
{
    if (phoneNumber && phoneNumber.length == 10)
    {
        this.Number = phoneNumber;
        this.AreaCode = phoneNumber.substr(0, 3);
        this.Exchange = phoneNumber.substr(3, 3);
        this.Station = phoneNumber.substr(6);
    }
}

function CustomerInformationControl()
{
	this.apartmentRequired = false;

	this.validationCounter = 0;
	this.noApartmentCounter = 0;

    this.headerText = $("cicHeader_Text");

	this.isApartmentInputContainer = $("cic_isApartmentInputContainer");
	this.isApartmentInput = $("cic_isApartmentInput");
	this.apartmentInput = $("cic_apartmentInput");
	this.addressInput = $("cic_addressInput");
	this.apartmentInput = $("cic_apartmentInput");
	this.cityInput = $("cic_cityInput");
	this.stateInput = $("cic_stateInput");
	this.zipInput = $("cic_zipCodeInput");

    this.phoneNumberInput = $("cic_phoneNumberInput");
    this.noPhoneNumberInput = $("cic_noPhoneNumberInput");

	this.customerInfoEntry = $("customerInformationControl");
	
	document.body.appendChild($('cic_orangeArrow').remove());
	
}

CustomerInformationControl.Instance = 
function()
{
	if(!window["_customerInformationControl"])
		window["_customerInformationControl"] = new CustomerInformationControl();

	return window["_customerInformationControl"];
}

CustomerInformationControl.prototype.ApartmentUserIgnore =
function()
{
    if (this.isApartmentInput && this.apartmentInput)
    {
        this.apartmentInput.disabled = this.isApartmentInput.checked;

        if (this.apartmentInput.disabled)
        {
            this.apartmentInput.parentNode.parentNode.className = "CustomerInformationControlDisabled";
            this.apartmentInput.value = "";
        } 
        else
        {
            this.apartmentInput.parentNode.parentNode.className = "CustomerInformationControlHighlighted";
        }
    }
}

CustomerInformationControl.prototype.HomePhoneNumberIgnore = 
function()
{
	if(this.phoneNumberInput && this.noPhoneNumberInput)
	{
		this.phoneNumberInput.disabled = this.noPhoneNumberInput.checked;
		
		if(this.noPhoneNumberInput.checked)
			this.savedPhone = this.phoneNumberInput.value;
		else
			this.phoneNumberInput.value = this.savedPhone;
		
		if(this.phoneNumberInput.disabled)
		   this.phoneNumberInput.value = "";
	}
}

CustomerInformationControl.prototype.Show =
function(requireApartment, headerMessage)
{
    if(box != null) box.Close();
		
	box = new Lightbox("PhoneEntry1");
	box.Top = 80;
	box.Width = 425; 
	box.Height = 300;
	box.Modal = false;
	box.Shadow = true;
	box.Draggable = false;
	box.autoSize = true;
	box.includeClose = false;
	box.includePrint = false;
	box.ClassName = "customer-info-control-lightbox";

    this.addressInput.value = "";
	this.apartmentInput.value = "";
	this.cityInput.value = "";
	this.stateInput.value = "";

	if (requireApartment && requireApartment == true)
	{
	    this.apartmentRequired = true;
	    if (this.isApartmentInputContainer) this.isApartmentInputContainer.style.display = 'block';
	    if (this.apartmentInput) this.apartmentInput.parentNode.parentNode.className = "CustomerInformationControlHighlighted";
	    
	    if(qualifiedLocation.Phone && qualifiedLocation.Phone != "")
	        box.Height = 320;
	}
	
	if (headerMessage && headerMessage != '')
	{
	    if (this.headerText) this.headerText.innerHTML = headerMessage;
	}
	
    var activity = new Activity(ActivityManager.ActivityType.AddressValidationPrompt);
	
	if(this.phoneNumberInput && qualifiedLocation.Phone && qualifiedLocation.Phone != "")
	{
        var phoneFormat = new Template(PHONE_NUMBER_FORMAT);
	    var phoneValues = {areaCode: qualifiedLocation.Phone.AreaCode, exchange: qualifiedLocation.Phone.Exchange, station: qualifiedLocation.Phone.Station };

		this.phoneNumberInput.value = phoneFormat.evaluate(phoneValues);

        activity.NPA = qualifiedLocation.Phone.AreaCode;
        activity.NXX = qualifiedLocation.Phone.Exchange;
        activity.Suffix = qualifiedLocation.Phone.Station;
    }
    else
        this.phoneNumberInput.parentNode.parentNode.style.display = 'none';

	if(qualifiedLocation.Address)
	{
		if(this.addressInput && qualifiedLocation.Address.AddressLine1) this.addressInput.value = qualifiedLocation.Address.AddressLine1;
		if(this.apartmentInput && qualifiedLocation.Address.Unit) this.apartmentInput.value = qualifiedLocation.Address.Unit;
		if(this.cityInput && qualifiedLocation.Address.City) this.cityInput.value = qualifiedLocation.Address.City;
		if(this.stateInput && qualifiedLocation.Address.State) this.stateInput.value = qualifiedLocation.Address.State;
		if(this.zipInput)
		{ 
		    this.zipInput.value = qualifiedLocation.Address.ZipCode;
		    
		    if (qualifiedLocation.Address.ZipCodeExtension && qualifiedLocation.Address.ZipCodeExtension != '')
		    {
		        this.zipInput.size = 9;
		        this.zipInput.value += '-' + qualifiedLocation.Address.ZipCodeExtension;
		    }
		}

        activity.Address1 = qualifiedLocation.Address.AddressLine1;
        activity.Address2 = qualifiedLocation.Address.AddressLine2;
        activity.Apartment = qualifiedLocation.Address.Unit;
        activity.City = qualifiedLocation.Address.City;
        activity.State = qualifiedLocation.Address.State;
        activity.ZipCode = qualifiedLocation.Address.ZipCode;

		if (qualifiedLocation.Address.ZipCodeExtension && qualifiedLocation.Address.ZipCodeExtension != '')
		    activity.ZipCode += '-' + qualifiedLocation.Address.ZipCodeExtension;
	}

    ActivityManager.Instance.LogActivity(activity);
	
	box.observe("open", this.ShowExtraInfo.bind(this));
    box.Show();
	box.clear();		
	
	this.customerInfoEntry.parentNode.removeChild(this.customerInfoEntry);
	box.appendChild(this.customerInfoEntry);
	

    if (requireApartment)
    {
        this.phoneNumberInput.readOnly = true;
        this.addressInput.readOnly = true;
        this.cityInput.readOnly = true;
        this.stateInput.disabled = true;
        this.zipInput.readOnly = true;
    
        this.noApartmentCounter++;
    }
    else
        this.validationCounter++;
}

CustomerInformationControl.prototype.ShowExtraInfo =
function()
{
	var phonehover = new Control.Window('cic_orangeArrow', {
			fade: false,
			hover: 'cic_nomobiles',
			position: 'relative',
			offsetLeft: 110,
			offsetTop: -5
		});
	/*
	if(this.phoneShowing)
	{
		var info_box = $('cic_orangeArrow');
		document.body.appendChild(info_box.remove());
		var offset = $('cic_addressInput').cumulativeOffset();
		var width = this.addressInput.getWidth();
		info_box.setStyle({top: offset.top + "px", left: (offset.left + width) + "px", display: "block"});
	}
	*/
}

CustomerInformationControl.prototype.Validate =
function (location)
{
	var result = true;
	var addr = location.Address;
	var phone = null;

	if (location.Phone) phone = location.Phone.Number;
	
	var validAddress = true;

	if(addr && addr.AddressLine1)
	{
		if(!IsZipValid(addr.ZipCode, true))
			validAddress = false;
		else if(!IsAddressValid(addr.AddressLine1, true))
			validAddress = false;
	}
	
	var validPhone = true;

	if(phone && !IsPhoneValid(phone, false))
		validPhone = false;
	if(!phone && !addr)
		return false;
	
	result = validPhone || validAddress;
	
	return result;
}

CustomerInformationControl.prototype.Resubmit =
function ()
{
    var phone = this.phoneNumberInput.value.replace(/\D/g, "");
    var postalCodeValue = this.zipInput.value;
	var postalCode = postalCodeValue;
    var postalCodeExtension = '';

    if (postalCodeValue.indexOf('-') > -1)
    {
        postalCode = postalCodeValue.split('-')[0];
        postalCodeExtension = postalCodeValue.split('-')[1];
    }
    
    if(!IsPhoneValid(phone, false))
    {
	    alert("Please enter a valid phone number");
	    return false;
    }
		
    if(!IsAddressValid(this.addressInput.value, true))
    {
	    alert("Please enter your address");
	    return false;
    }
	
    if (!this.isApartmentInput.checked)
    {
        if(!IsApartmentValid(this.apartmentInput.value, this.apartmentRequired))
        {
            alert("Please enter a valid apartment/unit number");
            return false;
        }
    }

    if(!IsCityValid(this.cityInput.value, true))
    {
	    alert("Please enter your city");
	    return false;
    }
	
    if(!IsStateValid($F(this.stateInput), true))
    {
	    alert("Please enter your state");
	    return false;
    }
    	
    if(!IsZipValid(postalCode, true))
    {
	    alert("Please enter a valid zip code");
	    return false;
    }
	
	//all validation passed. set the info
	if (phone && phone != '') qualifiedLocation.Phone = new Phone(phone);
    
	if (!qualifiedLocation.Address) qualifiedLocation.Address = {};

	qualifiedLocation.Address.AddressLine1 = this.addressInput.value;
	qualifiedLocation.Address.Unit = this.apartmentInput.value;
	qualifiedLocation.Address.City = this.cityInput.value;
	qualifiedLocation.Address.State = this.stateInput.value;
	qualifiedLocation.Address.ZipCode = postalCode;
	qualifiedLocation.Address.ZipCodeExtension = postalCodeExtension;
	
    if (this.isApartmentInput.checked)
    {
        var aptUserIgnoreActivity = new Activity(ActivityManager.ActivityType.AptValidationUserIgnore);
	    ActivityManager.Instance.LogActivity(aptUserIgnoreActivity);
    }
    
    var activity = new Activity(ActivityManager.ActivityType.AddressValidationContinue);

    if (qualifiedLocation.Phone)
    {
        activity.NPA = qualifiedLocation.Phone.AreaCode;
        activity.NXX = qualifiedLocation.Phone.Exchange;
        activity.Suffix = qualifiedLocation.Phone.Station;
    }
        
    activity.Address1 = qualifiedLocation.Address.AddressLine1;
    activity.Apartment = qualifiedLocation.Address.Unit;
    activity.City = qualifiedLocation.Address.City;
    activity.State = qualifiedLocation.Address.State;
    activity.ZipCode = postalCodeValue;

    ActivityManager.Instance.LogActivity(activity);

	box.Close();
	GOA();
}

CustomerInformationControl.prototype.Cancel =
function ()
{
	location.href = "/Verification.aspx?type=cancel"; 
}

function Dispatch_Load()
{
	if(!Acceller.DetectXsltSupport())
	{
		AjaxManager.Call("SetClientXsltSupport", [false], Dispatch_Load_Continue, { CallbackPage: "Dispatch.ashx" });
	}
	else
		Dispatch_Load_Continue();
	
}

function Dispatch_Load_Continue()
{
	if(isPhoneRequired)
		RenderPhoneEntryControl();
	else if(!CustomerInformationControl.Instance().Validate(qualifiedLocation))
		CustomerInformationControl.Instance().Show();
	else
		GOA();
}

function GOA()
{
	var phoneNumber = (qualifiedLocation.Phone && qualifiedLocation.Phone.Number) ? qualifiedLocation.Phone.Number : "";
	var addressLine1 = (qualifiedLocation.Address) ? qualifiedLocation.Address.AddressLine1 : "";
	var unit = (qualifiedLocation.Address) ? qualifiedLocation.Address.Unit : "";
	var city = (qualifiedLocation.Address) ? qualifiedLocation.Address.City : "";
	var state = (qualifiedLocation.Address) ? qualifiedLocation.Address.State : "";
	var zipCode = (qualifiedLocation.Address) ? qualifiedLocation.Address.ZipCode : "";
	var zipCodeExtension = (qualifiedLocation.Address) ? qualifiedLocation.Address.ZipCodeExtension : "";
	var apartmentIgnored = CustomerInformationControl.Instance().isApartmentInput.checked;
	var phoneNumberIgnored = CustomerInformationControl.Instance().noPhoneNumberInput.checked;

    var activities = ActivityManager.Instance.SerializeAndPurge();
    
	Acceller.GOA = AjaxManager.Call("GetOfferAvailability", [addressLine1, unit, city, state, zipCode, zipCodeExtension, phoneNumber, apartmentIgnored, phoneNumberIgnored, activities], GetOfferAvailability_Callback, {onException: function (){} } );
}

function UpdatePhoneEvent(e)
{
	var phone = $("npa").value + $("nxx").value + $("suffix").value;

	if(IsPhoneValid(phone, false))
	{
	    if (phone != "")
	    {
            qualifiedLocation.Phone = new Phone(phone);
    		
		    var supplementalPhoneQuery = new Activity(ActivityManager.ActivityType.SupplementalPhoneQuery);
    	    
	        supplementalPhoneQuery.NPA = qualifiedLocation.Phone.AreaCode;
		    supplementalPhoneQuery.NXX = qualifiedLocation.Phone.Exchange;
	        supplementalPhoneQuery.Suffix = qualifiedLocation.Phone.Station;
    		
		    ActivityManager.Instance.LogActivity(supplementalPhoneQuery);
		}
	}
	else
	{
		alert("Please enter a valid phone number.");
		return;
	}	
	
	if(!CustomerInformationControl.Instance().Validate(qualifiedLocation))
	{
		if(qualifiedLocation.Phone && qualifiedLocation.Phone.Number)
			CustomerInformationControl.Instance().Show();
	}
	else
	{
		box.Close();
		GOA()
	}
}

function RenderPhoneEntryControl()
{
	if( box != null )
		box.Close();
		
	box = new Lightbox("PhoneEntry1");
	box.Top = 80;
	box.Width = 350; 
	box.Height = 275;
	box.Modal = false;
	box.Shadow = true;
	box.Draggable = false;
	box.includeClose = false;
	box.includePrint = false;
	box.ClassName = "customer-info-control-lightbox";
	box.Show();

	box.clear();		
	var phoneentry = $("phone_entry_control");
	phoneentry.parentNode.removeChild(phoneentry);
	box.appendChild(phoneentry);
}

var GOAResponseCode =
{
	Success: "0",
	NoOffersAvailable: "1",
	AddressFormatError: "2",
	SystemError: "3",

	AddressNormalizationError: "7",
	PhoneResolutionError: "8",
	AddressPhoneMismatchError: "9",

	OneClickOfferSuccess: "10",
	OneClickOfferFailure: "11"
}

var GOAResponseStatus =
{
	Success: "1",
	Partial: "2",
	Failure: "3",
	Unknown: "999999"
}

function GetOfferAvailability_Callback( ajaxResponse )
{
	if( ajaxResponse.HasError )
	{
	    location.replace("/Verification.aspx?type=none");
	}
	
	try
	{
		var response = ajaxResponse.Output.evalJSON();
		if(response.Code == GOAResponseCode.OneClickOfferSuccess) //one click offer succeeded 
		{
			var offer = response.Message.evalJSON();
			PlaceOrder(true, offer);
		}
		else if(response.Code == GOAResponseCode.OneClickOfferFailure) //one click failure
		{
			location.replace("/Verification.aspx?type=oneclick");
		}
		else if(response.Code == GOAResponseCode.NoOffersAvailable) //no offers available
		{
			location.replace("/Verification.aspx?type=nooffers");
		}
		else if(response.Code == GOAResponseCode.AddressFormatError) // Failure and AddressFormatError
        {
            var requireApartment = null;
            var header = null;
            
			if(response.Message)
			{
				var addr = response.Message.evalJSON();
				qualifiedLocation.Address = addr;
			}
			
			if(response.Results && response.Results.length >= 1)
			{
			    header = response.Results[0].Message;
			    response.Results.each(function (result) { if (result.Code == "TransactionID") Acceller.TransactionID = result.Message;  });
			
			    if (response.Results[0].Code == "153") // Apartment Required
			    {
			        if (CustomerInformationControl.Instance().noApartmentCounter > 0)
			        {
			            location.replace("/Verification.aspx?type=apartmentValidation");
			        }
			        else 
			        {
			            if (qualifiedLocation && qualifiedLocation.Address)
			            {
                            var activity = new Activity();
                            
                            if (qualifiedLocation.Address.Normalized)
                                activity.ActivityType = ActivityManager.ActivityType.AptValidationTargus;
                            else 
                                activity.ActivityType = ActivityManager.ActivityType.AptValidationCorrectAddress;
        	                
	                        activity.Address1 = qualifiedLocation.Address.AddressLine1;
	                        activity.Address2 = qualifiedLocation.Address.AddressLine2;
	                        activity.Apartment = qualifiedLocation.Address.Unit;
	                        activity.City = qualifiedLocation.Address.City;
	                        activity.State = qualifiedLocation.Address.State;
	                        activity.ZipCode = qualifiedLocation.Address.ZipCode;
        	                
	                        ActivityManager.Instance.LogActivity(activity);
                        }
			    
			            requireApartment = true;
			        }
			    } else if (CustomerInformationControl.Instance().validationCounter > 0)
                    location.replace("/Verification.aspx?type=addressValidation");
			}
			
            CustomerInformationControl.Instance().Show(requireApartment, header);
        }
		else if((response.Status == GOAResponseStatus.Success) || (response.Status == GOAResponseStatus.Partial))
			location.replace("/ShowOffers.aspx");
		else
			location.replace("/Verification.aspx?type=none");
	}
	catch(ex)
	{
	}
}

function ChooseOffer_Callback(offerIDs, ajaxResponse )
{
	if(!ajaxResponse.HasError)
	{
		try
		{
			var result = ajaxResponse.Output.evalJSON();

			if(result.Code == "OfferIncompatible")
			{
				Acceller.Alert(SHOWOFFERS_INCOMPAT);
			}
			else 
			{
				var upsellsUpdated = false;
			
				var om = OfferManager.Instance();
				if(result.Results.length > 0)
				{
					for(var i=0; i<result.Results.length; i++)
					{
						var item = result.Results[i];
						if(item.Code == "CartUpdate")
						{
							//update my selection summary
							var msscData = item.Message.evalJSON();
							om.UpdateCart(msscData);

							//update price details
							for(var j=0; j<offerIDs.length; j++)
							{
								var offerID = offerIDs[j];
								if(PriceDetailsCtrl)
									PriceDetailsCtrl.addOffer(offerID);
								var category = om.GetOfferCategory(offerID);
								//var mode = om.mode;
								if( category != null )
								{
									category.Update();
									category.Close();
								}
							}

							window.scrollTo(0,0);
						}
						else if(item.Code == "Upsells")
						{
							var upsellsDiv = $("upsellOffers");
							
							upsellsUpdated = true;
							var upsells = item.Message.evalJSON();
							upsellsDiv.innerHTML = upsells.HTML;
							Highlight.curry("OfferUpsells", false, 2.5).defer();
							
							try
							{
								eval(upsells.Script);
							}
							catch (e)
							{}
						}
					}
				}
				
				if(!upsellsUpdated)
				{
					var upsellsDiv = $("upsellOffers");
					upsellsDiv.innerHTML = "";
				}
				
				if(PriceDetailsCtrl)
					PriceDetailsCtrl.updateDynamicBundles();
				om.UpdateDynamicBundleBanners();
								
				//show any removed offers
				var offerIDs = result.Message.evalJSON();
				var removedOfferCategories = [];
				for(var i=0; i<offerIDs.length; i++)
				{
					var oid = offerIDs[i];
					
					if(PriceDetailsCtrl)
						PriceDetailsCtrl.removeOffer(oid);
						
					//GEMINI DL-11217 - update categories with offers that should be re-shown
					var category = om.GetOfferCategory(oid);
					if(category && !removedOfferCategories.include(category))
						removedOfferCategories.push(category);
				}
				removedOfferCategories.each(function(cat) { cat.Update(); cat.QuickViewFixup(); });
			}
			
		}
		catch (ex)
		{
		}
	}
	else
	{
		Acceller.Alert(SHOWOFFERS_UNABLETOCHOOSE);
	}
	
	HideWait();
}


function RemoveOffer_Callback( offerID, ajaxResponse )
{		
	if( ajaxResponse.HasError )
	{
		Acceller.Alert(ajaxResponse.Error.Message);
	}
	else
	{
	
		try
		{
			var result = ajaxResponse.Output.evalJSON();
			var om = OfferManager.Instance();
			
			if(PriceDetailsCtrl)
				PriceDetailsCtrl.removeOffer(offerID);
			//update my selection summary
			var upsellsUpdated = false;
			
			for(var i=0; i<result.Results.length; i++)
			{
				var item = result.Results[i];
				if(item.Code == "CartUpdate")
				{
					var msscData = item.Message.evalJSON();
					om.UpdateCart(msscData);
				}
				else if(item.Code == "Upsells")
				{
					upsellsUpdated = true;
					var upsellsDiv = $("upsellOffers");
					var upsells = item.Message.evalJSON();			
					upsellsDiv.innerHTML = upsells.HTML;
				}
			}
			
			if(!upsellsUpdated)
			{
				var upsellsDiv = $("upsellOffers");
				upsellsDiv.innerHTML = "";			
			}
			
			if(PriceDetailsCtrl)
				PriceDetailsCtrl.updateDynamicBundles();
			om.UpdateDynamicBundleBanners();
		}
		catch (ex)
		{
		}
	}
	
	var om = OfferManager.Instance();
	var category = om.GetOfferCategory(offerID);
	if(category)
	{
		category.Update();	
	}
	
	HideWait();
}

//GEMINI DL-3734
function PlaceOrder(replace, o)
{
	if(typeof(OfferManager) != 'undefined')
	{
		var om = OfferManager.Instance();
		om.orderOffers.each(function(oid)
		{
			var offer = om.GetOffer(oid);
			if(offer)
			{
				var activity = new Activity(ActivityManager.ActivityType.CheckoutByOffer);
				activity.ProviderOfferCd = offer.offerCode;
				activity.ProviderID = offer.providerID;
				activity.OfferName = offer.name;
				activity.PageName = "ShowOffers.aspx";
				ActivityManager.Instance.LogActivity(activity);
			}
		});
	}
	else //one click order
	{
		var activity = new Activity(ActivityManager.ActivityType.CheckoutbyOffer);
		activity.ProviderOfferCd = o.OfferCode;
		activity.ProviderID = o.ProviderID;
		activity.OfferName = o.Name;
		activity.PageName = "Dispatch.aspx";
		ActivityManager.Instance.LogActivity(activity);
		
	}
	
	ActivityManager.Instance.DumpLogs();
	
	var url = "http" + (Acceller.secureOrder?"s":"") + "://" + location.host + "/PlaceOrder.aspx";
	(function() { if(replace===true) location.replace(url); else location.href = url; }).defer();
}

if(Acceller.isPage("placeorder.aspx"))
	Event.observe(window, "load", WebkitSubmitHandler)
	
function WebkitSubmitHandler()
{
	var form = $("aspnetForm");
	if(form)
	{
		Event.observe(form, "submit", WebkitSubmitHandler);
	}
}

function WebkitSubmitHandler(evt)
{
	evt.stop();
}

///////////////////////////////////////////////PlaceOffer.aspx///////////////////////////////////////////////


function UpdateCreditCardInfo_Begin(ccctrl)
{	
	UpdateCreditCardInfo( ccctrl.getJSON(), UpdateCreditCardInfo_End );
}
	
function UpdateCreditCardInfo_End( transport )
{
	
}

var CreditCardManager = Class.create(
{
	initialize: function()
	{
		this.controls = new Hash();
	},
	
	Add: function(ccc)
	{
		this.controls.set(ccc.id, ccc);
	},

	Get: function(id)
	{
		return this.controls.get(id);
	},
	
	SwapDiv: function(id, swap)
	{
		var cc = this.Get(id);
		if(cc)
			cc.swapDiv(swap);
	},
	
	SetCVV: function(id)
	{
		var cc = this.Get(id);
		if(cc)
			cc.setCVV();
	},
	
	ShowCCOverrideAuthorization: function(id)
	{
		var cc = this.Get(id);
		if(cc)
			cc.ShowCCOverrideAuthorization();
	},
	
	HideCCOverrideAuthorization: function(id)
	{
		var cc = this.Get(id);
		if(cc)
			cc.HideCCOverrideAuthorization();
	},
	
	CCPreOverride: function(id)
	{
		var cc = this.Get(id);
		if(cc)
			cc.PreOverride();
	},
	
	ClickBillingAddressChbx: function(id)
	{
		var cc = this.Get(id);
		if(cc)
			cc.ClickBillingAddressChbx();
	}
	
});

var CCManager = new CreditCardManager();

var CreditCardControl = Class.create(
{
	initialize: function(moID, yrID, stID, reID, ccDdlId, reuse, id, providerID, ccTypeID, validationGroupID)
	{
		this.id = id;
		this.monthID = moID;
		this.yearID = yrID;
		this.stateID = stID;
		this.relationshipID = reID;
		this.ccDDLID = ccDdlId;
		this.reuse = reuse;
		this.providerID = providerID;
		this.ccTypeID = ccTypeID;
		this.validationGroupID = validationGroupID;
		
		this.doPostOverride = false;
		this.doCCPreOverride = false;
		this.CCPreOverrideAuthorized = false;

		this.firstNameID = 'txtCardholderFirst';
		this.lastNameID = 'txtCardholderLast';
		this.address1ID = 'txtCCAddress1';
		this.address2ID = 'txtCCAddress2';
		this.apartmentID = 'txtCCApartment';
		this.cityID = 'txtCCCity';
		this.zipID = 'txtCCZipCode';
		this.ccNumberID = 'txtCCNumber';
		this.cvvID = 'txtCCcvv';
		this.billingAddressChbxID = 'cbxBillingAddress';
		this.billingAddressID = 'billingAddress';
			
		this.cleanup();
		
		this.inited = false;
		
		//add myself to the manager
		CCManager.Add(this);
	},
	
	init: function()
	{
		if(this.inited) return;
		
		this.month = $(this.monthID);
		this.year = $(this.yearID);
		this.state = $(this.stateID);
		this.cctype = $(this.ccTypeID);
		this.firstname = $(this.id + this.firstNameID);
		this.lastname = $(this.id + this.lastNameID);
		this.address1 = $(this.id + this.address1ID);
		this.address2 = $(this.id + this.address2ID);
		this.apartment = $(this.id + this.apartmentID);
		this.city = $(this.id + this.cityID);
		this.zip = $(this.id + this.zipID);
		this.number = $(this.id + this.ccNumberID);
		this.cvv = $(this.id + this.cvvID);
		this.billingAddressChbx = $(this.id + this.billingAddressChbxID);
		this.relationship = $(this.relationshipID);
		this.reuseCCDiv = $(this.id + "reuseCCDiv");
		this.newCCDiv = $(this.id + "newCCDiv");
		this.billingAddress = $(this.id + this.billingAddressID);
		this.ccDDL = $(this.ccDDLID);
		//this.reuseCardId = null;
		
		this.authorizedCode = null;
		this.authorizedReason = null;
			
		Event.observe(window, 'unload', this.cleanup.bind(this));
		
		this.inited = true;
	},
	
	cleanup: function()
	{
		this.month = null;
		this.year = null;
		this.state = null;
		this.cctype = null;
		this.firstname = null;
		this.lastname = null;
		this.address1 = null;
		this.address2 = null;
		this.apartment = null;
		this.city = null;
		this.zip = null;
		this.number = null;
		this.cvv = null;
		this.billingAddressChbx = null;
		this.relationship = null;
		this.reuseCCDiv = null;
		this.newCCDiv = null;
		this.ccDDL = null;
	},
	
	Validate: function()
	{
		this.init();
		
		if(this.reuse) return new ValidationResult(true);
		
		var today = new Date();
		var month = 0;
		var year = 0;
		
		var result = new ValidationResult(true);
		var msg;
		
		if(this.doCCPreOverride)
		{
			if(!this.CCPreOverrideAuthorized)
			{
				msg = "You must complete the Card Override Authorization or click the Cancel button and provide credit card information";
				result.messages.push(msg);
				result.isValid = false;
			}
		}
		else
		{
			if( this.number.value == '' )
			{
				msg = CRDT_CRD_ERR_MISSING_NUMBER;
				result.messages.push(msg)
				result.isValid = false;
			}
			else if( !checkCreditCard( this.number.value, this.cctype.options[this.cctype.selectedIndex].text ) )
			{
				msg = CRDT_CRD_ERR_INVALID_NUMBER;
				result.messages.push(msg);
				result.isValid = false;
			}
			
			ErrorIcon(this.id + 'errccnumber', !result.isValid, msg);

			var validDate = true;
			if( this.month.selectedIndex == -1 )
			{
				msg = CRDT_CRD_ERR_EXP_MONTH;
				result.messages.push(msg);
				result.isValid = false;
				validDate = false;
			}
			else
			{
				month = this.month.selectedIndex;
			}
			
			if( this.year.selectedIndex == -1 )
			{
				msg = CRDT_CRD_ERR_EXP_YEAR;
				result.messages.push(msg);
				result.isValid = false;
				validDate = false;
			}
			else
			{
				year = this.year.options[this.year.selectedIndex].text;
				if( year < today.getFullYear() )
				{
					msg = CRDT_CRD_ERR_EXPIRED;
					result.messages.push(msg)
					result.isValid = false;
					validDate = false;
				}
				else if(( year == today.getFullYear() ) && ( month < today.getMonth() ))
				{
					msg = CRDT_CRD_ERR_EXPIRED;
					result.messages.push(msg);
					result.isValid = false;
					validDate = false;
				}
			}
			
			ErrorIcon(this.id + 'errccexpiration', !validDate, msg);
			
			var validCvv = true;
			if(this.cvv)
			{
				var sCvvre = "^\\d{" + this.cvv.maxLength + "}$";
				var cvvre = new RegExp(sCvvre);
				if(this.cvv.value == '')
				{
					msg = CRDT_CRD_ERR_CVV;
					result.messages.push(msg);
					result.isValid = false;
					validCvv = false;
				}
				else if (!cvvre.test(this.cvv.value))
				{
					msg = CRDT_CRD_ERR_CVV_INVALID;
					result.messages.push(msg);
					result.isValid = false;
					validCvv = false;
				}
				ErrorIcon(this.id + 'errcvv', !validCvv, msg)
			}
				
			var validName = true;
			if(!dIsValidName(this.firstname.value) || !dIsValidName(this.lastname.value ))
			{
				msg = CRDT_CRD_ERR_NAME;
				result.messages.push(msg);
				result.isValid = false;
				validName = false;
			}

			ErrorIcon(this.id + 'errccname', !validName, msg);

			if( this.relationship && this.relationship.value == '' )
			{
				msg = CRDT_CRD_ERR_RELATIONSHIP;
				result.messages.push(msg);
				result.isValid = false;
			}
			
			if (!this.billingAddressChbx.checked)
			{
				var validAddr = true;		
				if(this.address1.value == '')
				{
					msg = CRDT_CRD_ERR_ADDRESS;
					result.messages.push(msg);
					result.isValid = false;
					validAddr = false;
				}
				ErrorIcon(this.id + 'erraddress1', !validAddr, msg);
				
				var validCityState = true;
				if(( this.city.value == '' ) || ( this.state.selectedIndex == -1 ))
				{
					msg = CRDT_CRD_ERR_CITYSTATE;
					result.messages.push(msg);
					result.isValid = false;	
					validCityState = false;	
				}
				ErrorIcon(this.id + 'errcitystate', !validCityState, msg);
				
				var validZip = true;
				if( this.zip.value == '' || this.zip.value.length != 5 || isNaN(this.zip.value) )
				{
					msg = CRDT_CRD_ERR_ZIP;
					result.messages.push(msg);
					result.isValid = false;
					validZip = false;
				}
				ErrorIcon(this.id + 'errzip', !validZip, msg);
			}
		}
				
		return result;
	},
	
	GetSubmissionPackage: function(validationGroupResult)
	{
		this.init();
		
		var cc = new CreditCard();
		if(this.reuse)
		{
			
			//jsonObject.reuse = true;
			if(this.ccDDL)
				cc.ProviderID = this.ccDDL.value;
			else if(this.reuseCardId != null)
				cc.ProviderID = this.reuseCardId;
		}
		else
		{
			cc.CreditCardNumber = this.number.value;
			cc.SecurityCode = (this.cvv)?this.cvv.value:'';
			cc.ExpirationMonth = (this.month.selectedIndex + 1);
			cc.ExpirationYear = parseInt(this.year.options[ this.year.selectedIndex ].text);
			cc.CardType = this.cctype.options[ this.cctype.selectedIndex ].value
			cc.FirstName = this.firstname.value;
			cc.LastName = this.lastname.value;
			cc.UseServiceAddress = this.billingAddressChbx.checked;
			cc.BillingAddress = new Address();
			cc.BillingAddress.AddressLine1 = this.address1.value;
			cc.BillingAddress.AddressLine2 = this.address2.value;
			cc.BillingAddress.Unit = this.apartment.value;
			cc.BillingAddress.City = this.city.value;
			var stateIdx = (this.state.selectedIndex>-1)?this.state.selectedIndex:1;
			cc.BillingAddress.State = this.state.options[ stateIdx ].text;
			cc.BillingAddress.ZipCode = this.zip.value;
			cc.Relationship = this.relationship.value;
			cc.ProviderID = this.providerID;
			cc.DoOverRide = this.doPostOverride;
		}
		
		if(validationGroupResult)
		{
			if(!validationGroupResult.CreditCardList) validationGroupResult.CreditCardList = [];
			validationGroupResult.CreditCardList.push(cc);
			if(this.authorizedCode)
			{
				validationGroupResult.CreditCardOverride = new CreditCardAuthorizedOverride();
				validationGroupResult.CreditCardOverride.ProviderID = this.ProviderID;
				validationGroupResult.CreditCardOverride.AuthorizedCode = this.authorizedCode;
				validationGroupResult.CreditCardOverride.AuthorizedReason = this.authorizedReason;
			}
		}	

		return cc;
	},
	
	ClickBillingAddressChbx: function()
	{
		this.init();
		if ( !this.billingAddressChbx.checked )
			this.billingAddress.style.display = "";
		else 
			this.billingAddress.style.display = "none";
	},
	
	ClearSecureInfo: function()
	{
		this.init();
		
		this.number.value = "";
		if(this.cvv)
			this.cvv.value = "";
	},
	
	swapDiv: function(reuse)
	{
		this.init();
		
		this.reuse = reuse;
		this.reuseCCDiv.style.display = reuse?"":"none";
		this.newCCDiv.style.display = reuse?"none":"";
	},
	
	setCVV: function()
	{
		this.init();
	    
		var cvv_length = 3;
	    
		if (this.cctype.options[ this.cctype.selectedIndex ].text == "American Express")
			cvv_length = 4;

		if(this.cvv)
		{
			if (this.cvv.value.length > cvv_length)
				this.cvv.value = this.cvv.value.substr(0, cvv_length);
		    
			this.cvv.maxLength = cvv_length;
		}
	},

	ShowCCOverrideAuthorization: function()
	{
		var ccdiv = $(this.id + "ccMain");
		var ccordiv = $(this.id + "ccPreOverrideSection");
		var orbtn = $(this.id + "ccPreOverrideBtn");
		orbtn.style.display = "none";
		
		ccordiv.style.display = "block";
		
		var options = { duration: 0.5, queue: 'end' };
		new Effect.Parallel([
					 new Effect.SlideUp( ccdiv,  { sync:true,scaleContent:false,scaleFromCenter:false,scaleTo:0 }),
					new Effect.SlideDown( ccordiv, { sync:true,scaleContent:false,scaleFromCenter:false,scaleTo:100 })
				], options);
				
		this.doCCPreOverride = true;
		
		ErrorIcon(this.id + 'errccnumber', false, "");
		ErrorIcon(this.id + 'errccexpiration', false, "");
		ErrorIcon(this.id + 'errcvvcc', false, "");
		ErrorIcon(this.id + 'errccname', false, "");
		ErrorIcon(this.id + 'erraddress1', false, "");
		ErrorIcon(this.id + 'errcitystate', false, "");
		ErrorIcon(this.id + 'errzip', false, "");

		if(this.validationGroupID)
		{
			var custMgr = CustomizationManager.Instance();
			var validationGroup = custMgr.GetValidationGroup(this.validationGroupID);
			var validationGroupList = custMgr.GetValidationGroupParentList(this.validationGroupID);
			validationGroup.messages = [];
			validationGroupList.messages = [];
			
			validationGroup.UpdateErrorIcon(false);
			validationGroupList.UpdateValidationSummary();
		}
	},
	
	HideCCOverrideAuthorization: function()
	{
		var ccdiv = $(this.id + "ccMain");
		var ccordiv = $(this.id + "ccPreOverrideSection");
		var orbtn = $(this.id + "ccPreOverrideBtn");
		orbtn.style.display = "block";
		
		var options = { duration: 0.5, queue: 'end' };
		new Effect.Parallel([
					 new Effect.SlideUp( ccordiv,  { sync:true,scaleContent:false,scaleFromCenter:false,scaleTo:0 }),
					new Effect.SlideDown( ccdiv, { sync:true,scaleContent:false,scaleFromCenter:false,scaleTo:100 })
				], options);
		
		this.doCCPreOverride = false;
		
		ErrorIcon(this.id + 'errccoverrideAuth', false, "Authorization Code is required.");
		ErrorIcon(this.id + 'errccoverrideReason', false, "Reason Code is required.");
		if(this.validationGroupID)
		{
			var custMgr = CustomizationManager.Instance();
			var validationGroup = custMgr.GetValidationGroup(this.validationGroupID);
			var validationGroupList = custMgr.GetValidationGroupParentList(this.validationGroupID);
			validationGroup.messages = [];			
			validationGroupList.messages = [];
			
			validationGroup.UpdateErrorIcon(false);
			validationGroupList.UpdateValidationSummary();
		}
	},

	PreOverride: function()
	{
		var authFld = $F(this.id + "ccPreOverride_AuthFld");
		var reasonFld = $F(this.id + "ccAuthorizedOverrideReasons");
		
		if(!authFld)
		{
			var custMgr = CustomizationManager.Instance();
			var validationGroup = custMgr.GetValidationGroup(this.validationGroupID);
			var validationGroupList = custMgr.GetValidationGroupParentList(this.validationGroupID);
			
			
			var msg = "Authorization Code is required.";
			ErrorIcon(this.id + 'errccoverrideAuthServiceAddresses', true, msg);
			validationGroup.messages = [msg];
			validationGroup.ShowErrorIcon(true);
			validationGroupList.UpdateValidationSummary();
		}
		else
			AjaxManager.Call("CCPreOverride", [authFld], this.PreOverride_Callback.bind(this, authFld, reasonFld));
	},

	PreOverride_Callback: function(auth, reason, ajaxResponse)
	{
		var result = ajaxResponse.Output.evalJSON();
		var custMgr = CustomizationManager.Instance();
		var validationGroup = custMgr.GetValidationGroup(this.validationGroupID);
		var validationGroupList = custMgr.GetValidationGroupParentList(this.validationGroupID);

		if(result.Status == 1)
		{
			var msgdiv = $(this.id + "ccPreOverrideMessage");
			msgdiv.innerHTML = result.Message;
			
			var frm = $(this.id + "ccPreOverrideForm");
			frm.style.display = "none";
						
			this.authorizedCode = auth;
			this.authorizedReason = reason;
			validationGroup.messages = [];
			
		}
		else
		{
			validationGroup.messages = [result.Message];
		}
		
		ErrorIcon(this.id + 'errccoverrideAuth', !this.CCPreOverrideAuthorized, result.Message);	
		validationGroup.UpdateErrorIcon(!this.CCPreOverrideAuthorized);
		validationGroupList.UpdateValidationSummary();
	}
});

var CreditCard = Class.create(
{
	initialize: function()
	{
		this.CreditCardNumber = null;
		this.SecurityCode = null;
		this.ExpirationMonth = null;
		this.ExpirationYear = null;
		this.CardType = null;
		this.FirstName = null;
		this.LastName = null;
		this.BillingAddress = null;
		this.UseServiceAddress = null;
		this.Relationship = null;
		this.ProviderID = null;
		this.DoOverRide = false;
	}
});

var CreditCardAuthorizedOverride = Class.create(
{
	initialize: function()
	{
		this.ProviderID = null;
		this.AuthoizedCode = null;
		this.AuthorizedReason = null;
	}
});


function IsDuplicateOrder()
{
    debug = true;
    var output = null;
    if(typeof(duplicateOrder) != 'undefined' && duplicateOrder)
		output = duplicateOrder.toArray();
	
	if(!output || output.length == 0 )
    {
		return false; 
    }
    else
    {
        if ( output[0] == "warning" ) 
        {
            var str = PLACE_ORDER_DUP_WARNING;

            str = str.replace("{0}", output[1]);
            var continueOrder = confirm(str);
            if ( continueOrder == true )
            {
				duplicateOrder = null;
				return false;
            }
            else
            {
                lock(false);
                return true;
            }
        } 
        // GEMINI : DL-4790
        else if ( output[0] == "error" ) 
        {
            var str = PLACE_ORDER_DUP_ERROR;
            str = str.replace("{0}", output[2]);
            str = str.replace("{1}", output[1]);
            alert(str);
            lock(false);
            return true;
        }
    }
}     

// COOKIE HELPERS
var transactionCookie = null;
function getTransactionCookie()
{
	if(!transactionCookie)
	{
		var cki = document.cookie.split(";");
		for(var i=0; i<cki.length; i++)
		{
			var idx = cki[i].indexOf("transaction=");
			if(idx == 0 || idx == 1) //check for idx 1 because IE7 seems to put a space in front
			{
				transactionCookie = cki[i];
				break;
			}
		}
	}

	return transactionCookie;	
}

var transactionCookieHash = null;
function getTransactionCookieHash()
{
	if(!transactionCookieHash)
	{
		if(!transactionCookie)
			getTransactionCookie();
			
		var valStr = transactionCookie.substr(transactionCookie.indexOf('=')+1);
		var vals = valStr.split('&');
		transactionCookieHash = new Hash();
		for(var i=0; i<vals.length; i++)
		{
			var kvp = vals[i].split('=');
			transactionCookieHash.set(kvp[0], kvp[1]);
		}
	}
	
	return transactionCookieHash;
}

function getTransactionCookieValue(key)
{
	var tch = getTransactionCookieHash();
	
	return tch.get(key);
}

function setTransactionCookieValue(key, val)
{
	var tch = getTransactionCookieHash();
	
	tch.set(key, val);
	document.cookie = "transaction=" + tch.toQueryString();
}

function SubmitOrder_Callback(ajaxResponse)
{
	var cm = CustomizationManager.Instance();
	if(ajaxResponse.HasError)
	{
		alert(PLACE_ORDER_CANNOT_COMPLETE);
		cm.RestartPolling();
		cm.RemoveMask();
		lock(false);
	}
	else
	{
		var aggregate = ajaxResponse.Output.evalJSON();
		if( aggregate.Status == 1 )
		{
			GoToConfirmation();
		}
		else
		{
			var result = null;
			var message = "";
			var i = 0;
			var len = aggregate.Results.length;
			for( i; i < len; i++ )
			{
				result = aggregate.Results[i];
				if( result.Status == 3 )
					message += "\n" + result.Message;
			}
			
			if( aggregate.Status == 2)
			{
				var alrt = new AccellerAlert();
				alrt.observe('ok', GoToConfirmation);
			    if (message != "")
				    alrt.message = PLACE_ORDER_FAILURE_INTRO + message;
				else 
				    alrt.message =(PLACE_ORDER_FAILURE_INTRO + PLACE_ORDER_FAILURE_END);
			    
				alrt.Show();
			}
			else
			// GEMINI : DL-4644 Fixed support for generic failure message
			{
			    if ( len > 0 )
					Acceller.Alert(PLACE_ORDER_FAILURE_INTRO + message);
				else
					Acceller.Alert(PLACE_ORDER_FAILURE_INTRO + PLACE_ORDER_FAILURE_END);
				
				cm.RestartPolling();
				lock(false);
			}
		}
	}
}

function GoToConfirmation()
{
	//force logging when we know we're leaving the page, don't rely on last resort unload handling
	ActivityManager.Instance.DumpLogs();
	
	location.href = "OrderConfirmation.aspx";
}

function TermsAndConditionsEvent(e)
{
     box = new Lightbox('TAC')
     box.Left = 25;
     box.Height = 599;
     box.Width = 701;
     box.Modal = true;
     box.Scroll = true;
     box.Shadow = true;
     box.Draggable = true;
     box.Content = "Article";
     box.Show();
     Event.observe( $('print_link'), 'click', PrintTermsEvent );
     
     AjaxManager.Call("ShowTermsAndConditions", [], Lightbox_Callback);
     //ShowTermsAndConditions(Lightbox_Callback);
}

function PrintTermsEvent(event)
{
    box.Close();
    window.open('Print.aspx?type=terms');
}

function ShowBillingInfoEvent(event, providerID, url)
{	
	box = new Lightbox('BillingBox1')
    box.Left = 25;
    box.Height = 599;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Content = "Details";
    box.Show();
    Event.observe( $('print_link'), 'click', PrintBillingEvent );
    
    if(url)
    {
		var callback = RenderArticleCallback.curry(url);
		AjaxManager.Call(null, null, callback, { Method: "get", ResponseType: AjaxManager.ResponseType.Literal, onSuccess: callback, onFailure: RenderArticleFailure, CallbackPage: url});
	}
	else
		AjaxManager.Call("RenderBillingInfo", [providerID], Lightbox_Callback);
}

function PrintBillingEvent(event)
{
    box.Close();
	window.open('Print.aspx?type=billing');
}

///////////////////////////////////////////////OrderAttachmentsControl.ascx///////////////////////////////////////////////
function ViewOrderAttachments(selectedAttachments)
{
	var btn = $("OrderAttachmentViewOffers");
	if(btn) btn.hide();
	var btn2 = $("OrderAttachmentSubmitWait");
	if(btn2) btn2.show();
	
	var backBtn = $("OrderAttachmentPaymentBack");
	if(backBtn) backBtn.hide();
	
	var submitBtn = $("OrderAttachmentSubmit");
	if(submitBtn) submitBtn.hide();
	
	selectedAttachments = selectedAttachments || "";
	AjaxManager.Call("RenderOrderAttachmentOffers", [selectedAttachments], ViewOrderAttachmentsCallback);
}

function ViewOrderAttachmentsCallback(ajaxResponse)
{
	var result = ajaxResponse.Output.evalJSON();
	var obj = result.Message.evalJSON();

	var div = $('OrderAttachmentContent');
	div.innerHTML = obj.HTML;
	
	try
	{
		eval(obj.Script);
	}
	catch(ex)
	{
	}
	
	var subhead = $('OrderAttachmentSubhead');
	subhead.innerHTML = ORDER_ATTACHMENTS_STEP1;
}

function OrderAttachmentsConfirmSelection()
{
	var offersDiv = $('OrderAttachmentOffers');
	var chbx = offersDiv.getElementsByTagName("INPUT");
	var ids = [];
	for(var i=0; i<chbx.length; i++)
	{
		if(chbx[i].checked)
			ids.push(chbx[i].value);
	}
	
	if(ids.length == 0)
		alert(INVALID_SELECTION);
	else
	{
		$("OrderAttachmentNext").hide();
		$("OrderAttachmentSubmitWait").show();
		
		var selectedIDs = ids.join(",");
		AjaxManager.Call("OrderAttachmentsSelect", [selectedIDs], OrderAttachmentsConfirmSelection_callback);
		//OrderAttachmentsSelect(selectedIDs, OrderAttachmentsConfirmSelection_callback);
	}
}

function OrderAttachmentsConfirmSelection_callback(ajaxResponse)
{
	var result = ajaxResponse.Output.evalJSON();
	var obj = result.Message.evalJSON();
	var div = $('OrderAttachmentContent');
	div.innerHTML = obj.HTML;
	
	try
	{
		eval(obj.Script);
	}
	catch(ex)
	{
	}
	
	var subhead = $('OrderAttachmentSubhead');
	subhead.innerHTML = ORDER_ATTACHMENTS_STEP2;
	
	if(div.scrollIntoView)
		div.scrollIntoView(true);
}

var attachmentSubmitting = false;
function DoOrderAttachmentSubmit(selectedOfferIDs, cccid)
{
	if(attachmentSubmitting) return;
	
	var errDiv = $("orderAttachmentError");
	errDiv.style.display = "none";
	
	var termsDiv = $("OrderAttachmentBillingTerms");
	var termsAccepted = true;
	if(termsDiv)
	{
	
		var termsChbx = termsDiv.getElementsByTagName("INPUT");
		for(var i=0; i<termsChbx.length; i++)
		{
			if(termsChbx[i].type == "checkbox")
			{
				termsAccepted = termsAccepted && termsChbx[i].checked; 
			}
		}
	}
	
	if(!termsAccepted)
	{
		alert(TERMS_ACCEPT_ERR);
		return;
	}

	var ccparam = "";
	var ccc = CCManager.Get('cc_0');
	if(ccc)
	{
		if(ccc.Validate().isValid)
		{
			//if(!ccc.reuse)
			ccparam = Object.toJSON(ccc.GetSubmissionPackage());
		}
		else
			return false;
	}	
	else
	{
		ccparam = "";
	}
	
	$("OrderAttachmentSubmit").hide();
	$("OrderAttachmentPaymentBack").hide();
	$("OrderAttachmentSubmitWait").show();
	
	attachmentSubmitting = true;
	AjaxManager.Call("OrderAttachmentSubmit", [ccparam, selectedOfferIDs], DoOrderAttachmentSubmit_Callback);
	//OrderAttachmentSubmit(ccparam, selectedOfferIDs, DoOrderAttachmentSubmit_Callback);	
}

function DoOrderAttachmentSubmit_Callback(ajaxResponse)
{
	//TODO: Error checking
	var result;
	if(ajaxResponse.Output)
		result = ajaxResponse.Output.evalJSON();
	else
		result = { Status: 3 };
		
	if(result.Status == 3 || result.Status == 999999) //failure
	{
		var message = result.Message || "Unfortunately your content subscription could not be processed.";
		var errDiv = $("orderAttachmentError");
		errDiv.innerHTML = message;
		errDiv.style.display = "";
		alert(message);
		
		
		$("OrderAttachmentPaymentBack").show();
		$("OrderAttachmentSubmitWait").hide();
		
		var btn = $("OrderAttachmentSubmit");
		if(btn)
		{
			btn.show();
			btn.disabled = false;
		}
	}
	else
	{
	    CustomizationManager.Instance().StopPolling();
		var div = $('OrderAttachmentBillingDiv');
		div.innerHTML = result.Message;
	
		var subhead = $('OrderAttachmentSubhead');
		subhead.style.display = "none";
	}
	
	attachmentSubmitting = false;
}

function AttachmentTerms(offerID)
{
	if( box != null )
		box.Close();
		
	chosenOfferID = offerID;
    box = new Lightbox('details1');
    box.Left = 25;
    box.Height = 597;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Show();
    Event.observe( $('print_link'), 'click', PrintDetailEvent.bind(window, offerID) );

	RenderAttachmentTerms(offerID, Lightbox_Callback);
}

function DynamicBundleDetails( file )
{
    if ((file != "") && (file != null))
    {
	    if( box != null )
		    box.Close();
    	
        box = new Lightbox('dynaBundle');
        box.Left = 25;
        box.Height = 602;
        box.Width = 701;
        box.Modal = true;
        box.Shadow = true;
        box.Draggable = true;
        box.Scroll = true;
        box.Shadow = true;
        box.Show();

	    var callback = DynamicBundleDetailCallback.curry(file);
	    AjaxManager.Call(null, null, callback, { Method: "get", ResponseType: AjaxManager.ResponseType.Literal, onSuccess: callback, onFailure: DynamicBundleDetailFailure, CallbackPage: file});
	}
}

function DynamicBundleDetailCallback(file, response)
{	
	if(response)
	{
		box.InnerHTML = response;
		box.Update();
	}
}

function DynamicBundleDetailFailure(ajaxResponse)
{
	box.InnerHTML = "An error has occurred";
	box.Update();
}

/*************************************** AT A GLANCE CONTROL ***************************************/
function AtAGlanceControl()
{
	this.shortTermPrice = 0;
	this.longTermPrice = 0;
	this.setupPrice = 0;
	this.messages = null;
	this.numOffers = 0;
}

AtAGlanceControl.prototype.update =
function(prices)
{
	
	if(prices)
	{
		this.shortTermPrice = prices.stp;
		this.longTermPrice = prices.ltp;
		this.setupPrice = prices.setup;
		this.numOffers = prices.numOffers;
		this.messages = prices.messages;
	}

	var shortTermPriceDiv = $('AAG_ShortPrice');
	if(shortTermPriceDiv)
		shortTermPriceDiv.innerHTML = parseFloat(this.shortTermPrice).toFixed(2);
	var shortTermDiv = $('AAG_ShortTermFees');
	if(shortTermDiv)
	{
		var display = "";
		if(this.shortTermPrice == 0)
			display = "none";
		
		shortTermDiv.style.display = display;
		var disclaimerDiv = $('AAG_Disclaimer');
		if(disclaimerDiv)
			disclaimerDiv.style.display = display;
	}
	
	var longTermPriceDiv = $('AAG_LongPrice');
	if(longTermPriceDiv)
		longTermPriceDiv.innerHTML = parseFloat(this.longTermPrice).toFixed(2);
	
	var setupPriceDiv = $('AAG_SetupPrice');
	if(setupPriceDiv)
		setupPriceDiv.innerHTML = parseFloat(this.setupPrice).toFixed(2);
		
	var messagesDiv = $('AAG_Disclaimers');
	if(messagesDiv)
	{
		var msg = $('AAG_Messages');
		if(msg)
			msg.innerHTML = this.messages;
		messagesDiv.style.display = (this.messages)?"":"none";
	}
		
	var placeOrderDiv = $('AAG_PlaceOrder');
	if(placeOrderDiv)
		placeOrderDiv.style.display = (this.numOffers>0 && location.href.toLowerCase().indexOf("showoffers.aspx") != -1)?"":"none";
}

AtAGlanceControl.prototype.ShowPriceDetails =
function()
{
	if( box != null )
		box.Close();
		
	box = new Lightbox('priceDetails');
	box.Left = 25;
	box.Height = 602;
	box.Width = 701;
	box.Modal = false;
	box.Shadow = false;
	box.Draggable = true;
	box.Scroll = true;
	box.includePrint = false;
	box.Content = "Article";    
	box.Show();
	
	AjaxManager.Call("RenderPriceDetails", [], this.ShowPriceDetailsCallback.bind(this));
}

AtAGlanceControl.prototype.ShowPriceDetailsCallback = 
function(ajaxResponse)
{
	Lightbox_Callback(ajaxResponse);
}

function GetPriceDisclaimer(providerID)
{
	if( box != null )
		box.Close();
		
	box = new Lightbox('priceDisclaimer');
	box.Left = 25;
	box.Height = 602;
	box.Width = 701;
	box.Modal = false;
	box.Shadow = false;
	box.Draggable = true;
	box.Scroll = true;
	box.includePrint = false;
	box.Content = "Article";    
	box.Show();

	var provider = OfferManager.Instance().GetProvider(providerID);
	if(provider && provider.priceDisclaimerURL)
	{
		var url = "/dynamiccontent/" + provider.priceDisclaimerURL;
		var callback = RenderArticleCallback.curry(url);
		AjaxManager.Call(null, null, callback, { Method: "get", ResponseType: AjaxManager.ResponseType.Literal, onSuccess: callback, onFailure: RenderArticleFailure, CallbackPage: url});
	}

}

/*
function ValidationResult(isValid, messages, hasValue)
{
	this.isValid = isValid || true;
	this.messages = messages || [];
	this.hasValue = hasValue || false;
	
}
*/

function ErrorIcon(img, show, msg)
{
	if(typeof(img) == "string")
		img = $(img);
		
	if(img)
	{
		img.style.display = show?"":"none";
		img.title = msg;
	}
}
//GEMINI : FALCON-5165 (Roberto Mardeni) Added to store the ActivityLog of ConfirmationUpsell
function ConfirmationUpsellEvent(upsellID)
{
    AjaxManager.Call("RegisterConfirmationUpsell", [Object.toJSON(upsellID)], RegisterConfirmationUpsell_Callback);
}
// Dummy function for callback
function RegisterConfirmationUpsell_Callback( ajaxResponse )
{
}
//END OF GEMINI : FALCON-5165 (Roberto Mardeni)

function CloseMessages()
{
	var div = $('MessageDiv');
	if(div)
		Collapse(div, true);
}


function VerisignSeal()
{
	var host = document.location.host;
	document.write("<script src=\"https://seal.verisign.com/getseal?host_name=" + host + "&#x26;size=M&#x26;use_flash=NO&#x26;use_transparent=NO&#x26;lang=en\"></sc" + "ript>");
}


function SubmitWarmTransfer(id)
{
	var ddl = $(id);
	
	if(ddl)
	{
		var opt = ddl.options[ddl.selectedIndex];
		AjaxManager.Call("SubmitWarmTransfer", [opt.value], SubmitWarmTransfer_Callback.bind(window, opt.text));
	}
}

function SubmitWarmTransfer_Callback(text, ajaxResponse)
{
	var div = $("warmTransferDiv");
	div.innerHTML = WARM_TRANSFER_COMPLETE + " <span class='warmTransferCompleteVal'>" + text + "</span>";
}

var resultsViewLoaded = false;
function RenderResultsView()
{
     var rv = $("resultsView");
     if(rv.getStyle("display") == "none")
	     Expand(rv);
     
     if(!resultsViewLoaded)
	     AjaxManager.Call("RenderProviderResults", [], RenderResultsView_Callback);
}

function RenderResultsView_Callback(ajaxResponse)
{
	if(!ajaxResponse.HasError && ajaxResponse.Output)
	{
		var div = $("resultsViewContent");
		div.innerHTML = ajaxResponse.Output;
		
		resultsViewLoaded = true;
	}
}

function ResultsViewClose()
{
	var rv = $("resultsView");
	Collapse(rv);
}

//////////////////////// ACTIVITY LOGGING //////////////////////// 
function ActivityManager()
{
	this.queue = new Array();
	this.enabled = true;
	
	this._logHandler = this.DumpLogs.bind(this, true);
	this.timeout = 60000;
	
	this.ServerTime = new Date();
	this.ServerTimeOffset = 0;
	
    this.asynchronous = (!Acceller.isPage('dispatch.aspx'));
	if (this.asynchronous)
		Event.observe(window, "load", this.init.bind(this));
		
	this.remoteActivityLoggingDisabled = false;
	this.remoteActivityLoggingURL = null;
	this.activityTypesHash = null;
}

ActivityManager.prototype.init =
function()
{
	window.setTimeout(this._logHandler, this.timeout);
	Acceller.AddUnloadListener(this._logHandler);
}

ActivityManager.prototype.SetServerTime = 
function(year, month, day, hours, minutes, seconds, ms, servertime)
{
	//month from the server is 1 based, client expects zero based.
	this.ServerTime = Date.UTC(year, month-1, day, hours, minutes, seconds, ms);
	var now = new Date();
	this.ServerTimeOffset = now.getTime() - this.ServerTime;
}

ActivityManager.prototype.GetActivityTime = 
function()
{
	var now = new Date();
	now.setTime(now.getTime() - this.ServerTimeOffset);
	var str = now.toUTCString();
	var idx = str.indexOf(" UTC");
	if(idx==-1) idx = str.indexOf(" GMT");
	return str.substr(0, idx);
}

ActivityManager.prototype.DumpLogs =
function(sync)
{
	if(this.enabled && this.queue.length && this.remoteActivityLoggingDisabled)
	{
		var async = !(sync === true);
		AjaxManager.Call("LogActivities", [Object.toJSON(this.queue)], this.DumpLogs_Callback.bind(this), { Asynchronous: async, onException: function() {} });
		this.queue = [];
	}
	
	this.allowDump = true;
}

ActivityManager.prototype.DumpLogs_Callback =
function(ajaxResponse)
{
	//alert(ajaxResponse.Output);
}

ActivityManager.prototype.LogActivity =
function(activity, forceDump)
{
    if (this.remoteActivityLoggingDisabled || activity.TransactionID <= 0 || CampaignInfo.RealTimeActivityLoggingEnabled)
        activity.PageName = "/" + Acceller.getPageName();
    if (this.remoteActivityLoggingDisabled || activity.TransactionID <= 0 )
        activity.CreatedDt = this.GetActivityTime();
    
	activity.SessionID = getTransactionCookieValue("dltoken");
    activity.TransactionID = Acceller.TransactionID;
    
    //GEMINI : DL-11113 (Eric Leichtenschlag) Escaping offer category type because it may have an ampersand (AT&T)
    if(activity.OfferCategoryType != null)
	    activity.OfferCategoryType = escape(unescape(activity.OfferCategoryType));
	if(activity.OfferName != null)
	    activity.OfferName = escape(unescape(activity.OfferName));
	if(activity.CustomizationSubGroupName != null)
	    activity.CustomizationSubGroupName = escape(unescape(activity.CustomizationSubGroupName));

    if (this.remoteActivityLoggingDisabled || activity.TransactionID <= 0)
	    this.queue.push(Object.toJSON(activity));
	else
	{
	    var activityParsed = "";
	    var activityMembers = $H(activity);
	    
	    if (activityMembers)
	    {
    	    activityMembers.each(
    	        function(item)
    	        {
    	            if (item.value)
    	            {
    	                if (activityParsed != "") activityParsed += "|";

    	                if (item.key == "ActivityType")
    	                {
    	                    if (!this.activityTypesHash) this.activityTypesHash = $H(ActivityManager.ActivityType);
    	                    var activityType = this.activityTypesHash.find(function(item2){ return (item2.value == item.value); });
    	                    activityParsed += item.key + "~" + (activityType ? activityType.key : item.value );
    	                }
    	                else
    	                {
    	                    if (item.value.constructor!=Date)
    	                        activityParsed += item.key + "~" + escape(unescape(item.value.toString().gsub('[|&~=]', "")));
    	                }
    	            }
    	        }
    	    );
	    }

	    var now = new Date();
	    var queryString = "?applicationID=" + escape(Acceller.ApplicationName) + "&activity=" + activityParsed + "&timestamp=" + now.toJSON().gsub('"', '');
	    var url = (("https:" == document.location.protocol) ? "https://" : "http://") + this.remoteActivityLoggingURL + "/ActivityLog" + (CampaignInfo.RealTimeActivityLoggingEnabled ? ".ashx" : ".html") + queryString;
	    
	    var activityHandler = new Element("img");
	    activityHandler.src = url;
	}
	
	if(this.queue.length >= 10 || forceDump)
		this.DumpLogs(false);
}

ActivityManager.prototype.SerializeAndPurge =
function()
{
    var value = Object.toJSON(this.queue);
    this.queue = [];
    return value;
}

ActivityManager.ActivityType =
{
        AddressQuery: 0,
        PhoneQuery: 1,
        AddressPhoneQuery: 2,
        ProviderOfferCount: 3,
        TargusNoMatch: 4,
        NoOffers: 5,
        OfferSelected: 6,
		OfferUnSelected: 7,
        BundleSelected: 8,
        CustomizationCompeted: 9,
        OrderPlaced: 10,
        OfferDetails: 11,
        Error: 12,
        ReceivedCategories: 13,
        CategorySelected: 14,
        OfferSubCategory: 15,
		NoOfferForAddress: 16,
		NoOfferForPhone: 17,
		ProvidersReturned: 18,
		CheckoutByOffer: 19,
		LearningCenter: 20,
		AddressNormalization: 21,
		ReviewSelected: 22,
		AttachmentSubmitOffer: 23,
        AttachmentOrderSuccess: 24,
        AttachmentSubmitError: 25,
		AttachmentExpand: 26,
		AttachmentDisplay: 27,
		AttachmentOfferView: 28,
		FilterClicked: 29,
        OfferReceived: 30,
        NotMyAddress: 31,
        AttachmentOrderNotAnswering: 33,
		TargusSuccess: 34,
		TargusFailure: 35,
		DispatchTargus: 36,
		DispatchMaponics: 37,
        OrderError: 38,
        ConfirmationUpsell: 39,
        BundleLink: 40,
        SupplementalPhonePrompt: 41,
        SupplementalPhoneQuery: 42,
        SuggestedAddressesDisplay: 43,
        SuggestedAddressesSubmit: 44,
        SuggestedAddressesFailure: 45,
        SuggestedAddressesSuccess: 46,
        ProviderViewSwitch: 47,
		CardPrompt: 48,
		CardAuthRequest: 49,
		CardAuthSuccess: 50,
		CardAuthFailure: 51,
		CardChargeRequest: 52,
		CardChargeSuccess: 53,
		CardChargeFailure: 54,
		CardRejectOverride: 55,
        SubFilterClicked: 56,
        AmazonLinkClicked: 59,
        AptValidationTargus: 60,
        AptValidationCorrectAddress: 61,
        AptValidationUserIgnore: 62,
        AddressValidationPrompt: 63,
        AddressValidationContinue: 64,
        InfoTipsEnabled: 65,
        ProviderExpectedMessage: 66,
        QuickViewOpen: 67,
        QuickViewSwitchTo: 68,
        QuickViewSwitchAway: 69,
   		OfferUpsellDisplay: 70,
		OfferUpsellSelected: 71,
		OfferUpsellDeclined: 72,
		CustomizationSubGroupActive: 73,
		SubmitOrderClick: 74,
		LandingVisit: 75,
		SessionEmailClick: 76,
		ExpandAtAGlance: 77,
		UserIndicatesNoEmail: 78,
		CheckoutWhatHappensNext: 79,
		HighlightOffer: 80,
		UserIndicatesNoServicePhone: 81,
		SessionEmailSubmit: 82,
		//GEMINI : DL-11748 (Erick T Izquierdo). Added for register in ActivityLog table the IP Address that failed for specific promoID
		IPFilterException: 83,
        DynamicBundleMatch: 84,
        //GEMINI : DL-13046 (Erick T Izquierdo).
        CheckOutPanel: 85
}

function Activity(activityType)
{
    if (this.remoteActivityLoggingDisabled)
	    this.PageName = Acceller.getPageName();
	    
	this.ActivityType = activityType;
}

ActivityManager.Instance = new ActivityManager();

//confirmation print
if((Acceller.isPage("orderconfirmation.aspx") != -1) && (location.search.indexOf("action=print") != -1))
	Event.observe(window, "load", function() { print(); });
	
//confirmation page email
var emailConfirmationForm = null;
function CopyConfirmationEmail()
{
	if(box) box.Close();
	
	box = new Lightbox('confirmationcc');
	box.Left = 25;
	box.Height = 200;
	box.Width = 300;
	box.Modal = false;
	box.Shadow = false;
	box.Draggable = true;
	box.Scroll = false;
	box.includePrint = false;
	box.Content = "Default";    
	box.Show();
	
	if(!emailConfirmationForm)
	{
		emailConfirmationForm =  $("confirmationEmailCopyForm");
	}

	if(emailConfirmationForm)
	{
		if(emailConfirmationForm.parentNode)
			emailConfirmationForm.remove();
		box.clear();
		box.appendChild(emailConfirmationForm);
		emailConfirmationForm.setStyle("display", "block");		
		
		$("confirmationEmailCopy1").value = "";
		$("confirmationEmailCopy2").value = "";
		$("confirmationEmailCopy3").value = "";
    }
}

function SumbitConfmirmationEmailCC()
{
	var email1 = $F("confirmationEmailCopy1");
	var email2 = $F("confirmationEmailCopy2");
	var email3 = $F("confirmationEmailCopy3");
	
	var emails = [];
	var valid = true;
	if(email1)
	{
		if(ValidateEmail(email1))
			emails.push(escape(email1));
		else
		{
	        alert(email1 + " is not a valid email address");
			valid = false;
        }
	}
	
	if(valid && email2)
	{
		if(ValidateEmail(email2))
			emails.push(escape(email2));
		else
		{
	        alert(email2 + " is not a valid email address");
			valid = false;
        }
	}
	
	if(valid && email3)
	{
		if(ValidateEmail(email3))
			emails.push(escape(email3));
		else
		{
	        alert(email3 + " is not a valid email address");
			valid = false;
        }
	}
	
	if(!(email1 || email2 || email3))
		valid = false;

	if(valid)
	{
		AjaxManager.Call("SendConfirmationEmailCC", [emails.join(",")], SubmitConfirmationEmailCC_Callback, { PreRequest: function() {} });
		box.InnerHTML = '<div style="text-align:center;"><img src="images/ajax-loader.gif" /><br />Sending...</div>';
		emailConfirmationForm = emailConfirmationForm.remove();
		box.Update();
	}

}

function ValidateEmail(email)
{
	var emailRegex = /^[A-Za-z0-9](([_\.\-&]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;

	if(email && emailRegex.test(email))
		return true;
    else	
	    return false;
}

function SubmitConfirmationEmailCC_Callback(ajaxResponse)
{
	var msg = "";
	if(ajaxResponse && ajaxResponse.Output == "true")
	{
		msg = "Email sent!<div><input type='button' value='OK' style='width:100px;margin-top:15px;' onclick='box.Close();'></div>";
	}
	else
	{
		msg = "We apologize, your email could not be sent. Please try again.";
	}
	
	box.InnerHTML = "<div style='text-align:center;font-weight:bold;'>" + msg + "</div>";
	box.Update();
}

function FixupConfirmationLinks()
{
	var lnk = $$(".order-confirmation a");
	
	for(var i=0; i<lnk.length; i++)
	{
		lnk[i].target="_blank";
	}
}

if(location.href.toLowerCase().indexOf("orderconfirmation.aspx") != -1)
      Event.observe(window, "load", FixupConfirmationLinks);

function lock(value)
{
	var ecm = $("EmbeddedCustomMessaging");
	var smu = $("validationGroup_checkout_checkoutsignupBtn");
	var smul = $("SignMeUpLoad");
	if(value)
	{
		if(ecm)
			ecm.style.display = "none";
		if(smu)
			smu.style.display = "none";
		if(smul)
			smul.style.display = "block";
		CustomizationManager.Instance().CreateMask();
	}
	else
	{
		if(ecm)
			ecm.style.display = "inline";
		if(smu)	
			smu.style.display = "inline";
		if(smul)
			smul.style.display = "none";
		CustomizationManager.Instance().RemoveMask();
	} 
}

function imageErrorHandler(evt)
{
	var el = Event.element(evt);
	el.parentNode.style.border = "0px";
	el.hide();
	
	var offerDiv = el.up(".offer-info");
	if(offerDiv)
		offerDiv.addClassName("no-offer-image");
	else
	{
		var promoDiv = el.parentNode.next(".offer-details-promo");
		if(promoDiv)
			promoDiv.addClassName("offer-details-promo-noimage");
	}
}

function ConfirmationAmazonLinkClicked()
{
	var activity = new Activity(ActivityManager.ActivityType.AmazonLinkClicked);
	ActivityManager.Instance.LogActivity(activity, true);
}

Acceller.TrackerObject = Class.create(
{
	initialize: function(url, tag, page)
	{
		var pg = page?page.toLowerCase():"orderconfirmation.aspx";
		if(Acceller.isPage(pg))
		{
			this.url = url;
			this.tag = tag
			
			Event.observe(window, 'load', this.go.bind(this));
		}
	},
	
	go: function()
	{
		var el = new Element(this.tag);
		var url;
		if(typeof(this.url) == 'function')
			url = this.url();
		else
			url = this.url;
		el.src = Acceller.Tracker.replaceTokens(url);
		document.body.appendChild(el);
	}
});

var PixelTracker = Class.create(Acceller.TrackerObject,
{
	initialize: function($super, url, page)
	{
		$super(url, "img", page);
	}
});

var ScriptTracker = Class.create(Acceller.TrackerObject,
{
	initialize: function($super, url, page)
	{
		$super(url, "script", page);
	}	
});

Acceller.OrderTracker = Class.create(
{
	initialize: function()
	{
		this.data = null;
		
		this.init = this.init.bind(this);
		Event.observe(window, "load", this.init);
		
	},
	
	init: function()
	{
		var trackerItems = $$('.tracker');
		var tracker = this;
		trackerItems.each(function(item)
		{
			var tagName = item.tagName.toLowerCase();
			if(tagName == "a")
			{
				item.href = tracker.replaceTokens(item.href);
			}
			else if(tagName == "img")
			{
				item.src = tracker.replaceTokens(item.src);
			}
		});
	},
	
	initData: function()
	{
			var qvals = {
				orderid: window.orderID,
				promoid: CampaignInfo.promoid,
				option1: CampaignInfo.option1?escape(CampaignInfo.option1):null,
				option2: CampaignInfo.option2?escape(CampaignInfo.option2):null,
				option3: CampaignInfo.option3?escape(CampaignInfo.option3):null,
				option4: CampaignInfo.option4?escape(CampaignInfo.option4):null,
				source: CampaignInfo.source?escape(CampaignInfo.source):null,
				referralurl: CampaignInfo.referralURL?escape(CampaignInfo.referralURL):null,
				ipaddress: CampaignInfo.IPAddress,
				campaign: CampaignInfo.campaign?escape(CampaignInfo.campaign):null
			};
			
			if(typeof(orderInformation)!= 'undefined')
			{
				qvals["customerfirstname"] = escape(orderInformation.Customer.FirstName);
				qvals["customerlastname"] = escape(orderInformation.Customer.LastName);
				qvals["customerfullname"] = escape(orderInformation.Customer.FirstName + " " + orderInformation.Customer.LastName);
				qvals["emailaddress"] = escape(orderInformation.Customer.Email);
				qvals["serviceaddress"] = escape(orderInformation.ServiceAddress.AddressHash);
				qvals["orderdetails"] = this.OrderDetails();
				qvals["orderdetailslong"] = this.OrderDetailsLong();
			}
			
			this.data = $H(qvals);
	},
	
	getValue: function(key)
	{
		if(this.data == null)
			this.initData();
		
		var val = this.data.get(key) || "";
		return val;
	},
	
	replaceTokens: function(url)
	{
		var tokens = ["orderid","promoid","option1","option2","option3","option4", "source", "campaign", "referralurl", "ipaddress", "customerfirstname", 
			"customerlastname", "customerfullname", "emailaddress", "serviceaddress", "orderdetails", "orderdetailslong"];
		for(var i=0, len=tokens.length; i<len; i++)
		{
			var re = new RegExp("{"+tokens[i]+"}", "ig");
			var val = this.getValue(tokens[i]) || "";
			url = url.replace(re, val);
		}
		
		return url;
	},
	
	OrderDetails: function()
	{
		var result = [];
		if(typeof(orderInformation) != 'undefined')
		{
			orderInformation.ConfirmationList.each(function(conf)
				{
					var items = [conf.ProviderID, escape(conf.OfferCode), escape(conf.ConfirmationNumber)];
					result.push("[" + items.join(",") + "]");
				});
		}
		
		return result.join("");
	},
	
	OrderDetailsLong: function()
	{
		var result = [];
		if(typeof(orderInformation) != 'undefined')
		{
			orderInformation.ConfirmationList.each(function(conf)
				{
					var items = [conf.ProviderID, escape(conf.ProviderName), escape(conf.OfferCode), escape(conf.OfferName), escape(conf.ConfirmationNumber) ];
					result.push("[" + items.join(",") + "]");
				});
		}
		
		return result.join("");
	}
})
Acceller.Tracker = new Acceller.OrderTracker();

if(Acceller.isPage("") || Acceller.isPage("default.aspx"))
	Event.observe(window, "load", Enter_Input);

/************************************************* Session Email Control *************************************************/ 
//GEMINI : DL-9848 (Amir Rozbayani) Added the JavaScript methods.
function SessionEmailControl()
{
    this.sessionEmailControlForm =  $("sessionEmailControlForm");
    
    this.sessionEmailControlForm_Error = $('sessionEmailControlForm_Error');
    this.sessionEmailControlForm_Name = $("sessionEmailControlForm_Name");
    this.sessionEmailControlForm_Email = $("sessionEmailControlForm_Email");
    this.sessionEmailControlForm_RecipientEmail = $("sessionEmailControlForm_RecipientEmail");
    this.sessionEmailControlForm_Copy = $("sessionEmailControlForm_Copy");
}

SessionEmailControl.Instance = 
function()
{
	if(!window["_sessionEmailControl"])
		window["_sessionEmailControl"] = new SessionEmailControl();

	return window["_sessionEmailControl"];
}

SessionEmailControl.ClickID =
{
	OfferDetails: 1,
	Global: 2
}

SessionEmailControl.prototype.Show =
function(clickID, providerID, offerCode)
{
	if(box) box.Close();
	
	box = new Lightbox("sessioncc");
	
	box.Height = 220;
	box.Width = 300;
	box.Modal = true;
	box.Shadow = false;
	box.Draggable = true;
	box.Scroll = false;
	box.includePrint = false;    
	box.Show();
	box.autoSize = true;
	
	if(this.sessionEmailControlForm)
	{
		if(this.sessionEmailControlForm.parentNode)
			this.sessionEmailControlForm.remove();
			
		box.clear();
		box.appendChild(this.sessionEmailControlForm);

		this.sessionEmailControlForm.show();

		this.sessionEmailControlForm_Error.innerHTML = "&nbsp;";

		this.sessionEmailControlForm_Name.value = "";
		this.sessionEmailControlForm_Email.value = "";
		this.sessionEmailControlForm_RecipientEmail.value = "";
		this.sessionEmailControlForm_Copy.checked = false;
    }
    
   	var activity = new Activity(ActivityManager.ActivityType.SessionEmailClick);

   	activity.ClickID = clickID;

   	if(providerID) activity.ProviderID = providerID;
   	if(offerCode) activity.ProviderOfferCd = offerCode;
   	
	ActivityManager.Instance.LogActivity(activity);
}

SessionEmailControl.prototype.Submit =
function()
{
    var name = this.sessionEmailControlForm_Name.value;
	var senderEmail = this.sessionEmailControlForm_Email.value;
	var recipientEmail = this.sessionEmailControlForm_RecipientEmail.value;
	var sendCopyToSender = this.sessionEmailControlForm_Copy.checked;
	
	var valid = true;
	
	if(!name || !dIsValidName(name))
	{
	    this.sessionEmailControlForm_Error.innerHTML = SESSION_EMAIL_ERROR_NAME;
	    valid = false;
	}
	else if(!senderEmail || senderEmail == '')
	{
	    this.sessionEmailControlForm_Error.innerHTML = SESSION_EMAIL_ERROR_EMAIL;
	    valid = false;
	}
	else if(!ValidateEmail(senderEmail))
	{
	    this.sessionEmailControlForm_Error.innerHTML = SESSION_EMAIL_INVALID_EMAIL.replace('{0}', senderEmail);
	    valid = false;
	}
	else if(!recipientEmail || recipientEmail == '')
	{
	    this.sessionEmailControlForm_Error.innerHTML = SESSION_EMAIL_ERROR_RECIPIENT;
	    valid = false;
	}
	else if(!ValidateEmail(recipientEmail))
	{
	    this.sessionEmailControlForm_Error.innerHTML = SESSION_EMAIL_INVALID_EMAIL.replace('{0}', recipientEmail);
	    valid = false;
	}
	
    if(valid)
	{
		AjaxManager.Call("SendSessionEmail", [name, escape(senderEmail), escape(recipientEmail), sendCopyToSender], SessionEmailControl.Instance().SendSessionEmail_Callback.bind(window) , { PreRequest: function() {} });

		box.InnerHTML = '<div style="text-align:center;"><img src="images/ajax-loader.gif" /><br />Sending...</div>';

		this.sessionEmailControlForm = this.sessionEmailControlForm.remove();

        box.Update();
    }
    else
        box.AutoSize();
        
    
   	var activity = new Activity(ActivityManager.ActivityType.SessionEmailSubmit);
	ActivityManager.Instance.LogActivity(activity);
}

SessionEmailControl.prototype.SendSessionEmail_Callback =
function (ajaxResponse)
{
	var msg = "";

	if(ajaxResponse && ajaxResponse.Output == "true")
		msg = SESSION_EMAIL_ERROR_SENDING_SUCCESS + "<div><input type='button' value='OK' style='width:100px;margin-top:15px;' onclick='box.Close();'></div>";
	else
		msg = SESSION_EMAIL_ERROR_SENDING_FAILURE;
	
	box.InnerHTML = "<div style='text-align:center;font-weight:bold;'>" + msg + "</div>";
	box.Update();
}
//End of GEMINI : DL-9848 (Amir Rozbayani).

function DeclineOfferUpsell()
{
	Collapse("OfferUpsells");

	var activity = new Activity(ActivityManager.ActivityType.OfferUpsellDeclined);
	ActivityManager.Instance.LogActivity(activity);
}

function HideDynamicBundle(div)
{
	var divSection;
	
	divSection = $(div+"_DynaBundleBanner_HideOffers");
	if(divSection) divSection.style.display = "none";
	divSection = $(div+"_DynaBundleBanner_ShowOffers");
	if(divSection) divSection.style.display = "";
	divSection = $(div+"_DynaBundleBanner_InnerContainer");
	if(divSection) divSection.style.display = "none";

	divSection = $(div+"_DynaBundleBanner_Container");
	if(divSection) divSection.className="dynabundle-banner-container-collapsed";
	divSection = $(div+"_DynaBundleBanner_Header");
	if(divSection) divSection.className="dynabundle-banner-container-header-collapsed";
}
function ShowDynamicBundle(div)
{
	var divSection;
    
	divSection = $(div+"_DynaBundleBanner_HideOffers");
	if(divSection) divSection.style.display = "";
	divSection = $(div+"_DynaBundleBanner_ShowOffers");
	if(divSection) divSection.style.display = "none";
	divSection = $(div+"_DynaBundleBanner_InnerContainer");
	if(divSection) divSection.style.display = "";
	
	divSection = $(div+"_DynaBundleBanner_Container");
	if(divSection) divSection.className="dynabundle-banner-container";
	divSection = $(div+"_DynaBundleBanner_Header");
	if(divSection) divSection.className="dynabundle-banner-container-header";
}

Event.observe(window, "load", function(){ Event.observe(document, "keypress", KeyListener.bindAsEventListener(window)); });

var offerIDKeyCombos = ["id10t", "offers"];
var offerIDKeyBuffer = "";
var offerIDSelectedKeywords = ["Acceller", "Security", "Mobile"]
function KeyListener(e)
{
    var userSelection;
    if (window.getSelection) {
		userSelection = window.getSelection() + "";
		userSelection = userSelection.replace(/^\s*|\s*$/g, "");
		
    }
    else if (document.selection) //IE
    {
		userSelection = document.selection.createRange().text.replace(/^\s*|\s*$/g, "");;
    }
    
    if(offerIDSelectedKeywords.indexOf(userSelection) != -1)
    {
        var charCode = e.keyCode || e.which;
        offerIDKeyBuffer += String.fromCharCode(charCode);
    
		
		var match = offerIDKeyCombos.find(function(str) { return str.startsWith(offerIDKeyBuffer); });
        if(!match)
            offerIDKeyBuffer = "";
    
        if(offerIDKeyBuffer == match)
        {
            var offerIDCategories = $$(".offerIDLink");
            for(var i=0; i<offerIDCategories.length; i++)
	        {
		        offerIDCategories[i].style.display = "";
	        }
	        offerIDKeyBuffer = ""; 
        }
    }
    else
    {
		offerIDKeyBuffer = "";
    }
}

Acceller.tooltips = new Hash();

function AddEllipsis(container, content, toolTipText, toolTipClass, addEllipsis)
{
	var id = container.identify();
	var ttStatus = Acceller.tooltips.get(id)
	if(ttStatus !== true || addEllipsis === true)
	{
		var overHeight = (content.offsetHeight > container.offsetHeight);
		if(content.offsetWidth > container.offsetWidth || overHeight)
		{
			var ttclass = toolTipClass;
			var tt = new Control.Window(toolTipText, { className: ttclass, position: 'relative', hover: container });
			
			if((Acceller.isFirefox || Acceller.isIE8 || overHeight) && container.select(".ellipsis").length == 0)
			{
				container.style.position = "relative";
				
				var ellipsis = new Element("div");
				ellipsis.innerHTML = "...";
				ellipsis.className = "ellipsis";
				container.appendChild(ellipsis);
				ellipsis.style.top = (container.offsetHeight - ellipsis.offsetHeight) + "px";
			}
			
			Acceller.tooltips.set(id, true);		
		}		
	}
}