// Add a trim function to the String object
String.prototype.trim=function(){
     var
         r=/^\s+|\s+$/,
         a=this.split(/\n/g),
         i=a.length;
     while(i-->0)
         a[i]=a[i].replace(r,'');
     return a.join('\n');
}

var successurl;
var zipcode;

var addtocartrelativetoid;

var zipentryblockpopupid;
var zipentryrelativetoid;

var removeitemrelativetoid;
var emptycartrelativetoid;
var checkcartrelativetoid;

function slideCompatiblePhones(elemID, accName) {
	var trigger = $("li"+elemID);
	if (trigger.className == "colapsed") {
		trigger.className = "expanded";
		new Effect.SlideDown("acc"+elemID, {duration: 0.3});
		if (typeof _hbLink != "undefined") {
			_hbLink('compatible+with',accName + '_on');
		}
	} else {
		trigger.className = "colapsed";
		new Effect.SlideUp("acc"+elemID, {duration: 0.3});
		if (typeof _hbLink != "undefined") {
			_hbLink('compatible+with',accName + '_off');
		}
	}
}

function getElementPosition(elem){
	var offsetTrail;
	if (typeof elem == 'string') {
		offsetTrail = $(elem);
	} else {
		offsetTrail = elem;
	}
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail){
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft,top:offsetTop};
}

function closePopup(popupid) {
	var popup = $(popupid);
	if (popup.style.position == 'absolute') {
		if (typeof _hbLink != "undefined") {
			_hbLink('close',popupid);
		}
		popup.style.display = 'none';
		//popup.style.height = 0;
	} else {
		new Effect.SlideUp(popupid);
		var errordiv = $('ziperror');
		errordiv.innerHTML = '';
		$(blkid).style.height = "140px";
	}

	if (!window.XMLHttpRequest) {
		$('windowFaderFrame').style.display = 'none';
	}
	currentpopupid = '';
}

function zipEntryBlock(blockid, relativetoid) {
	zipentryblockpopupid = blockid;
	zipentryrelativetoid = relativetoid;
	var block = $(blockid);
	if (block.style.position=='absolute') {
		popupChangeZipContent();
	} else {
		new Effect.SlideDown(blockid);
		if (typeof _hbPageView != "undefined") {
			_hbPageView('changezip_entry', '/popup');
		}
		//popup(blockid, relativetoid);
	}
}

/**
 * args:
 *	{
 *		url: The url to make the ajax call to. (required)
 *		postparams: A Hash() object of the post parameters to be sent in the ajax call. (optional)
 *		msgcontainerid: The id of the container div that will contain the response message from the
 *			ajax call. If not specified, the id of the container is assumed to be the popupid from
 *			the resulting jsonobj with +'content'. For example popupid='popupshort'. The id of the
 *			container will be 'popupshortcontent'. (optional)
 *		popupid: The id of the div that will be popped up. If no specified the popupid from the
 *			resulting jsonobj will be used. (optional)
 *		successcallback: Callback function to call when the jsonobj.code = 1. If not specified, then the javascript will
 *			load the document.location as specified by jsonobj.cartnexturl.
 *		prepopupback: Additional callback function to be called if jsonobj.code = -1 before the the popup function is called. (optional)
 *		postpopupcallback: Additional callback function to be called if jsonobj.code = -1 after the popup function is called. (optional)
 *		popupcallback: The callback function to be called to perform display of the message popup.
 *			If not specified, the default popup() function will be called. (optional)
 * 	}
 */
var cartCallPassthroughParams;
function cartCall(args) {
	new Ajax.Request(args.url,
		{
			parameters: args.postparams,
			method: 'post',
			onSuccess: function (res) {
				var txtres = res.responseText;
				if (txtres.isJSON()) {
					var jsonobj = txtres.evalJSON();
					cartCallPassthroughParams = $H(jsonobj.cartparams);
					if (jsonobj.code != '-1') {
						if (typeof(args.successcallback) == 'function') {
							args.successcallback(jsonobj);
						} else {
							//The cart operation was successfull. Perform
							//client side action based on the cartnexturl specified
							//in the resulting jsonobj.
							var cartnexturl = jsonobj.cartnexturl;
							if (cartnexturl.indexOf('javascript:') >= 0) {
								eval (cartnexturl.substring(11));
							} else if (cartnexturl != '') {
								document.location = cartnexturl;
							} else {
								document.location = document.location;
							}
						}
					} else {
						if (typeof(args.prepopupcallback) == 'function') {
							//A prepopup callback function was specified in the args.
							//Execute the callback function.
							args.prepopupcallback(jsonobj);
						}

						//The cart operation was not successfull. Perform
						//client side logic to display the error message.
						if (typeof(args.msgcontainerid) != 'undefined') {
							//The args.msgcontainerid was specified, this overrides
							//any content container specified by the jsonobj via jsonobj.popupid+'content'. Populate
							//the errmsg in the div container specified by args.msgcontainerid
							$(args.msgcontainerid).innerHTML = jsonobj.errmsg;
						} else if (jsonobj.popupid != '') {
							//Populate the content area of the popupid div specified by jsonobj.popupid
							$(jsonobj.popupid+'content').innerHTML = jsonobj.errmsg;
						}

						var popupid = '';
						if (typeof(args.popupid) != 'undefined') {
							//The args.popupid was specified, this overrides any
							//popupid speicfied by the jsonobj.popupid.
							popupid = args.popupid;
						} else if (typeof(jsonobj.popupid) != 'undefined' && jsonobj.popupid != '') {
							//Use the popupid specified in the jsonobj.
							popupid = jsonobj.popupid;
						}

						if (popupid != '' && typeof(args.relativetoid) != 'undefined' && args.relativetoid != '') {
							//A popupid was speicified. Display the popup div relative to the relativetoid specified
							//in args.relativetoid
							if (typeof args.popupcallback == 'function') {
								//A popup function was specified in the args. Use the specified
								//function instead of the default popup function.
								args.popupcallback(jsonobj);
							} else {
								//Call the default popup function
								popup(popupid, args.relativetoid);
							}

							if (typeof(_hbPageView) != 'undefined' &&
									typeof(jsonobj.hbxpn) != 'undefined' && jsonobj.hbxpn != '' &&
									typeof(jsonobj.hbxmlc) != 'undefined' && jsonobj.hbxmlc != '') {
								//An hbxpn and hbxmlc was specified, track the popup message in hbx using
								//the specified pn and mlc in the jsonobj.
								_hbPageView(jsonobj.hbxpn, jsonobj.hbxmlc);
							}
						}

						if (typeof(args.postpopupcallback) == 'function') {
							//An additional callback function was specified in the args.
							//Execute the callback function.
							args.postpopupcallback(jsonobj);
						}
					}
				}
			}
		}
	);
}

function popupChangeZipContent() {
	if (!isBlocked(zipentryrelativetoid)) {
		try {
			cartCall(
				{
					url: changezipcontenturl,
					relativetoid: zipentryrelativetoid,
					popupcallback: function (jsonobj) {
						//Override the popup call so we
						//can position it 20 pixels down
						//so it does not popup out of view.
						popup(jsonobj.popupid, zipentryrelativetoid, null, null, 0, 30);
					}
				}
			);
		} catch (err) {
			releaseBlock(zipentryrelativetoid);
		}
	}
}

var currentpopupid;
function popup(popupid,relativetoid,width,height,xoffset,yoffset) {
	//Check if xoffset/yoffset are passed in, if not, then set default values for each
	if(xoffset === undefined) {
		xoffset = 0;
	}
	if(yoffset === undefined) {
		yoffset = 0;
	}

	var relativeobj = $(relativetoid);
	var relativeto = getElementPosition(relativetoid);
	var popup = $(popupid);
	var popupcontainer = $(popupid+'container');
	if (!(width === undefined) && width != null) {
		if (popupcontainer) {
			popupcontainer.style.width = (width - 6)+'px';
		}
		popup.style.width = width+'px';
	}
	
	if (!(height === undefined) && height != null) {
		if (popupcontainer) {
			popupcontainer.style.height = (height - 6)+'px';
		}
		popup.style.height = height+'px';
	}

	popup.style.display = "block";	//temporarily turn element "on" so proper width/height calculations can work
	var left = 0;
	if(popup.style.width)
		var left = relativeto.left - parseInt(popup.style.width) + relativeobj.offsetWidth + xoffset;
	else
		var left = relativeto.left - parseInt(popup.offsetWidth) + relativeobj.offsetWidth + xoffset;
	var top = 0;
	if(popup.style.height)
		top = relativeto.top - parseInt(popup.style.height) + relativeobj.offsetHeight + yoffset;
	else
		top = relativeto.top - parseInt(popup.offsetHeight) + relativeobj.offsetHeight + yoffset;

	popup.style.display = "none";	//turn element "off" and let the Grow() function handle the display
	popup.style.left = left+'px';
	popup.style.top = top+'px';

	new Effect.Grow(popupid, {direction: 'bottom-right', duration: '0.5', afterFinish: function () { releaseBlock(relativetoid); currentpopupid = popupid;}});

	//this addresses form elements "bleeding through" dhtml popups in ie6.
	//XMLHttpRequest doesn't exist for ie6 and below.
	if (!window.XMLHttpRequest) {
		$('windowFaderFrame').style.display = 'block';
		$('windowFaderFrame').style.width = popup.style.width;
		$('windowFaderFrame').style.height = popup.style.height;
		$('windowFaderFrame').style.top = popup.style.top;
		$('windowFaderFrame').style.left = popup.style.left;
		$('windowFaderFrame').style.zIndex = 0;
	}
}
function setLocationPopup(formobj, url) {
	try {
		if (formobj.changezipcode.value.trim() != '' && formobj.changezipcode.value != '(enter your zip code)') {
			var hashedparams = new Hash();
			hashedparams.set('zipcode', formobj.changezipcode.value);

			cartCall(
				{
					url: url,
					postparams: hashedparams,
					relativetoid: zipentryrelativetoid
				}
			);
		}
	} catch (exc) {}
}

function setLocation(tzipcode, url, successurl, ziperrordivid) {
	try {
		if (tzipcode.trim() != '' && tzipcode != '(enter your zip code)') {
			zipcode = tzipcode;

			var hashedparams = new Hash();
			hashedparams.set('zipcode', zipcode);

			cartCall(
				{
					url: url,
					postparams: hashedparams,
					postpopupcallback: function(jsonobj) {
						if (blkid != "") {
							var obj = $(blkid);
							//Hack to prevent text overflow
							if (blkid != "changelocationpopup") {
								obj.style.height = "1%";
							}
						}
						var errordiv = $(ziperrordivid);
						errordiv.innerHTML = jsonobj.errmsg;
						errordiv.style.display = "block";
					}
				}
			);
		}
	}
	catch (exc) {}
}

/*
 * ==========================================================
 * CART FUNCTIONS
 * ==========================================================
 */

function setHBXPopupPageView(result) {
	var hbxpn = result.getElementsByTagName('hbxpn').item(0).firstChild.nodeValue;
	var hbxmlc =  result.getElementsByTagName('hbxmlc').item(0).firstChild.nodeValue;
	if (typeof _hbPageView != "undefined") {
		_hbPageView(hbxpn, hbxmlc);
	}
}

function cartCheckout(url, relativetoid) {
	if (!isBlocked(relativetoid)) {
		try {
			cartCall(
				{
					url: url,
					relativetoid: relativetoid
				}
			);
		} catch (err) {
			releaseBlock(relativetoid);
		}
	}
}

var blockTable = new Hash();
function isBlocked(elem) {
	try {
		var bttn;
		if (typeof elem == "string") {
			bttn = $(elem);
		} else {
			bttn = elem;
		}
		if (bttn.id) {
			if (!blockTable.get(bttn.id)) {
				blockTable.set(bttn.id, "unblocked");
			}
			if(typeof blockTable.get(bttn.id) != "string") {
				return true;
			} else {
				blockTable.set(bttn.id, bttn);
				return false;
			}
		}
	} catch (err) {}
	return false;
}

function releaseBlock(elem) {
	try {
		var bttn;
		if (typeof elem == "string") {
			bttn = $(elem);
		} else {
			bttn = elem;
		}
		if (bttn.id) {
			blockTable.set(bttn.id, "unblocked");
		}
	} catch (err) {}
}

function skipAccessories(url, relativetoid) {
	cartCall(
		{
			url: url,
			relativetoid: relativetoid
		}
	);
}

function addAccessories(url, relativetoid, itemcode, itemtype, isdata, packageid, context) {
	addtocartrelativetoid = relativetoid;
	var accessoriesForm = $('AccessoryAddtoCartForm');
	accessoriesForm.relativetoid.value = relativetoid;
	accessoriesForm.itemtype.value = itemtype;

	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			postparams: Form.serialize(accessoriesForm)
		}
	);

}

function addAccessory(url, relativetoid, itemcode, itemtype, isdata, packageid, context) {
	addtocartrelativetoid = relativetoid;
	var hashedparams = new Hash();
	hashedparams.set('relativetoid', relativetoid);
	hashedparams.set('itemtype', itemtype);
	hashedparams.set('context', context);
	hashedparams.set('itemcode', itemcode);
	hashedparams.set('itemcodes', itemcode);
	hashedparams.set('quantity_'+itemcode, '1');

	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			postparams: hashedparams
		}
	);

}

/**
 * Add the item to the cart using the passed URL.
 * url: URL to make the ajax call to.
 * hashedparams: Hash object of post data. If not specified, then the Hash object
 *	used in the originating call will be used.
 *
 */
function addToCartPassThrough(url, itemaction, hashedparams) {

	if (typeof(hashedparams) == 'undefined' || hashedparams == null)
	{
		hashedparams = cartCallPassthroughParams;
	}
	
	if (typeof(itemaction) != 'undefined' && itemaction != null)
	{
		hashedparams.set('itemaction', itemaction);
	}
	
	addtocartrelativetoid = hashedparams.get('relativetoid');
	if (!isBlocked(addtocartrelativetoid)) {
		try {
			cartCall(
				{
					url: url,
					postparams: hashedparams,
					relativetoid: addtocartrelativetoid,
					popupcallback: function(jsonobj) {
						//Position the popup so that it is 10 px to the right so
						//it does not grow past the left margin of the site for
						//cases where the addtocart button is in the far left column.
						popup(jsonobj.popupid, addtocartrelativetoid, null, null, 10, 0);
					},
					postpopupcallback: function(jsonobj) {
						new PeriodicalExecuter(
								function (pe) {
									if ($('addtocartzipform')) {
										Form.focusFirstElement('addtocartzipform');
									}
									pe.stop();
								}, 1.5);
					}
				}

			);

		} catch (err) {
			releaseBlock(addtocartrelativetoid);
		}
	}
} 

function addToCart(url, relativetoid, itemcode, itemtype, isdata, packageid, context, itemaction) {
	var hashedparams = new Hash();
	hashedparams.set('relativetoid', relativetoid);
	hashedparams.set('packageid', packageid);
	hashedparams.set('itemcode', itemcode);
	hashedparams.set('itemtype', itemtype);
	hashedparams.set('isdata', isdata);
	hashedparams.set('context', context);
	hashedparams.set('itemaction', itemaction);
	addToCartPassThrough(url, null, hashedparams);
}

function addToCartReplaceInPackage(url, packageid) {
	//Add the packageid as an argument to the originally posted params
	cartCallPassthroughParams.set('packageid', packageid);
	addToCartPassThrough(url);
}

function addToCartZipEntry(formobj, url) {
	try {
		if (formobj.zipcode.value != '(enter your zip code)') {
			cartCall(
				{
					url: url,
					postparams: Form.serialize(formobj),
					relativetoid: addtocartrelativetoid
				}
			);
		}
	} catch (err) {}
}

function cartNextAction(cartnexturlelem) {
	var cartnexturl = '';
	if (cartnexturlelem.hasChildNodes()) {
		cartnexturl = cartnexturlelem.firstChild.nodeValue;
	}
	if (cartnexturl.indexOf('javascript:') >= 0) {
		eval (cartnexturl.substring(11));
	} else if (cartnexturl != '') {
		document.location = cartnexturl;
	} else {
		document.location = document.location;
	}
}

function removeCartItem(url, itemid) {
	var hashedparams = new Hash();
	hashedparams.set('itemid', itemid);

	cartCall(
		{
			url: url,
			postparams: hashedparams
		}
	);

}

function confirmRemoveItem(url, itemid) {
	removeitemrelativetoid = 'cartrm_'+itemid;
	if (!isBlocked(removeitemrelativetoid)) {
		try {
			var hashedparams = new Hash();
			hashedparams.set('itemid', itemid);

			cartCall(
				{
					url: url,
					relativetoid: removeitemrelativetoid,
					postparams: hashedparams
				}
			);

		} catch (err) {
			releaseBlock(removeitemrelativetoid);
		}
	}
}

function confirmEmptyCart(url, relativetoid) {
	//document.body.style.cursor = 'wait';
	if (!isBlocked(relativetoid)) {
		cartCall(
			{
				url: url,
				relativetoid: relativetoid,
				prepopupcallback: function(jsonobj) {
					$('popup').style.display = "none";
				}
			}
		);

	}
}

function emptyCart(url, relativetoid) {
	//document.body.style.cursor = 'wait';
	if (!isBlocked(relativetoid)) {
		cartCall(
			{
				url: url,
				relativetoid: relativetoid,
				prepopupcallback: function(jsonobj) {
					$('popup').style.display = "none";
				}
			}
		);

	}
}

function doShortPopup(url, relativetoid) {
	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			prepopupcallback: function(jsonobj) {
				$('popup').style.display = "none";
			}
		}
	);
}

function emptyCartWithZip(url, zipcode, relativetoid) {
	emptycartrelativetoid = relativetoid;
	var hashedparams = new Hash();
	hashedparams.set('zipcode', zipcode);

	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			postparams: hashedparams
		}
	);

}

function activatePackage(url, packageid) {
	var hashedparams = new Hash();
	hashedparams.set('packageid', packageid);
	new Ajax.Request(url,
		{
			parameters: hashedparams,
			method: 'post',
			onSuccess: function (res) {
				//Do nothing with the response.
			}
		}
	);
}

function nextCartStep(url, relativetoid) {
	cartCall(
		{
			url: url,
			relativetoid: relativetoid
		}
	);
}

//=============================================================
// BEGIN MY ACCOUNT FUNCTIONS
//=============================================================
function validateAccountLogin(url, relativetoid, formobj) {
	checkcartrelativetoid = relativetoid;
	if (!isBlocked(checkcartrelativetoid)) {
		try {
			var hashedparams = new Hash();
			hashedparams.set('uid',formobj.uid.value);
			hashedparams.set('pwd',formobj.pwd.value);

			cartCall(
				{
					url: url,
					relativetoid: relativetoid,
					postparams: hashedparams,
					successcallback: function(jsonobj) {
						$('myaccountlogin').submit();
					},
					prepopupcallback: function(jsonobj) {
						$(jsonobj.popupid).style.zIndex = '99';
					}
				}
			);

		} catch (err) {
			releaseBlock(checkcartrelativetoid);
		}
	}
}

function clearCartLogin(url) {
	cartCall(
		{
			url: url,
			relativetoid: checkcartrelativetoid,
			successcallback: function(jsonobj) {
				$('myaccountlogin').submit();
			},
			prepopupcallback: function(jsonobj) {
				$(jsonobj.popupid).style.zIndex = '99';
			}
		}
	);
}

function popupMyAccountLogin(url, relativetoid) {
	new Ajax.Request(url, {
		method: 'post',
		onSuccess: function (res) {
			var result = res.responseText;
			$("popupcontent").innerHTML = result;
			popup("popup", relativetoid);
		}
	});
}
//=============================================================
// END MY ACCOUNT FUNCTIONS
//=============================================================

function expireCart() {
	var date = new Date();
	date.setTime(date.getTime()+(-7*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = "MyCricketCartID="+expires+"; path=/; domain=.mycricket.com";
}

/* RS - COMMENTED. CARTS WILL NOW HAVE A 10 DAY EXPIRATION.
function startCartExpirer() {
	//Set a 3 hour timer to expire the user's Cart Cookie of inactivity.
	Event.observe(window, 'load', function() {
	    new PeriodicalExecuter(function(pe) {
	            expireCart();
	            pe.stop(); // stop the updater
	     }, 10800);
	});
}
*/

function setIntention(relativetoid, url, formobj) {
	$('popup').hide();

	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			postparams: Form.serialize(formobj)
		}
	);

}

/*
 * ==========================================================
 * END CART FUNCTIONS
 * ==========================================================
 */

/*
 * ==========================================================
 * ASPECT IMAGE POPUP FUNCTIONS AND PLAN COMPARISON POPUP FUNCTIONS
 * ==========================================================
 */
 var aspectImagePopup = null;
 var aspectImgHider = null;
 var isPageLoaded = false;

 Event.observe(
 	window,
 	'load',
 	function () {
 		isPageLoaded = true;
 	}
 );

 function aspectImageOut() {
 	if (aspectImagePopup) {
 		aspectImagePopup.stop();
 		hideAspectImage();
 	}
 }

 function showAspectImage(relativeobj, imguri, phonename) {
 	if (isPageLoaded) {
	 	aspectImagePopup = new PeriodicalExecuter(
	 		function (ppe) {
	 			var popup = $('popup');
	 			$('popupcontent').update('<img id="aspectimage" src="' + imguri + '" alt=""/>');
 				popup.style.display = "block";
				var width = $('aspectimage').offsetWidth;
				var height = popup.offsetHeight;
				popup.style.display = "none";
				//if correct width isn't availabe keep trying periodic execution until it's correctly set (width less than 30 causes weird behavior in IE)
				if(width > 30) {
					var relativeto = getElementPosition(relativeobj);
					var left = relativeto.left + relativeobj.offsetWidth;
					var top = relativeto.top;
					popup.style.left = left+'px';
					//prevent popup from displaying below browser window
					var scrollOffsets = document.viewport.getScrollOffsets();
					if((top - scrollOffsets.top + height) > document.viewport.getHeight() )
						popup.style.top = (top-height)+'px';
					else
						popup.style.top = top+'px';
					popup.style.width = (width + 30) + 'px';
					new Effect.Grow('popup', {direction: 'top-left', duration: '0.3'});
					ppe.stop();
				}
			}, 0.4
		);
	}
 }

function hideAspectImage() {
	if (isPageLoaded) {
		aspectImgHider = new PeriodicalExecuter(
	 		function (ppe) {
				var popup = $('popup');
			 	popup.style.display = 'none';
			 	popup.style.top = '0';
			 	popup.style.left = '0';
				ppe.stop();
			}, 0.4
		);
	}
}

var comparePlansRelativeto;
function comparePlans(relativeto, url, planname) {
	comparePlansRelativeto = relativeto;
	if (!isBlocked(relativeto)) {
		try {
			if (typeof _hbLink != "undefined") {
				_hbLink('compareplans', planname);
			}

			var hashedparams = new Hash();
			hashedparams.set('relativetoid',relativeto.id);

			cartCall(
				{
					url: url,
					relativetoid: relativeto.id,
					postparams: hashedparams,
					popupcallback: function(jsonobj) {
						if (comparePlansRelativeto.id.match("planscomparison_lnk_")) {
							popupComparePlansLnk(jsonobj.popupid, comparePlansRelativeto.id);
						} else {
							popup(jsonobj.popupid, comparePlansRelativeto.id);
						}
					},
					postpopupcallback: function(jsonobj) {
						new PeriodicalExecuter(
						function (pe) {
							if ($('compareplanszipform')) {
								Form.focusFirstElement('compareplanszipform');
							}
							pe.stop();
						}, 1.5);
					}
				}
			);

		} catch (err) {
			releaseBlock(relativeto);
		}
	}
}

function comparePlansZipEntry(frm, url) {
	try {
		var hashedparams = new Hash();
		hashedparams.set('relativetoid',frm.relativetoid.value);
		hashedparams.set('zipcode',frm.zipcode.value);

		cartCall(
			{
				url: url,
				relativetoid: comparePlansRelativeto.id,
				postparams: hashedparams,
				popupcallback: function(jsonobj) {
					if (comparePlansRelativeto.id.match("planscomparison_lnk_")) {
						popupComparePlansLnk(jsonobj.popupid, comparePlansRelativeto.id);
					} else {
						popup(jsonobj.popupid, comparePlansRelativeto.id);
					}
				},
				postpopupcallback: function(jsonobj) {
					new PeriodicalExecuter(
					function (pe) {
						if ($('compareplanszipform')) {
							Form.focusFirstElement('compareplanszipform');
						}
						pe.stop();
					}, 1.5);
				}
			}
		);
	} catch (err) {
		alert(err.message);
	}
}

function popupComparePlansLnk(popupid, relativetoid) {
	var relativeobj = $(relativetoid);
	var relativeto = getElementPosition(relativetoid);
	var popup = $(popupid);
	var left = relativeto.left + 6;
	popup.style.display = "block";	//turn element on temporarily
	var top = relativeto.top - parseInt(popup.offsetHeight) + relativeobj.offsetHeight + 6;
	popup.style.display = "none";	//turn element back off
	popup.style.left = left+'px';
	popup.style.top = top+'px';
	new Effect.Grow(popupid, {direction: 'bottom-left', duration: '0.5', afterFinish: function () { releaseBlock(relativetoid); }});
}

function marketaction(url, relativetoid, args) {
	//create array of name/value pairs for the ajax request
	var postparams = new Hash();
	if (args === undefined) {
		postparams.set('relativetoid', relativetoid);
	} else {
		postparams = new Hash(Form.serialize(args, true));
		if (relativetoid != '') {
			postparams.set('relativetoid', relativetoid);
		}
	}
	postparams.set('url', url);
	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			postparams: postparams
		}
	);

}

/*
 * ==========================================================
 * END ASPECT IMAGE POPUP FUNCTIONS AND PLAN COMPARISON POPUP FUNCTIONS
 * ==========================================================
 */

 /*
 * ==========================================================
 * 360 PHONE VIEW POPUP FUNCTIONS
 * ==========================================================
 */
 var isDomRendered_popup360Tour = false;
 function popup360Tour(relativetoid, swfpath) {
 	_hbLink_('360Tour');
 	if (DetectFlashVer(7,0,0)) {
 		if (!isDomRendered_popup360Tour) {
 			var popup360 = '<div id="popup360" class="dropshadow" style="display: none; position: absolute; top: 0; left: 0">';
 			popup360 += '<div class="popupcontainer">';
			popup360 += '<div class="popupheader">&nbsp;</div>';
			popup360 += '<div style="padding: 1em 1em 0 1em; border-bottom: 1px solid #DADADA; height:35px;">';
			popup360 += '<span class="theme-color" style="font-size: 18px;">Take It For a Spin</span>';
			popup360 += '<a class="closetour-btn cssbutton block" style="position:relative; top:-20px; left:210px;" onclick="close360Popup(\'popup360\');">Close Tour</a>';
			popup360 += '</div>';
			popup360 += '<div id="popupcontent360"></div>';
			popup360 += '</div>';
			popup360 += '</div>';
			Element.insert($$('body')[0], popup360);
 			isDomRendered_popup360Tour = true;
 		}
 		
 		var so = new SWFObject(swfpath, "Tour360", "320", "360", "0", "#FFFFFF");
 		so.useExpressInstall("swfobject/expressinstall.swf");
 		so.addParam("scale","noscale");
 		so.addParam("wmode","transparent");
 		so.addParam("wmode","transparent");
 		so.write("popupcontent360");
		
 		popup("popup360",relativetoid, 330, 428, 250, 0);
 	} else {
 		$('popupcontent').innerHTML = "<p>You must have Flash version 7 or greater installed to view the 360 tour.</p>";
 		popup("popup", relativetoid, 280, null, 200, 0);
 	}

 }

 function close360Popup(popupid) {
 	$("popupcontent360").update();
 	$(popupid).style.display = "none";
 }

 /*
 * ==========================================================
 * END 360 PHONE VIEW POPUP FUNCTIONS
 * ==========================================================
 */
function logoutMyAccount(url) {
	document.location = url + '&src=' + srcURL;
}

//=============================================================
// BEGIN SHOP NOW FUNCTIONS
//=============================================================
var isDomRendered_shopNow = false;

function shopNow(url, relativetoid, itemcode) {
	var postparams = new Hash();
	postparams.set('itemcode', itemcode);
	postparams.set('relativetoid', relativetoid);
	postparams.set('itemtype', 'phone');
	
	if (!isDomRendered_shopNow) {
		var popupShopNow = '<div id="popupShopNow" class="dropshadow" style="display: none; position: absolute; top: 0; left: 0; width: 300px;">';
		popupShopNow += '<div class="popupcontainer">';
		popupShopNow += '<div class="popupheader"><a class="popupclosebtn" href="javascript:closePopup(\'popupShopNow\')"><img class="" src="'+IMAGES_ROOT+'119_skin/buttons/img-close.gif" width="10" height="11"/>CLOSE</a></div>';
		popupShopNow += '<div id="popupShopNowcontent" class="popupcontent"></div>';
		popupShopNow += '</div>';
		popupShopNow += '</div>';
		Element.insert($$('body')[0], popupShopNow);
		isDomRendered_shopNow = true;
 	}
	
	cartCall(
		{
			msgcontainerid: 'popupShopNowcontent',
			popupid: 'popupShopNow',
			url: url,
			relativetoid: relativetoid,
			postparams: postparams
		}
	);
}

function shopNowSetZip(url, formobj) {
	cartCall(
		{
			msgcontainerid: 'popupShopNowcontent',
			popupid: 'popupShopNow',
			url: url,
			postparams: new Hash(Form.serialize(formobj, true))
		}
	);
}
//=============================================================
// END SHOP NOW FUNCTIONS
//=============================================================

// ==========================================================
// PAYGo activation functions
// ==========================================================
function validateESN(url, relativetoid, formdata, smapHash) {
	var postparams = $H( Form.serialize(formdata, true) );
	postparams.set('itemtype','esn');
	postparams.set('relativetoid', relativetoid);
	//swap button with spinner
	$(relativetoid).removeClassName('next-btn');
	$(relativetoid).addClassName('ajax-spinner');
	cartCall(
		{
			url: url,
			relativetoid: relativetoid,
			postparams: postparams,
			postpopupcallback: function(jsonobj) {
				//restore button
				$(relativetoid).removeClassName('ajax-spinner');
				$(relativetoid).addClassName('next-btn');
				
				refreshSmap(smapHash);
			}
		}
	);
}

function refreshSmap(smapHash) {
	//update captcha image, question and user's selections
	new Ajax.Updater(smapHash['qContainer'], smapHash['qURL'], {
		onComplete: function() {
			date = new Date();
			$('captchabg').style.backgroundImage="url(" + smapHash['imageURL'] + "?t=" + date.getTime() + ")";
			$$(smapHash['selector']).invoke('hide');
			$(smapHash['cVal']).value = 0;
		}
	});
}

function cancelPAYGoActivationConfirm(url, relativetoid) {
	if (!isBlocked(relativetoid)) {
		try {
			var postparams = new Hash();
			postparams.set('relativetoid', relativetoid);
			cartCall(
				{
					url: url,
					relativetoid: relativetoid,
					postparams: postparams,
					popupcallback: function(jsonobj) {
						popup(jsonobj.popupid, relativetoid, null, null, 190, 10);
					}
				}
			);
		}catch(err){
			releaseBlock(relativetoid);
		}
	}
}

function cancelPAYGoActivation(url) {
	var relativetoid = cartCallPassthroughParams.get('relativetoid');
	cartCall(
			{
				url: url,
				relativetoid: relativetoid,
				prepopupcallback: function(jsonobj) {
					closePopup('popup');
				},
				popupcallback: function(jsonobj) {
					popup(jsonobj.popupid, relativetoid, null, null, 190, 10);
				}
			}
		);
}

function addItemCancelPAYGoActivation(url) {
	cartCall(
			{
				url: url,
				relativetoid: cartCallPassthroughParams.get('relativetoid'),
				postparams: cartCallPassthroughParams
			}
		);
}
// ==========================================================
// End PAYGo activation functions
// ==========================================================
