//--------------------------------------------------------------------------------------------------
// PocketGear.com/Motricity Javacript 2.2.0.4 2008.03
// Developed by Noel Fiser, noel.fiser@motricity.com
// Copyright 2008, All Rights Reserved.
//--------------------------------------------------------------------------------------------------

var YUE = YAHOO.util.Event;
var YUD = YAHOO.util.Dom;
var YUC = YAHOO.util.Connect;
var YUEL = YAHOO.util.Element;

var syncNameLabels = Array(); 
syncNameLabels.push(Array("Windows Mobile PocketPC","Owner Name")); 
syncNameLabels.push(Array("Windows Mobile Smartphone","Owner Name")); 
syncNameLabels.push(Array("PalmOS","HotSync ID")); 
syncNameLabels.push(Array("RIM","Personal ID Number (PIN)"));

var cartItems = {
	init: function() {
		pr = YUD.getElementsByClassName("purchaseReceipt","div");
		if (pr.length > 0) return true;
		
		r = YUD.getElementsByClassName("row","div");
		for (i = 0; i < r.length; i++) {
			if (YUD.hasClass(r[i],"itemInCart")) {
				a = YUD.getElementsByClassName("a","div",r[i])[0];
				b = YUD.getElementsByClassName("b","div",r[i])[0];
				c = YUD.getElementsByClassName("c","div",r[i])[0];

				iTitle = YUD.getElementsByClassName("itemTitle","div",r[i])[0];
				em = "em";
				if (iTitle) em = YUD.getStyle(iTitle,"height");
				
				if (em != "auto") {
					if (em.indexOf("em") != -1) em = 12;
					else em = em.replace("px","") / 1.5;
	
					iTitle.style["height"] = "auto";
					YUD.setStyle(iTitle,"height","auto");
					h = iTitle.offsetHeight; if (!h) h = iTitle.style.pixelHeight;

					h = h + 16;
					h = Math.round((h / em)*100)/100 + "em";
	
					YUD.setStyle(c,"height",h);
					YUD.setStyle(b,"height",h);
					YUD.setStyle(a,"height",h);
					YUD.setStyle(r[i],"height",h);
				}
			}
		}
	}
}

var messaging = {
	divID: "messaging",
	div: null,
	options: Array(),

	init: function() {
		// check for an "messaging" DIV in the page. The structure of this DIV should be:
		//	<messaging>
		//		<message type="information|confirmation|error|noresults">
		//			<msgText />
		//			<highlight /> (repeatable)
		//		</message> (repeatable)
		//	</messaging>

		messaging.options = Array("information", "error", "confirmation", "noresults");

		messaging.div = document.getElementById(messaging.divID);
		if (messaging.div) {
			md = messaging.div;
			p = md.parentNode;

			m = YUD.getElementsByClassName("message","div",messaging.div);
			for (i = 0; i < m.length; i++) {
				mType = m[i].getAttribute("type"); if (!mType) mType = "information";

				if (messaging.validateOption(mType)) {
					t = YUD.getElementsByClassName("msgText","div",m[i])[0];

					// if there's a message then create the message area at the top of the page
					if (t) {
						msg = messaging.shortenUrl(t.cloneNode(true));
			
						d = messaging.createWrapper(mType); // creates the space for the error message and puts it in the document

						if (d) {
							icon = document.createElement("img");
							icon.setAttribute("src", "images/messaging/icon-" +mType+ ".gif");
							YUD.addClass(icon,"icon");
							d.appendChild(icon);
	
							d.appendChild(msg);
							
							messaging.resize(d,75);
						}
					}
				}

				// highlight the proper fields
				h = YUD.getElementsByClassName("highlight","div",m[i]);
				for (j = 0; j < h.length; j++) {
					inp = document.getElementById(h[j].innerHTML);
					if (inp) {
						iNN = inp.nodeName.toLowerCase();
						if (j == 0) if (iNN == "input" || iNN == "select" || iNN == "textarea") { inp.focus(); inp.select(); } //focus on the first highlight

						while (!(YUD.hasClass(inp,"row")  || YUD.hasClass(inp,"section")) && inp.nodeName != "body") inp = inp.parentNode;
						if (inp.nodeName != "body") YUD.addClass(inp,"msgHighlight");
					}
				}
			}

			md = document.getElementById(messaging.divID);
			md.parentNode.removeChild(md);
		}
	},

	resize: function(d, min) {
		// check the height of the div and resize if necessary
		dHeight = d.style.pixelHeight; dType = "style.pixelHeight"; if (!dHeight) { dHeight = d.offsetHeight; dType = "offsetHeight"; }
		if (dHeight < min) {
			c = d;
			b = c.parentNode;
			a = b.parentNode;
			d = a.parentNode;

			YUD.setStyle(a, "height", min+"px");
			YUD.setStyle(b, "height", min+"px");
			YUD.setStyle(c, "height", min+"px");
			YUD.setStyle(d, "height", min+"px");
		}
	},

	shortenUrl: function(msg) {
		urls = YUD.getElementsByClassName("url","span",msg);
		for (i=0; i<urls.length; i++) {
			url = urls[i].innerHTML;
			len = url.length;
			if (len > 40) {
				fullUrl = document.createElement("span");
				YUD.addClass(fullUrl,"fullUrl");
				fullText = document.createTextNode(url);
				fullUrl.appendChild(fullText);
				YUD.setStyle(fullUrl,"margin-left","-4px");
				
				url = url.substr(0,38)+"...";
				urls[i].innerHTML = url;
				urls[i].insertBefore(fullUrl,urls[i].childNodes[0]);
				
				YUE.addListener(urls[i],"mouseover", messaging.toggleUrl, Array(fullUrl, "on"));
				YUE.addListener(urls[i],"mouseout", messaging.toggleUrl, Array(fullUrl, "off"));
			}
		}
		return msg;
	},
	toggleUrl: function(e, obj) {
		sp = obj[0]; state = obj[1];
		if (state == "on") {
			YUD.setStyle(sp,"display","block");
		} else {
			YUD.setStyle(sp,"display","none");
		}
	},
	
	createWrapper: function(mType) {
		a = document.createElement("div");
		YUD.addClass(a, "a");
		b = document.createElement("div");
		YUD.addClass(b, "b");
		c = document.createElement("div");
		YUD.addClass(c, "c");

		d = document.createElement("div");
		YUD.addClass(d, "message");
		YUD.addClass(d, "msg_"+mType);

		b.appendChild(c);
		a.appendChild(b);
		d.appendChild(a);

		B2 = document.getElementById("pg_columnB2");
		if (B2) {
			target = null;
			
			t = YUD.getElementsByClassName("title","div",B2);
			if (t.length > 0) if (t[0].parentNode.parentNode.parentNode.parentNode == B2) target = t[0];
			t = YUD.getElementsByClassName("title","div",B2);
			if (t.length > 0) if (YUD.hasClass(t[0].parentNode,"item") && YUD.hasClass(t[0].parentNode,"productDetail")) target = t[0];
			b = YUD.getElementsByClassName("breadcrumb","ul",B2);
			if (b.length > 0) target = b[0];
			
			if (target) {
				target.appendChild(d);
			} else { 
				B2a = YUD.getElementsByClassName("a","div",B2);
				if (B2a.length > 0) if (B2a[0].parentNode == B2) B2 = B2a[0];
				B2b = YUD.getElementsByClassName("b","div",B2);
				if (B2b.length > 0) if (B2b[0].parentNode == B2) B2 = B2b[0];
				B2c = YUD.getElementsByClassName("c","div",B2);
				if (B2a.length > 0) if (B2c[0].parentNode == B2) B2 = B2c[0];

				kids = B2.childNodes;
				newKids = Array();
				newKids.push(d);
				for (i=0;i<kids.length;i++) {
					newKids.push(kids[i]);
				}
				for (i=0;i<newKids.length;i++) B2.appendChild(newKids[i]);
			}
			
			return c;
		}
	},

	validateOption: function(opt) {
		for (i = 0; i < messaging.options.length; i++) {
			if (opt == messaging.options[i]) return true;
		}
		return false;
	}
}

var collapse = {
	init: function() {
		col = YUD.getElementsByClassName("collapsible","div");
		for (i=0;i<col.length;i++) {
			h1 = YUD.getElementsBy(alwaysTrue,"h1",col[i])[0];
			if (h1) YUE.addListener(h1,"click",collapse.toggle);
			if (h1) YUE.addListener(h1,"mouseover",collapse.toggleClass);
			if (h1) YUE.addListener(h1,"mouseout",collapse.toggleClass);
		}
		collapse.buildInternal();
	},
	toggle: function(e,p) {
		if (!p) p = this.parentNode;
		d = YUD.getElementsBy(alwaysTrue,"div",p)[0];

		pHeight = p.style.pixelHeight; if (!pHeight) pHeight = p.offsetHeight;

		disp = YUD.getStyle(d,"display");
		if (disp == "block") { disp = "none"; act = "shrink"; } else { disp = "block"; act = "grow"; }
		YUD.setStyle(d,"display",disp);

		if (act == "grow") {
			pHeight = p.style.pixelHeight; if (!pHeight) pHeight = p.offsetHeight;
		} else {
			pHeight = 0 - pHeight; 
		}
		balanceColumns.adjustLR(pHeight);
	},
	toggleClass: function() {
		if (YUD.hasClass(this,"hover")) {
			YUD.removeClass(this,"hover");
		} else {
			YUD.addClass(this,"hover");
		}
	},
	
	buildInternal: function() {
		var c = YUD.getElementsByClassName("collapsible");
		for (var i=0; i<c.length; i++) {
			var a = YUD.getElementsBy(alwaysTrue,"a",c[i]);
			for (var j=0; j<a.length; j++) {
				var n = a[j].getAttribute("name");
				if (!n) {
					var h = a[j].getAttribute("href");
					if (h.substr(0,1) == "#") {
						h = h.substr(1);
						a[j].setAttribute("href","javascript:void(0);");
						YUE.addListener(a[j],"click",collapse.findInternal,h);
					}
				}
			}
		}
	},
	findInternal: function(e,h) {
		var c = YUD.getElementsByClassName("collapsible");
		for (var i=0; i<c.length; i++) {
			var a = YUD.getElementsBy(alwaysTrue,"a",c[i]);
			for (var j=0; j<a.length; j++) {
				var n = a[j].getAttribute("name");
				if (n == h) {
					var p = a[j].parentNode;
					while (!YUD.hasClass(p,"collapsible")) p = p.parentNode;
					collapse.toggle(null,p);
					document.location.href = "#"+h;
				}
			}
		}
	}
}

var cleanPage = {
	pd: null,

	init: function() {
		cleanPage.pd = document.getElementById("pg_columnB2");
		if (cleanPage.pd) {
			if (YUD.hasClass(cleanPage.pd,"productDetail")) cleanPage.productDetail();
		}
		
		// clean out the product descriptions (only in lists)
		// cleanPage.descriptions();
		
		cleanPage.footDivider();
		cleanPage.balanceFoot();
	},

	productDetail: function() {
		cl = YUD.getElementsByClassName("columnLeft","div",cleanPage.pd);
		if (cl) {
			compat = YUD.getElementsByClassName("compatible","div",cl[0]);
			if (compat) YUD.setStyle(compat[0],"display","block");
		}
	},
	
	footDivider: function() {
		var fd = document.createElement("div");
		fd.setAttribute("id","footDivider");

		var pm = document.getElementById("pg_main");
		if (pm) pm.appendChild(fd);
	},
	balanceFoot: function() {
		var a = Array("pg_footCol1","pg_footCol2","pg_footCol3");
		var cols = Array();
		for (var i=0; i<a.length; i++) {
			var c = document.getElementById(a[i]);
			if (c) cols.push(c);
		}
		if (a.length == cols.length) {
			var max = 0;
			for (i=0; i<cols.length; i++) {
				var h = sizeImg.getSize(cols[i])[1];
				if (h > max) max = h;
			}
			for (i=0; i<cols.length; i++) {
				YUD.setStyle(cols[i],"height",max+"px");
			}
		}
	},
	
	descriptions: function() {
		var list = YUD.getElementsByClassName("list","div");
		for (var i=0; i<list.length; i++) {
			var im = YUD.getElementsByClassName("item","div",list[i]);
			for (var j=0; j<im.length; j++) {
				var desc = YUD.getElementsByClassName("description","div",im[j]);
				for (var k=0; k<desc.length; k++) {
					desc[k].innerHTML = cleanPage.removeTags(desc[k]);
				}
			}
		}
	},
	
	removeTags: function(div) {
		var strIn = div.innerHTML;
		var strIpped = strIn.replace(/<\/?[^>]+(>|$)/g, "");
		return strIpped;
	}
}

var getReviews = {
	divSection: null,
	divTotal: null,
	divReviews: null,

	myProduct: "",
	myList: Array(),

	navStart: 0,
	navCount: 5,

	init: function() {
		r = YUD.getElementsByClassName("pg_columnB2");
		if (r) {
			pd = YUD.getElementsByClassName("productDetail","div",r[0]);
			for (var i=0; i<pd.length; i++) {
				if (YUD.hasClass(pd[i],"item")) {
					getReviews.myProduct = pd[i].getAttribute("id"); // document.form.TellFriend.productId.value;

					var ra = pd[i].getElementsByTagName("a");
					for (var i = 0; i < ra.length; i++) {
						if (ra[i].getAttribute("name") == "reviews") {
							getReviews.divReviews = ra[i].parentNode;
							i = ra.length+1;
						}
					}
				}
			}
			if (getReviews.divReviews) {
				getReviews.divSection = getReviews.divReviews;
				var l = YUD.getElementsByClassName("label","div",getReviews.divSection);
				if (l.length > 0) getReviews.divTotal = l[0];
				else {
					var l = document.createElement("div");
					YUD.addClass(l,"label");
					getReviews.divSection.appendChild(l);
					getReviews.divTotal = l;
				}
				
				// fire off the ajax that will populate the reviews
				getReviews.connect();
			}
		}
	},

	connect: function() {
		// var entryPoint = 'xml_reviewlist.xml';
		var entryPoint = 'includes/userReviewListXml.jsp';

		thisdate = new Date();
		var queryString = encodeURI('?prodid=' + getReviews.myProduct + "&time=" + thisdate.getTime());
		var sUrl = entryPoint + queryString;

		var request = YUC.asyncRequest('GET', sUrl, { success:getReviews.store, failure:getReviews.fail });
	},
	fail: function(o) {
		// write out that no reviews are yet available.
		getReviews.empty();
	},

	store: function(o) {
		// store the reviews in a local array
		root = o.responseXML.documentElement;
		revs = root.getElementsByTagName("review");
		for (i = 0; i < revs.length; i++) {
		    r = revs[i];            
		    rDate = getFieldValue(r,"date",0);
		    rFirst = getFieldValue(r,"firstName",0);
		    rLast = getFieldValue(r,"lastName",0);
		    rRating = getFieldValueAsFloat(r,"rating",0);
		    rReview = getFieldValue(r,"comments",0);
		    rArray = Array(i, rDate, rFirst, rLast, rRating, rReview);
		    getReviews.myList.push(rArray);
		}

		if (revs.length == 0) getReviews.empty();
		else {
			getReviews.show();
			getReviews.divTotal.innerHTML = '<div class="nav">Total reviews: ' +revs.length+ '</div>';

			seeAll = '<a href="">See all customer reviews &#187;</a>';
			if (revs.length > getReviews.navCount) {
				getReviews.divReviews.innerHTML += '<div class="nav">' +seeAll+ '</div>';
				tmp = getReviews.divTotal.innerHTML.toLowerCase();
				tmp = tmp.replace('</div>',' / ' +seeAll+ '</div>');
				getReviews.divTotal.innerHTML = tmp;

				a = YUD.getElementsBy(alwaysTrue,"a",getReviews.divReviews);
				a.push(YUD.getElementsBy(alwaysTrue,"a",getReviews.divTotal)[0]);

				for (i = 0; i < a.length; i++) {
					a[i].setAttribute("href","javascript:void(0);");
					YUE.addListener(a[i],"click",getReviews.showAll);
				}
			}
		}
	},

	show: function() {
		start = getReviews.navStart;
		count = getReviews.navCount;

		// write X number of reviews
		html = '';

		list = getReviews.myList;

		if (start > list.length) start = 0;
		if ((start+count) > list.length) count = list.length - start;
		stop = start+count;

		for (i = start; i < stop; i++) {
			rID = list[i][0];
			rDate = list[i][1];

			rName = list[i][2];

			if (rName != ""){
				rName = rName.substr(0,1).toUpperCase() + " ";
				rName += list[i][3];
			} else {
				rName = "Anonymous";
			}

			rStars = "";
			for (j = 1; j <= 5; j++) {
				if (list[i][4] >= j) rStars += '<img alt="starFilled" src="images/pg_rating_starFilled.gif" />\n';
				else rStars += '<img alt="starFilled" src="images/pg_rating_starEmpty.gif" />\n';
			}
			rReview = list[i][5];

			html += '<div class="review" id="review_' +rID+ '">\n' +
				'\t<div class="stars">' +rStars+ '</div>\n' +
				'\t<div class="date">' +rDate+ '</div>\n' +
				'\t<div class="reviewer">' +rName+ '</div>\n' +
				'\t<div class="description">' + rReview+ '</div>\n' +
				'</div>\n\n';
		}
		getReviews.divReviews.innerHTML = html;
	},

	showAll: function() {
		first = false;
		if (getReviews.navCount == 5) {
			// we're shifting from the first screen to scrolling through the reviews
			first = true;
			getReviews.navStart = 0;
			getReviews.navCount = 8;

			hOld = getReviews.divSection.style.pixelHeight; if (!hOld) hOld = getReviews.divSection.offsetHeight;
		}
		start = getReviews.navStart;
		count = getReviews.navCount;
		total = getReviews.myList.length;
		end = start + count; if (end > total) { end = total; }

		// txtPrev = '<a href="" class="nav navPrev">&#171; Previous ' +count+ '</a>';
		// txtNext = '<a href="" class="nav navNext">Next ' +(count+end>total ? (total-end>0 ? total-end : count) : count)+ ' &#187;</a>';
		txtPrev = '<a href="" class="nav navPrev">&#171; Previous</a>';
		txtNext = '<a href="" class="nav navNext">Next &#187;</a>';

		nav = '<div class="nav">' +txtPrev+' / '+(start+1)+'-'+end+' of '+total+' / '+txtNext+ '</div>\n';

		getReviews.divTotal.innerHTML = "";
		getReviews.show();
		getReviews.divReviews.innerHTML = nav + getReviews.divReviews.innerHTML + nav;

		// get all the <a>'s
		a = YUD.getElementsBy(alwaysTrue,"a",getReviews.divSection);
		aPrev= Array(); aNext = Array();
		for (i = 0; i < a.length; i++) {
			a[i].setAttribute("href","javascript:void(0);");
			if (YUD.hasClass(a[i],"navPrev")) aPrev.push(a[i]);
			if (YUD.hasClass(a[i],"navNext")) aNext.push(a[i]);
		}
		count = getReviews.navCount;

		newStart = start - count; if (newStart < 0) newStart = 0;
		for (i = 0; i < aPrev.length; i++) {
			aPrev[i].setAttribute("onclick","getReviews.navStart="+newStart+"; getReviews.showAll();");
		}
		newStart = start + count;
		for (i = 0; i < aNext.length; i++) {
			aNext[i].setAttribute("onclick","getReviews.navStart="+newStart+"; getReviews.showAll();");
		}

		if (start == 0) getReviews.killNav(aPrev);
		if (count+start >= total) getReviews.killNav(aNext);

		if (first) {
			B = document.getElementById("pg_columnB");
			hB = parseInt(YUD.getStyle(B,"height").replace("px",""));

			h = getReviews.divSection.style.pixelHeight; if (!h) h = getReviews.divSection.offsetHeight;
			h = h - hOld;

			hAll = hB+h;
			YUD.setStyle(B,"height",hAll+"px");

			balanceColumns.init();
		}
	},
	killNav: function(arr) {
		// remove the links
		for (i = 0; i < arr.length; i++) {
			arr[i].removeAttribute("onclick");
			YUD.addClass(arr[i],"navDead");
		}
	},

	empty: function() {
		// write out that no reviews are yet available.
		if (getReviews.divTotal) getReviews.divTotal.innerHTML = '';
		if (getReviews.divReviews) {
			getReviews.divReviews.innerHTML = '<p>No reviews have been posted for this product. <a href="">Be the first to review it!</a></p>';

			a = YUD.getElementsBy(alwaysTrue,"a",getReviews.divReviews)[0];
			a.setAttribute("href","#top");
			YUE.addListener(a,"click",reviewBox.toggle);
		}
	}
}

var balanceColumns = {
	cols: Array(),
	location: "normal",

	init: function() {
		var cb = document.getElementById("pg_columnB");
		if (cb) if (YUD.hasClass(cb,"home")) {
			balanceColumns.cols = Array("pg_columnB1","pg_columnB2");
			balanceColumns.location = "interior";
			// balanceColumns.doit();
			
			balanceColumns.location = "front";
		}

		balanceColumns.cols = Array("pg_columnA","pg_columnB","pg_columnB2");
		balanceColumns.doit();
		
		// balanceColumns.pullFooter(20);
		if (balanceColumns.location == "front") balanceColumns.pullFooter(0);
	},

	pullFooter: function(h) {
		f = document.getElementById("pg_footer");
		if (f) YUD.setStyle(f, "top", h+"px");
	},
	
	reset: function() {
		for (i = 0; i < balanceColumns.cols.length; i++) {
			tmp = document.getElementById(balanceColumns.cols[i]);
			YUD.setStyle(tmp,"height","auto");
			
			var c = YUD.getElementsByClassName("c","div",tmp);
			if (c.length > 0) {
				c = c[0];
				if (c.parentNode.parentNode.parentNode == tmp) {
					YUD.setStyle(c,"height","auto");
					YUD.setStyle(c.parentNode,"height","auto");
					YUD.setStyle(c.parentNode.parentNode,"height","auto");
				}
			}
		}
		var bkg = document.getElementById("background");
		if (bkg) YUD.setStyle(bkg,"height","auto");
	},

	doit: function() {
		// get the columns
		var cols = Array(); allHere = true;
		for (i = 0; i < balanceColumns.cols.length; i++) {
			e = document.getElementById(balanceColumns.cols[i]);
			if (!e) allHere = false; else cols.push(e);
		}

		if (allHere) {
			loc = balanceColumns.location;
			colA = cols[0]; colB = cols[1];

			heightA = colA.style.pixelHeight; if (!heightA) heightA = colA.offsetHeight;
			heightB = colB.style.pixelHeight; if (!heightB) heightB = colB.offsetHeight;
			if (heightA > heightB) hB = heightA; else hB = heightB;

			switch(loc) {
				case "front":		hA = hB+30; break;
				case "interior":	hA = hB; break;
				case "replace":		hB += sizeImg.replacedPixels;
				default:		hA = hB+40; break;
			}
			YUD.setStyle(colA,"height",hA+"px");
			
			switch(loc) {
				case "replace":
				case "normal":	balanceColumns.balanceABC(Array(cols[1],cols[2]), hB); break;
				case "interior":	balanceColumns.balanceABC(Array(cols[0],cols[1]), hB);
								break;
			}
		}
	},
	
	adjustLR: function(adj) {
		var cb = document.getElementById("pg_columnB");
		if (cb) if (YUD.hasClass(cb,"home")) {
			cols = Array("pg_columnA", "pg_columnB");
		} else {
			cols = Array("pg_columnA", "pg_columnB2", "pg_columnB");
		}
		for (i = 0; i < cols.length; i++) {
			balanceColumns.adjust(cols[i],adj);

			// fix background to fit
			background.init();
		}
	},
	
	adjust: function(div, value) {
		d = document.getElementById(div);
		var height = d.style.pixelHeight; var adjust = 0;
		if (!height) { height = d.offsetHeight; adjust = -10; }
			
		if (div == "pg_columnB") height += adjust;
		heightAdj = (parseInt(value)+height) + "px";

		a = YUD.getElementsByClassName("a","div",d);
		if (a.length > 0) if (a[0].parentNode == d) { 
			YUD.setStyle(a[0],"height",heightAdj);
			b = YUD.getElementsByClassName("b","div",d);
			YUD.setStyle(b[0],"height",heightAdj);
			c = YUD.getElementsByClassName("c","div",d);
			YUD.setStyle(c[0],"height",heightAdj);
		}
		YUD.setStyle(d,"height",heightAdj);
	},
		
	getKids: function(div) {
		d = div;
		a = YUD.getElementsByClassName("a","div",d);
		if (a.length > 0) if (a[0].parentNode == d) d = a[0];
		b = YUD.getElementsByClassName("b","div",d);
		if (b.length > 0) if (b[0].parentNode == d) d = b[0];
		c = YUD.getElementsByClassName("c","div",d);
		if (c.length > 0) if (c[0].parentNode == d) d = c[0];
		
		kids = d.childNodes; h = 0;
		for (i = 0; i < kids.length; i++) {
			if (kids[i].nodeName == "DIV") {
				kh = kids[i].style.pixelHeight; if (!kh) kh = kids[i].offsetHeight;
				h += kh;
			}
		}
		return h;
	},
	
	balanceABC: function(cols, height) {
		colB = cols[0]; colB2 = cols[1]; hB = height;

		YUD.setStyle(colB,"height",hB+"px");
		bA = YUD.getElementsByClassName("a","div",colB2)[0];
		bB = YUD.getElementsByClassName("b","div",colB2)[0];
		bC = YUD.getElementsByClassName("c","div",colB2)[0];

		YUD.setStyle(Array(colB, colB2, bA,bB,bC),"height",hB+"px");
	},
	
	productDetails: function(id) {
		var pd = document.getElementById(id);
		if (pd) {
			balanceColumns.cols = Array("pg_columnA","pg_columnB","pg_columnB2");
			balanceColumns.reset();
			balanceColumns.doit();
		}
	}
}

var ajaxObject = {
	handleSuccess:function(o) { },
	handleFailure:function(o) { },
	startRequest:function(e,a,i) {
		YAHOO.util.Connect.asyncRequest('GET', i, {
			success: function() {
				actionImages.swapImage(e,a,i);
				actionImages.addToAlready(i); },
			failure: function() { return false; }
		});
	}
}

var actionImages = {
	// Purpose: This function is intended to scour the page after it loads for images that might have alternate "_mouseover" versions
	//	(i.e. they are expected to display a mouseover effect). If an image is found on the server, it adds the onmouseover/onmouseout
	//	behaviors.
	imageList: Array(),
	alreadyFound: Array(),

	init: function() {
		actionImages.imageList = YUD.getElementsByClassName("active", "img"); 
		tmpList = YUD.getElementsByClassName("active", "input");
		for (i=0;i<tmpList.length;i++) actionImages.imageList.push(tmpList[i]);
		
		// check for non-Pocketgear images
		actionImages.cleanList();

		for (i=0;i<actionImages.imageList.length;i++) {
			el = actionImages.imageList[i];
			actionImages.addActions(el);
		}
	},

	addActions: function(el) {
		oldSrc = el.getAttribute("src");

		states = Array("mouseover", "mouseout", "click");
		for (j=0;j<states.length;j++) {
			file = "_"+states[j];
			if (file == "_mouseout") file = "";

			newSrc = oldSrc.replace(".gif",file+".gif").replace(".jpg",file+".jpg");
			actionImages.handleAjax(el, states[j], newSrc);
		}
	},

	cleanList: function() {
		loc = window.location.href;
		s = loc.indexOf("://")+3;
		for (i = s; i < loc.length; i++) {
			if (loc.substr(i,1) == "/") break;
		}
		loc = loc.substr(0,i+1);

		newArray = Array();
		for (i=0;i<actionImages.imageList.length;i++) {
			el = actionImages.imageList[i];
			if (src = el.getAttribute("src")) {
				addThis = true;
				if (src == "" || src == undefined) addThis = false;
				if (src.substr(0,4) == "http" && src.substr(0,loc.length) != loc) addThis = false;
	
				if (addThis) newArray.push(el);
			}
		}
		actionImages.imageList = newArray;
	},

	handleAjax: function (e,a,i) {
		// Purpose: check for the existence of the new image (via ajax call)

		// First see if we've found it already
		found = false;
		if (a == "mouseout") found = true;
		for (k=0;k<actionImages.alreadyFound.length;k++) {
			if (i == actionImages.alreadyFound[k]) { found = true; break; }
		}
		if (found)
			actionImages.swapImage(e,a,i); // on a mouseout, we know the original image is there...
		else
			ajaxObject.startRequest(e,a,i); // ...otherwise we check the server
	},

	swapImage: function(e,a,i) {
		YUE.addListener(e,a, function() { e.src = i; });
		if (i != e.src.substr(e.src.length-i.length)) sizeImg.loadImg(i);
	},

	addToAlready: function(val) {
		absent = true;
		for (k = 0; k < actionImages.alreadyFound.length; k++)
			if (actionImages.alreadyFound[k] == val) absent = false;
		if (absent) actionImages.alreadyFound.push(val);
	}
}

var sizeImg = {
	replacedImages: 0,
	replacedPixels: 0,
	
	init: function() {
		// check for any thumbnails on the page and resize them and their boxes
		sizeImg.resizeItems(null,false);
		
		// load the default images and replace any missing ones
		sizeImg.loadImg("images/products/_default_product_small.gif");
		sizeImg.loadImg("images/products/_default_product_large.gif");
		setTimeout("sizeImg.replace();",2000);
	},
	
	resizePage: function() { sizeImg.resizeItems(null,true); },

	resizeItems: function(div,replace) {
		var finalWide = 75;
		var padding = 30;

		if (div) im = Array(div);
		else im = YUD.getElementsByClassName("item");

		for (i = 0; i < im.length; i++) {
			// get the given height of the "item"
			iSize = sizeImg.getSize(im[i]);
			iWidth = iSize[0]; iHeight = iSize[1];

			d = YUD.getElementsByClassName("image","div",im[i])[0];
			if (d) {
				// get the particular image and its shadow
				thumb = YUD.getElementsBy(alwaysTrue,"img",d)[0];

				// check to see if we're on the main product page or just in a list
				if (YUD.hasClass(im[i],"productDetail")) primary = true; else primary = false;

				// get the actual size of the image, then resize it to fit a fixed-pixel space.
				thumb.setAttribute("style","");
				tharr = sizeImg.getSize(thumb);
				wide = tharr[0]; high = tharr[1];

				// setting a fixed width for the images
				if (primary) finalWide = 240;
				finalHigh = Math.ceil(finalWide*(high/wide));

				YUD.setStyle(Array(d,thumb),"width",finalWide+"px");
				YUD.setStyle(Array(d,thumb),"height",finalHigh+"px");
				
				if (!primary) {
					// resize the entire box if necessary
					if ((finalHigh+padding) > iHeight) {
						sizeImg.replacedPixels += finalHigh - high;
						iHeight = finalHigh+padding; // finalHigh - high + 8;
					}
					sizeImg.resizeABC(im[i],0,iHeight);
				} else {
					// resize columnLeft and columnRight
					cL = YUD.getElementsByClassName("columnLeft","div",im[i])[0];
					cLWide = sizeImg.getSize(cL)[0];
					cR = YUD.getElementsByClassName("columnRight","div",im[i])[0];
					cRWide = sizeImg.getSize(cR)[0];

					dL = finalWide + 9;
					diff = cLWide - dL;
					dR = cRWide + diff;

					YUD.setStyle(cL,"width",dL+"px");
					YUD.setStyle(cR,"width",dR+"px");
				}

				sizeImg.addShadow(d.parentNode,finalHigh,finalWide,primary);
				if (!primary) {
					YUE.addListener(thumb,"mouseover",sizeImg.darkenShadow);
					YUE.addListener(thumb,"mouseout",sizeImg.darkenShadow);
				}
			}
		}
		
		// push down the page accordingly
		if (replace) {
			balanceColumns.cols = Array("pg_columnA","pg_columnB","pg_columnB2");
			balanceColumns.location = "replace";
			balanceColumns.doit();
		}
		sizeImg.replacedPixels = 0;
		
		// fix background to fit the added images
		background.init();
	},

	addShadow: function(original, h, w, primary) {
		// first check for another shadow (and remove it)
		var s = YUD.getElementsByClassName("imageShadow","div",original);
		for (var i=0; i<s.length; i++) s[i].parentNode.removeChild(s[i]);
		
		shadow = document.createElement("div");
		YUD.addClass(shadow,"imageShadow");
		if (primary) YUD.addClass(shadow,"imagePrimaryShadow");

		YUD.setStyle(shadow,"height",(h+2)+"px");
		YUD.setStyle(shadow,"width",(w+2)+"px");
		original.appendChild(shadow);
	},

	darkenShadow: function(o) {
		p = this;
		while (!YUD.hasClass(p,"item")) p = p.parentNode;

		if (YUD.hasClass(p,"darkShadow")) {
			YUD.removeClass(p,"darkShadow");
		} else {
			YUD.addClass(p,"darkShadow");
		}
	},
	
	resizeABC: function(id, width, height) {
		idA = YUD.getElementsByClassName("a","div",id)[0];
		idB = YUD.getElementsByClassName("b","div",id)[0];
		idC = YUD.getElementsByClassName("c","div",id)[0];

		if (idA) {
			pT = YUD.getStyle(idC,"padding-top");
			pT = pT.substr(0,pT.length-2);
			pB = YUD.getStyle(idC,"padding-bottom");
			pB = pB.substr(0,pB.length-2);
			heightIDC = height - pT - pB;

			if (width > 0) {
				YUD.setStyle(id,"width",width+"px");
				YUD.setStyle(idA,"width",width+"px");
				YUD.setStyle(idB,"width",width+"px");
				YUD.setStyle(idC,"width",width+"px");
			}
			if (height > 0) {
				YUD.setStyle(id,"height",height+"px");
				YUD.setStyle(idA,"height",height+"px");
				YUD.setStyle(idB,"height",height+"px");
				YUD.setStyle(idC,"height",heightIDC+"px");
			}
		}
	},

	getSize: function(i) {
		w = h = 0;
		try {
			if (typeof(i) != 'undefined') {
				h = i.offsetHeight; if (!h) h = i.style.pixelHeight; 
				w = i.offsetWidth; if (!w) w = i.style.pixelWidth;
			}
			return Array(w,h);
		} catch(e) { }
	},
	setSize: function(o,w,h) {
		try {
			if (typeof(o) != 'undefined') {
				if (h) YUD.setStyle(o,"height",h+"px");
				if (w) YUD.setStyle(o,"width",w+"px");
			}
		} catch(e) { }
	},

	loadImg: function(url) {
		corral = document.getElementById("image_corral");
		if (!corral) {
			foot = document.getElementById("pg_footer");
			if (!foot) { foot = document.createElement("div"); foot.setAttribute("id","pg_footer"); b = document.getElementsByTagName("body")[0]; b.appendChild(foot); }
				
			corral = document.createElement("div");
			corral.setAttribute("id","image_corral");
			YUD.setStyle(corral,"display","none");
			foot.appendChild(corral);
		}

		img = document.createElement("img");
		img.setAttribute("src", url);
		corral.appendChild(img);
	},

	fade: function(c,inout,dur,max) {
		if (!dur) dur = 1;
		if (!max) max = 1;
		
		var myAnim = new YAHOO.util.Anim(c);
		myAnim.duration = dur;

		myAnim.attributes.opacity = { from: 0, to: max };
		if (inout == "out") myAnim.attributes.opacity = { from: 1, to: 0 };
		
		myAnim.animate();
	},
	
	replace: function() {
		var base = getBase(window.location.href);

		// check for any thumbnails on the page and resize them and their boxes
		var im = YUD.getElementsByClassName("item");
		for (i = 0; i < im.length; i++) {
			var d = YUD.getElementsByClassName("thumb","div",im[i])[0];
			if (d) {
				// check to see if we're on the main product page or just in a list
				if (YUD.hasClass(im[i],"productDetail")) primary = true; else primary = false;

				// replace the image if it's missing
				var t = YUD.getElementsBy(alwaysTrue,"img",d);
				if (t.length > 0) {
					var current = t[0].getAttribute("src");
					var cb = getBase(current);

					var getIt = true;
					if (current.substr(0,7) == "http://" || current.substr(0,8) == "https://") getIt = false;
					if ((current.substr(0,7) == "http://" || current.substr(0,8) == "https://") && cb == base) getIt = true;
					if (getIt) {
						sizeImg.replacedImages++;
						var args = Array(d,primary);
						var request = YUC.asyncRequest('GET', current, { success:sizeImg.replaceResponse, failure:sizeImg.replaceResponse, argument: args });
					}
				}
			}
		}
	},
	replaceResponse: function(o) {
		var d = o.argument[0];
		var p = o.argument[1];
		var status = o.status;

		var padding = 30;
		
		if (status != 200) {
			var i = YUD.getElementsBy(alwaysTrue,"img",d);
			if (i.length > 0) {
				var par = i[0].parentNode;
				// par.innerHTML = "";
				par.removeChild(i[0]);
				YUD.addClass(par,"unavailable");
				
				// get the replacement
				var rep = "images/products/_default_product_small.gif"; rw = 75; rh = 100;
				if (p) { rep = "images/products/_default_product_large.gif"; rw = 240; rh = 240; }
				
				// create the new image node
				var ni = document.createElement("img");
				ni.setAttribute("alt","Image Unavailable");
				ni.setAttribute("src",rep);
				
				// append the image node
				par.appendChild(ni);
				
				// add the shadowing plus positioning
				// sizeImg.addShadow(d.parentNode,rh,rw,p);
				YUD.setStyle(par,"height",rh+"px");
				if (!p) {
					// YUE.addListener(par,"mouseover",sizeImg.darkenShadow);
					// YUE.addListener(par,"mouseout",sizeImg.darkenShadow);
				
					// find the "item" box surrounding the image
					b = par;
					while (!YUD.hasClass(b,"item")) b = b.parentNode;
					
					// get the current size of the item and increase as necessary
					hPrev = sizeImg.getSize(b)[1];
					sizeImg.resizeItems(b,false);

					sizeImg.replacedPixels += sizeImg.getSize(b)[1] - hPrev - 4;
					
//					iHeight = sizeImg.getSize(b)[1];
//					var minHeight = rh + padding;
//					if (iHeight < minHeight) { sizeImg.replacedPixels += (minHeight - iHeight - 5); iHeight = minHeight; }
//					sizeImg.resizeABC(b,0,iHeight);
				} else {
					balanceColumns.cols = Array("pg_columnA","pg_columnB","pg_columnB2");
					balanceColumns.doit();
				}
 			}
		}
		
		sizeImg.replacedImages--;
		if (sizeImg.replacedImages == 0) sizeImg.resizePage();
			
			/* // push down the page accordingly
			balanceColumns.cols = Array("pg_columnA","pg_columnB","pg_columnB2");
			balanceColumns.location = "replace";
			balanceColumns.doit();
			sizeImg.replacedPixels = 0;
			
			// fix background to fit the added images
			background.init(); */
	}
}

var transitionCount = {
	secs: 6,
	element: "",

	init: function() {
		// count down 8 seconds then transition to the proper URL
		transitionCount.element = document.getElementById("transitionCountdown");

		if (transitionCount.element) {
			YUE.addListener(transitionCount.element.parentNode,"click",transitionCount.go);

			transitionCount.countdown();
		}
	},

	go: function() {
		window.location.href = "http://www.pocketgear.com/";
	},

	countdown: function() {
		transitionCount.element.innerHTML = "<em>Here we go!</em>";

		c = transitionCount.secs;
		unit = " seconds"; if (c == 1) unit = " second&nbsp;";
		if (c > 0) { transitionCount.element.innerHTML = c + unit; }
		transitionCount.secs--;

		if (transitionCount.secs < 0) {
			transitionCount.go();
		} else {
			setTimeout("transitionCount.countdown()",1000);
		}
	}

}

var folds = {
	init: function() {
		var c = YUD.getElementsByClassName("folded");
		folds.getFolds(c);
		var h = window.location.hash;
		if (h) folds.open(h.replace("#",""));
	},
	addArrows: function(h2) {
		h2.innerHTML += " ";
		
		var t = h2.childNodes[0];
		h2.removeChild(t);
 	 	
		var pre = document.createElement("span");
		YUD.addClass(pre,"pointer");
		pre.innerHTML = "&#187;";
 	 	
		var post = pre.cloneNode(true);
		YUD.addClass(pre,"pre");
		YUD.addClass(post,"post");
 	 	h2.appendChild(pre);
		
		h2.appendChild(t);
		h2.appendChild(post);
 	},

 	open: function(n) {
		var node = null;
		var a = document.getElementsByTagName("a");
		for (var i=0; i<a.length; i++) {
			if (a[i].getAttribute("name") == n) { 
				node = a[i];
				break;
			}
		}
		if (node) { 
			while (node != document) { 
				node = node.parentNode;
				if (YUD.hasClass(node,"folded")) {
					f = folds.getNode(node,"foldedText");
					if (f) folds.toggleText(null,f);
				}
			}
		}
 	},
	getNode: function(o,type) {
		var tn = null;
		var kids = o.childNodes;
		for (var j=0; j<kids.length; j++) {
			var nt = kids[j].nodeType;
			if (nt == 1) { 	
				if (type == "h2") {
					if (kids[j].nodeName == "H2") { tn = kids[j]; break; }
				} else {
					if (YUD.hasClass(kids[j],type)) { tn = kids[j]; break; }
				}
			}
		}
		return tn;
 	},
	getFolds: function(c) {
		for (var i=0; i<c.length; i++) {
			var h2 = folds.getNode(c[i],"h2");
			var ft = folds.getNode(c[i],"foldedText");
			if (ft) {
				YUE.addListener(h2,"mouseover",folds.toggleActive,h2);
				YUE.addListener(h2,"mouseout",folds.toggleActive,h2);
				YUE.addListener(h2,"click",folds.toggleText,ft);
			}
			if (h2) folds.addArrows(h2);
		}
	},
	toggleActive: function(e,o) {
		if (YUD.hasClass(o,"active")) { 
			YUD.removeClass(o,"active");
		} else {
			YUD.addClass(o,"active");
		}
 	},
	toggleText: function(e,o) {
		var p = o.parentNode;
		var h2 = p.getElementsByTagName("h2");
		if (h2.length > 0) h2 = h2[0];
		else h2 = NULL;
		
		if (YUD.hasClass(o,"unfolded")) { 
			folds.toggleBox(o,"fold");
			sizeImg.fade(o,"out",0.5,1);
			YUD.removeClass(o,"unfolded");
			if (h2) YUD.removeClass(h2,"unfolded");
		} else { 
			if (h2) YUD.addClass(h2,"unfolded");
			YUD.addClass(o,"unfolded");
			sizeImg.fade(o,"in",0.5,1);
			folds.toggleBox(o,"unfold");
		}
	},
	toggleBox: function(o,action) { 
		pHeight = o.style.pixelHeight;
		if (!pHeight) pHeight = o.offsetHeight;
		if (action == "unfold") { 
			disp = "block"; act = "grow";
		} else { 
			disp = "none"; act = "shrink";
		}
		if (act == "grow") {
			pHeight = o.style.pixelHeight; if (!pHeight) pHeight = o.offsetHeight;
		} else { 
			pHeight = 0 - pHeight;
		}
		setTimeout("balanceColumns.adjustLR("+pHeight+");",400);
	}
}

var popup = {
	init: function() {
		var pops = YUD.getElementsByClassName("popup","span");
		for (var i=0; i<pops.length; i++) {
			YUE.addListener(pops[i],"mouseover",popup.hover,pops[i]);
			YUE.addListener(pops[i],"mouseout",popup.hover,pops[i]);
			YUE.addListener(pops[i],"click",popup.toggle,pops[i]);
			YUD.addClass(pops[i],"built");
		}
	},
	
	hover: function(e,o) {
		if (e.type == "mouseover") {
			YUD.addClass(o,"hover");
		} else {
			YUD.removeClass(o,"hover");
		}
	},
	toggle: function(e,o) {
		if (YUD.hasClass(o,"toggle")) {
			YUD.removeClass(o,"toggle");
		} else {
			YUD.addClass(o,"toggle");
		}
	}
}

var tooltips = {
	init: function() {
		var tips = YUD.getElementsByClassName("tooltip");
		for (var i=0; i<tips.length; i++) {
			if (!YUD.hasClass(tips[i],"built")) {
				var icon = document.createElement("div");
				YUD.addClass(icon,"icon");
				
				var box = document.createElement("div");
				YUD.addClass(box,"tip");
				var boxStyle = tips[i].getAttribute("style");
				if (boxStyle != "") box.setAttribute("style",boxStyle);
				tips[i].setAttribute("style","");
				
				var close = document.createElement("a");
				YUD.addClass(close,"close");
				close.innerHTML = "Close";
				box.appendChild(close);
				
				while (tips[i].childNodes.length > 0) { box.appendChild(tips[i].childNodes[0]); }
				tips[i].appendChild(icon);
				tips[i].appendChild(box);
				
				YUE.addListener(icon,"mouseover",tooltips.active,icon);
				YUE.addListener(icon,"mouseout",tooltips.active,icon);
				YUE.addListener(icon,"click",tooltips.toggle,tips[i]);
				
				YUD.addClass(tips[i],"built");
			}
		}
	},
	toggle: function(e,o) {
		var id = o.getAttribute("id");
		var icon = YUD.getElementsByClassName("icon","div",o)[0];
		var tip = YUD.getElementsByClassName("tip","div",o)[0];

		if (YUD.hasClass(o,"toggled")) {
			var vt = YUD.getElementsByClassName("viewTip","div");
			for (var i=0; i<vt.length; i++) {
				if (vt[i].getAttribute("id") == id+"viewTip") {
					sizeImg.fade(vt[i],"out",0.2,1);
					vt[i].parentNode.removeChild(vt[i]);
				}
			}
			YUD.removeClass(o,"toggled");
			ie6.toggleDropdowns(null,"off");
		} else {
			// create a new tip
			var viewTip = tip.cloneNode(true);
			YUD.addClass(viewTip,"viewTip");
			viewTip.setAttribute("id",id+"viewTip");
			
			var iconXY = findPos(icon);
			viewX = iconXY[0]-388; viewY = iconXY[1]+24;
			YUD.setStyle(viewTip,"left",viewX+"px");
			YUD.setStyle(viewTip,"top",viewY+"px");
			
			var close = YUD.getElementsByClassName("close","a",viewTip);
			YUE.addListener(close,"click",tooltips.toggle,o);
			var h3 = viewTip.getElementsByTagName("h3");
			YUE.addListener(h3,"click",tooltips.toggle,o);
			
			document.body.appendChild(viewTip);
			tooltips.buildOptions(viewTip);
			sizeImg.fade(viewTip,"in",0.5,1);
			
			YUD.addClass(o,"toggled");
			ie6.toggleDropdowns(null,"on");
		}
	},
	active: function(e,o) {
		if (e.type == "mouseover") {
			YUD.addClass(o,"active");
		} else {
			YUD.removeClass(o,"active");
		}
	},
	
	buildOptions: function(t) {
		var tipOptions = YUD.getElementsByClassName("toggle","div",t);
		for (var j=0; j<tipOptions.length; j++) {
			var a = tipOptions[j].getElementsByTagName("a");
			for (var k=0; k<a.length; k++) {
				a[k].setAttribute("href","javascript:void(0);");
				YUE.removeListener(a[k]);
				YUE.addListener(a[k],"click",tooltips.toggleOptions,tipOptions[j]);
			}
		}
	},
	toggleOptions: function(e,o) {
		var p = o.parentNode;
		var t = YUD.getElementsByClassName("toggle","div",p);
		for (var i=0; i<t.length; i++) {
			if (t[i] == o) YUD.removeClass(t[i],"active");
			else YUD.addClass(t[i],"active");
		}
	}
}

var pageInfo = {
	linkName: 'catLink',
	headNodeId: 'pg_headAbout',
	headNode: Object,
	footNodeId: 'pg_footAbout',
	headNode: Object,

	init: function() {
		this.headNode = document.getElementById(this.headNodeId);
		this.footNode = document.getElementById(this.footNodeId);
		headBody =  YUD.getElementsByClassName("body","div",this.headNode)[0];
		footBody =  YUD.getElementsByClassName("body","div",this.footNode)[0];

		if (headBody && footBody) {
			footBody.innerHTML = headBody.innerHTML;
			headBody.innerHTML = "";
		}
	}
}

var activationCodes = {
	init: function() {
		codeClickers = YUD.getElementsByClassName("prodActivationToggler");
		for (i=0;i<codeClickers.length;i++)
			YUE.addListener(codeClickers[i],"click",activationCodes.toggle, i);
	},

	toggle: function(event, clicker) {
		pC = YUD.getElementsByClassName("activationCode", "div");
		adjust = 0 - sizeImg.getSize(pC[clicker])[1];

		if (pC[clicker].style.display != "block") {
			YUD.setStyle(pC[clicker],"display","block");
			folds.toggleBox(pC[clicker],"unfold");
			// adjust = sizeImg.getSize(pC[clicker])[1];
		} else {
			folds.toggleBox(pC[clicker],"fold");
			YUD.setStyle(pC[clicker],"display","none");
		}
		// balanceColumns.adjustLR(adjust);
	}
}

var ie6 = {
	toggleDropdowns: function(event, status) {
		if (!ie6.check()) return true;
		b = document.getElementById("pg_columnB2"); // only checking inside the major "B" column area
		c = "hideIE6";
		d = document.getElementsByTagName("select");
		for (i=0;i<d.length;i++) {
			if (YUD.isAncestor(b,d[i])) {
				// first remove the class anyway, then add back if it's set to "on"
				if (YUD.hasClass(d[i],c)) YUD.removeClass(d[i],c);
				if (status == "on") YUD.addClass(d[i],c);
			}
		}
	},
	check: function() {
		if (window.XMLHttpRequest) return false; else return true;
	}
}

/* Still to add to device selector: 
	failure messaging, device counts per manufacturer, 
	and "Other" grouping for those with fewer than 4 devices) */

var devSelect = {
	ds: "",
	dl: "",
	
	manufacturer: "",
	device: "",
	deviceName: "",
	deviceOrOS: "OS",
	operatingSystem: "",
	
	start: 0,
	perPage: 8,
	
	results: null,
	resultsArray: Array(),
	resultsSorted: Array(),
	textOnly: false,
	
	display: "none",
	context: "selector",
	
	groupCount: 0,
	otherGroup: Array(),

	init: function() {
		// add the newUser action.
		man = document.getElementById("newUser_manufacturer");
		if (man) { devSelect.fillForm(man); devSelect.syncNameLabel(currentSelectedDeviceOS); }
		
		var p = document.getElementById("phoneOS");
		if (p) {
			var phoneos = p.value;
			if (typeof(phoneos) != "undefined" && phoneos != "") devSelect.syncNameLabel(phoneos);
		}
		
		devSelect.ds = document.getElementById("pg_deviceSelector");
		devSelect.dst = document.getElementById("pg_deviceSelectorText");
		
		// first create the "current" (state) DIV
		// this is the only one that will be visible at any given time
		// it will be populated with other DIVs based on the class of the parent DIV
		if (devSelect.ds) {
			// write the device selector text
			devSelect.writeDS();
			
			// add the deviceList DIV
			devSelect.addDL();
			
			// add the "My Devices" option
			devSelect.myDevices();
			
			// clear out the "Generic" option from the "Browse By Device" list
			devSelect.generic();
			
			// load the loading and background images
			devSelect.loadImages();
			
			// add device counts to the manufacturers, then group them
			//devSelect.group();
		}
	},
	
	group: function() {
		// first find the device list
		var fd = document.getElementById("formDevices");
		if (fd) {
			var fds = fd.getElementsByTagName("select");
			if (fds.length > 0) {
				var fdo = fds[0].getElementsByTagName("option");
				if (fdo.length > 0) {
					devSelect.groupCount = fdo.length;
					for (var i=0; i<fdo.length; i++) {
						var opt = fdo[i].getAttribute("value");
						if (opt == 0) devSelect.groupCount--;
						else devSelect.groupConnect(opt, "check", fdo[i]);
					}
				}
			}
		}
	},
	groupConnect: function(id, action, target) {
		var entryPoint = 'includes/devicesByManufacturer.jsp';
		thisdate = new Date();
		var queryString = encodeURI('?manId=' + id + "&time=" + thisdate.getTime());
		var sUrl = entryPoint + queryString;
		
		switch(action) {
			case "check":	var request = YUC.asyncRequest('GET', sUrl, { success:devSelect.groupSuccess, failure:devSelect.failureGeneral, argument: { "opt":target } }); break;
		}
	},
	groupSuccess: function(o,arg) {
		var root = o.responseXML.documentElement;
		var devCount = root.getElementsByTagName("name").length;
		
		var opt = o.argument.opt;
		var sel = opt.parentNode;
		
		// opt.innerHTML += " [" +devCount+"]";
		if (devCount < 4) {
			// var copy = opt.cloneNode(true);
			// devSelect.otherGroup.push(copy);
			opt.parentNode.removeChild(opt);
			
			var p = root.getElementsByTagName("phone");
			for (var i=0; i<p.length; i++) devSelect.groupAdd(p[i]);
		}
		devSelect.groupCount--;
		
		if (devSelect.groupCount == 0 && devSelect.otherGroup.length > 0) devSelect.groupAppend(sel);
	},
	groupAppend: function(s) {
		var o = document.createElement("option");
		o.setAttribute("value","other");
		o.innerHTML = "Other Devices";
		s.appendChild(o);
	},
	
	groupBuild: function() {
		devSelect.resultsArray = devSelect.otherGroup;
		devSelect.showDevices(null,"");
		
		var dl = document.getElementById("pg_deviceList");
		if (dl) if (YUD.getStyle(dl,"display") != "block") {
			YUD.setStyle(dl,"display","block");
			devSelect.display = "block";
		}
	},
	groupAdd: function(n) {
		oID = n.getAttribute("id");
		oTitle = n.getElementsByTagName("name")[0].firstChild.nodeValue;
		
		oOS = "None";
		var nOS = n.getElementsByTagName('phoneos');
		// need to be sure <phoneos/> is set on all devices
		if (nOS.length > 0) if (nOS[0].firstChild) oOS = nOS[0].firstChild.nodeValue;
		
		oImage = "";
		imgsrc = "images/devices/126x126/_other_126x126.gif";
		if (n.getElementsByTagName('imageurl')[0].hasChildNodes()) {
			oImage = n.getElementsByTagName('imageurl')[0].firstChild.nodeValue;
			oImage = oImage.replace("_48x75","_126x126");
		}
		if (oImage != "") imgsrc = oImage;
		
		var tmp = Array(oTitle,oID,imgsrc,oOS);
		devSelect.otherGroup.push(tmp);
	},
	
	
	
	
	loadImages: function() {
		sizeImg.loadImg("images/selector/device-change.gif");
		sizeImg.loadImg("images/selector/device-selected.gif");
		sizeImg.loadImg("images/selector/device-start.gif");
		
		sizeImg.loadImg("images/loading.gif");
		sizeImg.loadImg("images/pg_deviceList_bkg.jpg");
		sizeImg.loadImg("images/pg_deviceList_error.jpg");
	},
	
	generic: function() {
		var f = Array();
		var fd = document.getElementById("formDevices"); if (fd) f.push(fd); 
		// var fu = document.getElementById("formUser"); if (fu) f.push(fu);
		for (var j=0; j<f.length; j++) {
			var o = f[j].getElementsByTagName("option");
			for (var i=0; i<o.length; i++) {
				if (o[i].text.trim() == "Generic") o[i].parentNode.removeChild(o[i]);
			}
		}
	},
	
	fillForm: function(m) {
		var numod = document.getElementById("newUser_model");
		if (numod) numod.value = currentSelectedDevice;
		
		YUE.addListener(m,"change",devSelect.getList);
		YUE.addListener(m,"click",devSelect.resetList,m);
		YUD.addClass(m,"active");

		var dst = document.getElementById("pg_deviceSelectorText");
		if (dst) {
			var c = YUD.getElementsByClassName("selected","div",dst);
			if (c.length > 0) {
				var p = YUD.getElementsByClassName("phone","div",c[0]);
				if (p.length > 0) {
					var t = YUD.getElementsByClassName("title","div",p[0]);
					if (t.length > 0) {
						var dev = t[0].childNodes[0].nodeValue;
						var manu = m.options[m.selectedIndex].text;
						var box = document.getElementById("newUser_modelBox");
						if (box) box.value = dev.replace(manu,"").replace("&amp;","&").trim();
					}
				}
			}
		}
	},
	
	addDL: function() {
		// remove the possible deviceList div
		dl = document.getElementById("pg_deviceList");
		if (dl) dl.parentNode.removeChild(dl);

		// create the deviceList div
		main = document.getElementById("pg_main");
		dl = document.createElement("div");
		dl.setAttribute("id","pg_deviceList");

		// create the close button
		var bc = document.createElement("a");
		YUD.addClass(bc,"close");
		bc.setAttribute("href","javascript:void(0);");
		var bct = document.createTextNode("Close");
		bc.appendChild(bct);
		dl.appendChild(bc);
		
		// create the space for the list items
		var dlist = document.createElement("div");
		dlist.setAttribute("id","pg_deviceListItems");
		YUD.addClass(dlist,"devices");
		dl.appendChild(dlist);
		
		main.appendChild(dl);
		devSelect.dl = dl;
		
		// add the close function to the close button
		buttonClose = YUD.getElementsByClassName("close","a",devSelect.dl);
		YUE.addListener(buttonClose,"click",devSelect.toggleBox);
	},
	
	changeState: function(e,s) {
		var pgdl = document.getElementById("pg_deviceList");
		if (pgdl) {
			if (YUD.getStyle(pgdl,"display") == "block") {
				devSelect.display = "none";
				YUD.setStyle(pgdl,"display","none");
			}
		}

//		var c = devSelect.ds.getAttribute("class");
//		YUD.replaceClass(devSelect.ds,c,s);
		devSelect.ds.className = s;
		devSelect.writeDS();
	},
	
	writeDS: function() {
		var ds = devSelect.ds;
		var dt = document.getElementById("pg_deviceSelectorText");
		
		// create the "current" DIV (remove any that might be there first)
		var c = YUD.getElementsByClassName("current","div",dt);
		if (c.length > 0) c[0].parentNode.removeChild(c[0]);
		
		c = document.createElement("div");
		YUD.addClass(c,"current");
		dt.appendChild(c);
		
		// see if we've selected a device or not yet
		var state = "change";
		var current = ds.className;
		if (current == "deviceSelected") state = "selected";

		// if we're loading a new device show the icon
		if (YUD.hasClass(ds,"deviceLoading")) {
			var i = document.createElement("img");
			i.setAttribute("alt","Loading...");
			i.setAttribute("src","images/loading.gif");
			c.appendChild(i);
			state = "";
		}
		
		if (state != "") {
			// load up the current state's HTML
			var d = YUD.getElementsByClassName(state,"div",dt);
			if (d.length > 0) devSelect.getKids(d[0],c);
			
			// add functionality to the buttons/links
			var f = YUD.getElementsBy(alwaysTrue,"form",c);
			for (var i=0; i<f.length; i++) {
				var n = f[i].getAttribute("name");
				f[i].setAttribute("id",n);
			}
			
			cDOS = YUD.getElementsByClassName("changeDeviceOS","a");
			for (var i=0; i<cDOS.length; i++) {
				cDOS[i].setAttribute("href","javascript:void(0);");
				YUE.removeListener(cDOS[i],"click",devSelect.changeState);
				YUE.addListener(cDOS[i],"click",devSelect.changeState, "deviceChange");
			}
			cBack = YUD.getElementsByClassName("toggle","a",c);
			if (cBack.length > 0) {
				YUE.removeListener(cBack[0],"click",devSelect.changeState);
				YUE.addListener(cBack[0],"click",devSelect.changeState, "deviceSelected");
			}
			
			// add the onchange events to the two selectors (OS and DEVICE)
			sels = YUD.getElementsBy(alwaysTrue,"select",c);
			for (i=0;i<sels.length;i++) {
				sels[i].selectedIndex = 0;
				YUD.addClass(sels[i].options[0],"first");
				YUE.addListener(sels[i],"change",devSelect.getList);
			}
		}
			
		// fade in the Device Selector
		sizeImg.fade(c,"in",1,1);
	},
	
	getKids: function(d,tgt) {
		for (var i=0; i < d.childNodes.length; i++) {
			tgt.appendChild(d.childNodes[i].cloneNode(true));
		}
	},
	
	hideFirst: function(o) {
		if (YUD.hasClass(this,"hidden")) {
			YUD.removeClass(this,"hidden");
		} else {
			YUD.addClass(this,"hidden");
		}
	},
	
	myDevices: function() {
		sels = YUD.getElementsBy(alwaysTrue,"select",devSelect.ds);
		for (i=0;i<sels.length;i++) {
			if (sels[i].getAttribute("name") == "deviceManufacturer") {
				opt = YUD.getElementsByClassName("myDevices","option",sels[i])[0];
				
				arrOpts = Array();
				YUE.addListener(opt,"mouseover",devSelect.myDevicesToggle);
				YUE.addListener(opt,"mouseout",devSelect.myDevicesToggle);
			}
		}
	},
	myDevicesToggle: function(o) {
		opts = YUD.getElementsByClassName("myDevices","option",devSelect.ds);
		for (i=0;i<opts.length;i++) {
			switch (o.type) {
				case "mouseover":	YUD.addClass(opts[i],"myDevicesOn"); break;
				case "mouseout":		YUD.removeClass(opts[i],"myDevicesOn"); break;
			}
		}
	},
	
	toggleBox: function(o) {
		ie6.toggleDropdowns(null,"on"); // hide dropdowns for IE6

		// display = YUD.getStyle(devSelect.dl, "display");
		display = devSelect.display;
		if (display != "none") display = "none"; else display = "block";

		YUD.setStyle(devSelect.dl, "display", display);
		devSelect.display = display;

		// reset the combo boxes if we're closing the box.
		if (display == "none") {
			ie6.toggleDropdowns(null,"off"); // return dropdowns to page

			sels = YUD.getElementsBy(alwaysTrue,"select",devSelect.ds);
			for (i=0;i<sels.length;i++) sels[i].selectedIndex = 0;
			devSelect.start = 0;
			devSelect.results = null;
		}

		// setTimeout('YUD.setStyle(devSelect.dl,"height","auto");', 1000);
	},

	getTextList: function(o) {
		manu = document.formUser.newUser_manufacturer;
		model = document.formUser.newUser_model;

		manID = manu.options[manu.selectedIndex].value;

		if (manID != devSelect.manufacturer) {
			// clear out the model list.
			model.length = 0;
			YUD.removeClass(model,"active");

			devSelect.manufacturer = manID;
			devSelect.device = "0";
		}
		if (manID != "0") devSelect.connect(manID, "getTextList");
	},
	writeTextList: function(o) {
		// model = document.formUser.newUser_modelID;
		model = document.formUser.newUser_model;

		root = o.responseXML.documentElement;
		for (i = -1; i < root.getElementsByTagName("phone").length; i++) {
			if (i < 0) {
				oID = 0;
				oTitle = "Select your model:";
			} else {
				n = root.getElementsByTagName('phone')[i];
				oID = n.getAttribute("id");
				oTitle = n.getElementsByTagName("name")[0].firstChild.nodeValue;
			}

			opt = document.createElement("option");
			opt.setAttribute("value",oID);
			if (devSelect.device == oID) opt.setAttribute("selected", true);
			opt.innerHTML = oTitle;

			model.appendChild(opt);
		}
		YUD.addClass(model,"active");
	},
	populateTextLists: function() {
		manu = document.formUser.newUser_manufacturer;
		model = document.formUser.newUser_model;

		devSelect.device = document.formUser.newUser_modelID.value;
		devSelect.manufacturer = document.formUser.newUser_manufacturerID.value;

		// add activity on the SELECTs
		// YUE.addListener(document.getElementById("formUser"),"submit",devSelect.updateHidden);
		// YUE.addListener(manu,"change",devSelect.getTextList);
		// YUE.addListener(model,"change",devSelect.updateDevice);
		YUD.addClass(manu,"active");

		if (devSelect.manufacturer == "0" || devSelect.device == "0")  { devSelect.manufacturer = "0"; devSelect.device = "0"; }

		// first select the proper manufacturer
		for (i = 0; i < manu.length; i++) {
			if (manu.options[i].value == devSelect.manufacturer) manu.options[i].selected = true;
		}
		// then populate the second combo box
		devSelect.getTextList();
	},
	updateDevice: function() {
		devSelect.device = this.options[this.selectedIndex].value;
	},
	updateHidden: function() {
		document.formUser.newUser_manufacturerID.value = devSelect.manufacturer;
		document.formUser.newUser_modelID.value = devSelect.device;
	},

	getList: function(o) {
		// if the name of the select is deviceManufacturer, then we look up the manufacturer's devices
		// otherwise it's OS-based and we just change by OS immediately.
		name = this.getAttribute("name");
		devSelect.context = name;
		
		id = this.options[this.selectedIndex].value;
		txt = this.options[this.selectedIndex].text;

		if (name == "deviceManufacturer" || name == "newUser_manufacturer") {
			devSelect.deviceOrOS = "device";
			devSelect.start = 0;
			devSelect.results = null;

			if (id == 0) {
				devSelect.display = "block";
				devSelect.toggleBox();
			} else {
				// fire off a request for the device list for this manufacturer
				devSelect.manufacturer = txt;
				devSelect.connect(id, "");
			}
		} else {
			devSelect.display = "block";
			devSelect.toggleBox();

			// send the user to the selected OS.
			devSelect.deviceOrOS = "OS";
			// dOS = document.getElementById("selectDeviceOS");
			// devSelect.device = dOS.options[dOS.selectedIndex].value
			devSelect.device = id;

			if (id != "0") devSelect.checkWarning();
		}
	},
	resetList: function(e,o) {
		var s = this.getAttribute("status");
		if (s != "open" || typeof(s) == "undefined") {
			o.selectedIndex = 0;
			this.setAttribute("status","open");
		} else {
			this.setAttribute("status","closed");
		}
	},
	
	checkWarning: function(o) {
		if (devSelect.context == "deviceManufacturer" || devSelect.deviceOrOS == "OS") {
			// entryPoint = 'xml_incompatible.xml';
			entryPoint = 'includes/incompatibleScProductsXML.jsp';
			
			thisdate = new Date();
			queryString = encodeURI('?newDeviceId=' + devSelect.device + '&time=' + thisdate.getTime());
			sUrl = entryPoint + queryString;
				
			request = YUC.asyncRequest('GET', sUrl, { success:devSelect.showWarning, failure:devSelect.failureGeneral });
		} else {
			var phoneos = "";
			var dev = YUD.getElementsByClassName("label","div",this);
			if (dev.length > 0) {
				devSelect.deviceName = dev[0].innerHTML;
				var l = document.getElementById(devSelect.context);
				devSelect.deviceName = devSelect.deviceName.replace(l.options[l.selectedIndex].text,"").trim();
				phoneos = dev[0].parentNode.getAttribute("phoneos");
			}
			
			document.getElementById("newUser_model").value = devSelect.device;
			
			var box = document.getElementById("newUser_modelBox");
			if (box) box.value = devSelect.deviceName.replace("&amp;","&").replace(devSelect.manufacturer,"").trim();
			devSelect.toggleBox();
			
			// change the title of the "sync name" field based on the OS
			devSelect.syncNameLabel(phoneos);
		}
	},
	
	syncNameLabel: function(os) {
		// find out the operating system then change the value in "column2" in the "rowSyncName" row and make it appear
		var syncs = Array();
		syncs.push(Array("None","Sync Name"));
		if (typeof(syncNameLabels) != "undefined") {
			for (var i=0; i<syncNameLabels.length; i++) { syncs.push(syncNameLabels[i]); } 
		}
		
		if (typeof(os) == "undefined" || os == "" || syncs.length == 1) os = "None";
		
		var sID = -1;
		for (var i = 0; i < syncs.length; i++) if (syncs[i][0].replace(/ /g,"_") == os) sID = i;
		if (sID < 0) { os = "None"; sID = 0; }
		
		var rsn = document.getElementById("rowSyncName");
		if (rsn) {
			if (YUD.hasClass(rsn,"noOS")) YUD.removeClass(rsn,"noOS");
			if (os == "None") YUD.addClass(rsn,"noOS");
				
			var c2 = YUD.getElementsByClassName("column2","div",rsn);
			if (c2.length > 0) {
				c2 = c2[0];
				while (c2.childNodes[0]) c2.removeChild(c2.childNodes[0]);
				
				var txt = document.createTextNode(" "+ syncs[sID][1] +":");
				
				var sp = document.createElement("span");
				YUD.addClass(sp,"required");
				sp.innerHTML = "*";
				
				c2.appendChild(sp);
				c2.appendChild(txt);

			}

			YUD.setStyle(rsn,"display","block");
		
			// fix the tooltips to only show the one related to the current operating system.
			var tt = YUD.getElementsByClassName("tooltip","div",rsn);
			if (tt.length > 0) {
				var b = YUD.getElementsByClassName("body","div",tt[0]);
				for (var i = 0; i < b.length; i++) {
					YUD.addClass(b[i],"hidden");
					if (b[i].getAttribute("phoneos") == os) YUD.removeClass(b[i],"hidden");
				}
			}
		}

	},
	
	showWarning: function(o) {
		// get the response information.
		root = o.responseXML.documentElement;
		products = root.getElementsByTagName("product");
		arrLength = products.length;

		// if the list is empty, there are no incompatible items, so continue
		if (arrLength > 0 && document.getElementById("leftNavSuccessUrl")) { 
			// document.getElementById("leftNavSuccessUrl").value = "cartNoIncompat.jsp?_dyncharset=UTF-8&%2Fmotricity%2Fcommerce%2Forder%2FRemoveIncompatibleItemsFormHandler.removalCommerceIds=&_D%3A%2Fmotricity%2Fcommerce%2Forder%2FRemoveIncompatibleItemsFormHandler.removalCommerceIds=+&%2Fmotricity%2Fcommerce%2Forder%2FRemoveIncompatibleItemsFormHandler.removeIncompatItemsFromOrder=remove&_D%3A%2Fmotricity%2Fcommerce%2Forder%2FRemoveIncompatibleItemsFormHandler.removeIncompatItemsFromOrder=+&_DARGS=%2Fen_US%2Fhtml%2FcartNoIncompat.jsp.1"; 
			// document.getElementById("leftNavSuccessUrl").value = "cartNoIncompat.jsp";
			document.getElementById("leftNavSuccessUrl").value = location.href;
		}
		else if (arrLength == 0) { devSelect.postDevice(); return true; }

		// create a list of devices.
		list = "";
		for (i = 0; i < arrLength; i++) {
			name = "";
			if (products[i].getElementsByTagName('name')[0].hasChildNodes())
				name = products[i].getElementsByTagName('name')[0].firstChild.nodeValue;
			list += "<li>"+name+ "</li>\n";
		}

		msg = "<img class=\"icon\" src=\"images/messaging/icon-error.gif\" />";
		msg += "<p>The following items are incompatible with the " +(devSelect.deviceOrOS == "OS" ? "operating system" : "device") + " you have selected.</p>\n";
		msg += "<ul>\n" +list+ "</ul>\n";
		msg += '<p class="center">Do you wish to continue?</p>\n';
		msg += '<div class="buttons"><img src="images/buttons/continue.gif" class="button active" alt="Continue" /> <img src="images/buttons/cancel.gif" class="button active" alt="Cancel" /></div>\n';

		msg = '<div class="a"><div class="b"><div class="c"><div class="text">\n' + msg + '</div></div></div></div>';
		
		// hide all drop-downs temporarily (IE6 fix)
		ie6.toggleDropdowns(null,"on");
		
//		ct = document.createElement("div");
//		YUD.addClass(ct,"text");
//		ct.innerHTML = msg;

		ca = document.createElement("div");
		ca.className = "a";
		cb = document.createElement("div");
		cb.className = "b";
		cc = document.createElement("div");
		cc.className = "c";

//		cc.appendChild(ct);
//		cb.appendChild(cc);
//		ca.appendChild(cb);
//		conf.appendChild(ca);

		conf = document.createElement("div");
		conf.setAttribute("id","pg_confirmation");
		YUD.addClass(conf,"message");
		YUD.addClass(conf,"msg_error");
		conf.innerHTML = msg;

		main = document.getElementById("pg_main");
		main.appendChild(conf);
		
		buttons = YUD.getElementsByClassName("button","img",conf);
		actionImages.addActions(buttons[0]);
		actionImages.addActions(buttons[1]);
		YUE.addListener(buttons[0],"click",devSelect.postDevice);
		YUE.addListener(buttons[1],"click",devSelect.hideWarning);

		YUD.setStyle(conf,"display","block");
	},
	
	hideWarning: function(o) {
		devSelect.device = "";
		var f = document.getElementById("formOSSelector");
		if (f) {
			var os = YUD.getElementsBy(alwaysTrue,"select",f);
			if (os.length > 0) os[0].selectedIndex = 0;
		}

		conf = document.getElementById('pg_confirmation');
		conf.parentNode.removeChild(conf);

		// return all drop-downs (IE6 fix)
		ie6.toggleDropdowns(null,"off");

	},

	pickDevice: function(did) {
		devSelect.device = did;
		devSelect.deviceOrOS = "OS";
		
		devSelect.checkWarning();
	},
	
	postDevice: function (o) {
		document.getElementById("theDeviceId").value = devSelect.device;

		frm = document.getElementById("formDeviceSelector");
		
		// add the "Loading" icon to the device selector
		devSelect.changeState(null,"deviceLoading");
		
		frm.action = location.href; // "pg_topDeviceSelected.split.php";
		// setTimeout("frm.submit();",2000);
		frm.submit();
	},

	connect: function(id, action) {
		if (id == "other") return devSelect.groupBuild();
		
		// var entryPoint = 'xml_devices2.xml';
		var entryPoint = 'includes/devicesByManufacturer.jsp';

		thisdate = new Date();
		var queryString = encodeURI('?manId=' + id + "&time=" + thisdate.getTime());
		var sUrl = entryPoint + queryString;

		switch(action) {
			case "registerUser":	var request = YUC.asyncRequest('GET', sUrl, { success:devSelect.newUserSuccess, failure:devSelect.failureGeneral }); break;
			case "getTextList":	var request = YUC.asyncRequest('GET', sUrl, { success:devSelect.writeTextList, failure:devSelect.failureGeneral }); break;
			
			default:			loading = '<div class="devices loading"><div class="title">Loading Devices...</div><img src="images/loading.gif" alt="Loading..." /></div>\n';
						d = document.getElementById("pg_deviceListItems"); 
						if (YUD.hasClass(d.parentNode,"error")) YUD.removeClass(d.parentNode,"error");
						d.innerHTML = loading;
						if (devSelect.display == "none") devSelect.toggleBox();
						
						setTimeout("var request = YUC.asyncRequest('GET', '" +sUrl+ "', { success:devSelect.parseResults, failure:devSelect.failureDevices });", 500);
						break;
		}
	},

	newUserSuccess: function(o) {
		var root = o.responseXML.documentElement;
		var arrLength = root.getElementsByTagName('name').length;
		var grabSelector = document.getElementById('selectDeviceId');
		var hiddenDeviceHtml = document.getElementById('hiddenDeviceSelect');
		var exposedDeviceContent = document.getElementById('userDeviceModel');

		document.getElementById('selectDeviceId').options.length = 0;

		for (i=0; i < arrLength; i++) {
			oTitle = root.getElementsByTagName('name')[i].firstChild.nodeValue;
			oId = root.getElementsByTagName('phone')[i].getAttribute("id");

			grabSelector.options[i]=new Option(oTitle, oId, false, false);
		}

		exposedDeviceContent.innerHTML = hiddenDeviceHtml.innerHTML;
	},

	failureDevices: function(o) {
		myError = '<div class="title">Failed to Load</div>\n\n';
		myError += '<p class="message">There was a problem retrieving the list of devices. Please try again.<br /><br />If the problem persists, please <a href="contactUs.jsp">contact customer service</a>.</p>';		
		myError += '<div class="divider dividerNoLine"><!-- --></div>\n';
		
		d = document.getElementById("pg_deviceListItems");
		l = YUD.getElementsBy(alwaysTrue,"img",d)[0];
		l.parentNode.removeChild(l);

		YUD.addClass(d.parentNode,"error");
		d.innerHTML = myError;
	},
	
	showSort: function(o,e) {
		var dssl = document.getElementById("dsSortLabel");
		var dssla = dssl.getElementsByTagName("a")[0];
		
		dssla.setAttribute("onclick","");
		YUE.removeListener(dssla,"click");
		
		if (e == "off") {
			var dsslist = document.getElementById("dsSortList");
			dsslist.parentNode.removeChild(dsslist);
			YUE.addListener(dssla,"click",devSelect.showSort,"on");
			
		} else {
			var sort = Array(Array("Sort the devices alphabetically (A to Z)","alpha"),Array("Sort the devices chronologically (newer to older)","chrono"));
			
			var ul = document.createElement("ul");
			ul.setAttribute("id","dsSortList");
			
			var li = document.createElement("li");
			var lia = document.createElement("a");
			for (var i=0; i<sort.length; i++) {
				var liat = lia.cloneNode(true);
				liat.innerHTML = sort[i][0];
				liat.setAttribute("href","javascript:void(0);");
				YUE.addListener(liat,"click",devSelect.doSort,sort[i][1]);

				var lit = li.cloneNode(true);
				lit.appendChild(liat);
				ul.appendChild(lit);
			}
			dssl.parentNode.parentNode.appendChild(ul);
			YUE.addListener(dssla,"click",devSelect.showSort,"off");
		}
	},
	doSort: function(e,o) {
		switch(o) {
			case "alpha":		// resort the array by function
							devSelect.resultsArray = devSelect.resultsArray.sort(devSelect.sortByName); break;
			case "chrono": 	// reset the array to its original order
							devSelect.resultsArray = devSelect.resultsSorted.slice(); break;
		}
		devSelect.start = 0;
		var tmp = ""; if (devSelect.textOnly) tmp = "all";
		devSelect.showDevices(null,tmp);
	},
	sortByName: function(a, b) {
		var x = a[0].toLowerCase();
		var y = b[0].toLowerCase();
		return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	},
	
	parseResults: function(o) {
		devSelect.resultsArray = Array();
		
		root = o.responseXML.documentElement;
		arrLength = root.getElementsByTagName("name").length;
		
		for (var i=0; i < arrLength; i++) {
			n = root.getElementsByTagName('phone')[i];
			
			oID = n.getAttribute("id");
			oTitle = n.getElementsByTagName("name")[0].firstChild.nodeValue;
			
			oOS = "None";
			var nOS = n.getElementsByTagName('phoneos');
			// need to be sure <phoneos/> is set on all devices
			if (nOS.length > 0) if (nOS[0].firstChild) oOS = nOS[0].firstChild.nodeValue;
			
			oImage = "";
			imgsrc = "images/devices/126x126/_other_126x126.gif";
			if (n.getElementsByTagName('imageurl')[0].hasChildNodes()) {
				oImage = n.getElementsByTagName('imageurl')[0].firstChild.nodeValue;
				oImage = oImage.replace("_48x75","_126x126");
			}
			if (oImage != "") imgsrc = oImage;
			
			var tmp = Array(oTitle,oID,imgsrc,oOS);
			devSelect.resultsArray.push(tmp);
		}
		devSelect.resultsSorted = devSelect.resultsArray.slice();
		
		devSelect.showDevices(null,"");
	},
	
	showDevices: function(o,param) {
		if (param == "all") devSelect.textOnly = true; else devSelect.textOnly = false;
		
		// if (devSelect.results == null) devSelect.results = o;
		// root = devSelect.results.responseXML.documentElement;
		arrLength = devSelect.resultsArray.length;
		
		var myTitle = devSelect.manufacturer;
		if (devSelect.manufacturer == "View My Devices") myTitle = 'My Devices'; 
		
		// handle getting more devices from the list than are displayed
		start = devSelect.start;
		end = start + devSelect.perPage;
		previous = start - devSelect.perPage; if (previous < 0) previous = 0;
		
		aMore = '<a class="more" onclick="devSelect.start=' +end+ '; devSelect.showDevices(null);" href="javascript:void(0);">More Devices &#187;</a>\n';
		if (end >= arrLength) {
			end = arrLength;
			aMore = '<a class="more moreNoDevice" href="contactUs.jsp?supportRequest=missingDevice">' +
				'Click here if you are unable to find your device.</a>\n';
		}
		
		aLess = '';
		if (start > 0) {
			aLess = '<a class="less" onclick="devSelect.start=' +previous+ '; devSelect.showDevices(null);" href="javascript:void(0);">&#171; Back</a>\n';
		}

		var subTitle = ': ' + arrLength + ' Devices';
		if (param == "all") {
			start = 0; end = arrLength;
		} else {
			if (arrLength > devSelect.perPage)
				subTitle = ': Devices ' + (start+1) + '-' +end+ ' of ' + arrLength;
		}
		
		var toggle = 'null,\'all\');">Text Only'; if (param == "all") toggle = 'null);">Show Images'; 
		toggle = ' <span class="completeList">// <a href="javascript:void(0);" onclick="devSelect.showDevices(' +toggle+ '</a></span>\n';

		var sort = ' <span class="sortList" id="dsSortLabel">// <a href="javascript:void(0);">Sort List</a></span>\n';
		
		if (arrLength < devSelect.perPage+1) toggle = ''; 
		myItems = '<div class="title">' +myTitle+subTitle+toggle+sort+ '</div>\n\n';
		
		for (i=start; i < end; i++) {
			if (i % Math.round(devSelect.perPage/2) == 0 && i > 0) myItems += '<div class="clear">&nbsp;</div>\n';

			oTitle = devSelect.resultsArray[i][0];
			oID = devSelect.resultsArray[i][1];
			imgsrc = devSelect.resultsArray[i][2];
			oOS = devSelect.resultsArray[i][3];

			var img = '<img src="' +imgsrc + '" /><div class="label">'; var cl = '';
			if (param == "all") { img = ''; cl += ' deviceAll'; }
			myItems += '<div class="device' +cl+ '" phoneos="' +oOS+ '" onclick="devSelect.device=\'' +oID+ '\';">' +img+oTitle+ '</div></div>\n';
		}
		if ((end -start) <= Math.round(devSelect.perPage/2)) {
			myItems += '<div class="divider dividerNoLine dividerFiller"><!-- --></div>\n';
		}
		// add a message about choosing OS
		myItems += '<div class="instructions"><p>Please select your device from the choices above. If there are more than ' +devSelect.perPage+ ' devices from this manufacturer, you can scroll through them by ' +
			'clicking the <b>More Devices</b> link (bottom right). If you are still unable to find your device, please consider (A) browsing by your device\'s operating system below and (B) ' +
			'<a href="contactUs.jsp?supportRequest=missingDevice">letting us know</a> your device model so we can add it.</p>\n' +
			'<ul><li><a href="javascript:void(0);" onclick="devSelect.pickDevice(\'10035900022\');">&#187; BlackBerry</a></li>\n' +
			'<li><a href="javascript:void(0);" onclick="devSelect.pickDevice(\'xpg1010000\');">&#187; Palm OS</a></li>\n' +
			'<li><a href="javascript:void(0);" onclick="devSelect.pickDevice(\'xpg1020000\');">&#187; Windows Mobile Pocket PC</a></li>\n' +
			'<li><a href="javascript:void(0);" onclick="devSelect.pickDevice(\'xpg1030000\');">&#187; Windows Mobile Smartphone</a></li>\n</ul>\n' +
			'</div>\n';
		myItems += '<div class="divider dividerNoLine"><!-- --></div>\n';

		// add the navigation
		if (param != "all") myItems += '<div class="navigation">' +aLess+aMore+ '</div>';

		// throw the HTML into the device list DIV
		d = document.getElementById("pg_deviceListItems");
		d.innerHTML = myItems;

		dList = YUD.getElementsByClassName("device","div",d);
		YUE.addListener(dList,'mouseover',devSelect.toggleClass);
		YUE.addListener(dList,'mouseout',devSelect.toggleClass);
		YUE.addListener(dList,'click',devSelect.checkWarning);

		var dssl = document.getElementById("dsSortLabel");
		var dssla = dssl.getElementsByTagName("a")[0];
		YUE.addListener(dssla,"click",devSelect.showSort,"on");
		
		// if (devSelect.display == "none") devSelect.toggleBox();
	},

	failureGeneral: function(o) {
		// alert("There was a problem completing your request. Please try again.");
		// alert("failed");
	},

	toggleClass: function(o) {
		if (o.type == "mouseout") YUD.removeClass(this,"active"); else YUD.addClass(this,"active");
	}
}

var preloadImage = {
	list: Array(),

	add: function(img) {
		if (document.images) {
			img1 = new Image();
			img1.src = img;
			preloadImage.list.push(img1);
		}
	}
}

var advertising = {
	adCount: 0,
	adLoading: 0,
	
	init: function(rTime) {
		if (typeof(currentSelectedDevice) == "undefined") currentSelectedDevice = "Other";
		if (typeof(currentSelectedDeviceOS) == "undefined") currentSelectedDeviceOS = "Other";

		ads = YUD.getElementsByClassName("adspace","div");
		for (i=0;i<ads.length;i++) {
			server = ads[i].getAttribute("server"); if (!server) server="http://pbh.adbureau.net";
			
			target = ads[i].getAttribute("target");
			load = ads[i].getAttribute("load"); if (!load) load = "post";
			
			width = YUD.getStyle(ads[i],"width").replace("px","");
			height = YUD.getStyle(ads[i],"height").replace("px","");
			
			if (server && target && rTime == load) {
				// add the device and operating system to the advertisement call (if applicable)
				target = target.replace("[[DEVICE]]", currentSelectedDevice).replace("[[DEVICEOS]]", currentSelectedDeviceOS);
				random = Math.round ( Math.random() * 100000000); 
				if (!pageNum) var pageNum = Math.round ( Math.random() * 100000000 );
				src = server + '/hserver/acc_random=' + random + target + "/pageid=" + pageNum;
				
				name = "adspace_" + ads[i].getAttribute("id"); // create/enforce the "name" attribute on the iframe
				
				html = '<iframe name="' +name+ '" class="ad" src="' +src+ '" frameborder="0" scrolling="no" width="' +width+ '" height="' +height+ '" noresize="true" marginheight="0" marginwidth="0"></iframe>';
				ads[i].innerHTML = html;

				advertising.fadeIn(ads[i],i);
			}
		}
	},

	fadeIn: function(ad,loc) {
		// randomize the duration of fade-in
		var random = Math.round (Math.random() * 30) / 10; 
		var myAnim = new YAHOO.util.Anim(ad);
		myAnim.attributes.opacity = { from: 0, to: 1 };
		myAnim.duration = random;
		myAnim.animate();
	}
}

var highlights = {
	// this object is intended to manage any generic highlighting we need to add.
	// it will add a class called "on" to whichever elements it is applied.
	divs: Array("legacyPocketgear","legacyPalmgear"),
	
	init: function() {
		for (i=0; i<highlights.divs.length; i++) {
			thisDiv = document.getElementById(highlights.divs[i]);
			if (thisDiv) {
				highlights.getA(thisDiv);
				YUE.addListener(thisDiv,"mouseover",highlights.toggle, Array(thisDiv, "on"));
				YUE.addListener(thisDiv,"mouseout",highlights.toggle, Array(thisDiv, "off"));
				
				// preload any relevant imagery
				sizeImg.loadImg("images/" +highlights.divs[i]+ ".gif");
				sizeImg.loadImg("images/" +highlights.divs[i]+ ".jpg");
			}
		}
	},
	
	getA: function(td) {
		a = YUD.getElementsBy(alwaysTrue,"a",td)[0];
		if (a) {
			href = a.getAttribute("href");
			YUE.addListener(td,"click", highlights.getAGo, href);
		}
	},
	getAGo: function(e, h) {
		window.location.href = h;
	},
	
	toggle: function(e, objstate) {
		if (objstate[1] == "off") {
			YUD.removeClass(objstate[0], "on");
		} else {
			YUD.addClass(objstate[0], "on");
		}
	}
}

var allCats = {
	ac: null,
	
	init: function() {
		var bc = document.getElementById("pg_breadcrumbs");
		allCats.ac = document.getElementById("w299_12");
		var ac = allCats.ac;
		
		if (ac && bc) {
			var a = YUD.getElementsBy(alwaysTrue,"a",bc);
			for (var i=0; i < a.length; i++) {
				if (a[i].childNodes.length > 0) {
					if (a[i].childNodes[0].nodeValue == "All Categories") {
						a[i].setAttribute("href","javascript:void(0);");
						a[i].setAttribute("onclick","void(0);");
						YUE.addListener(a[i],"click",allCats.toggle);
					}
				}
			}
			
			var c = YUD.getElementsByClassName("close","div",ac);
			for (var i=0; i < c.length; i++) {
				if (c[i].childNodes.length > 0) {
					var a = c[i].childNodes[0];
					if (a.nodeName == "A") {
						a.setAttribute("href","javascript:void(0);");
						a.setAttribute("onclick","void(0);");
						YUE.addListener(a,"click",allCats.toggle);
					}
				}
			}
		}
	},
	
	toggle: function() {
		var v = YUD.getStyle(allCats.ac,"display");
		if (v != "block") {
			YUD.setStyle(allCats.ac,"display","block");
			ie6.toggleDropdowns(null,"on");
		} else {
			YUD.setStyle(allCats.ac,"display","none");
			ie6.toggleDropdowns(null,"off");
		}
	}
}

var tabs = {
	t: null,
	
	init: function() {
		tabs.t = document.getElementById("navTabs");
		if (tabs.t) {
			tabs.loadImages();
			//tabs.totalProducts();
			tabs.empty();
			
			// add IE6 hiders
			YUE.addListener(tabs.t,"mouseover",ie6.toggleDropdowns,"on");
			YUE.addListener(tabs.t,"mouseout",ie6.toggleDropdowns,"off");
			
			tabs.addAll();
		}
	},
	
	loadImages: function() {
		// load up the tab images.
		sizeImg.loadImg("images/tabs/home.gif");
		sizeImg.loadImg("images/tabs/sublevel1.jpg");
		
		sizeImg.loadImg("images/tabs/off.gif");
		sizeImg.loadImg("images/tabs/off-right.gif");
		sizeImg.loadImg("images/tabs/on.gif");
		sizeImg.loadImg("images/tabs/on-right.gif");

		sizeImg.loadImg("images/tabs/left.gif");
		sizeImg.loadImg("images/tabs/left-current.gif");
		sizeImg.loadImg("images/tabs/left-on.gif");

		sizeImg.loadImg("images/tabs/current.gif");
		sizeImg.loadImg("images/tabs/current-right.gif");
	},
	
	empty: function() {
		var li = tabs.t.getElementsByTagName("a");
		for (var i=0; i<li.length; i++) {
			var c = YUD.getElementsByClassName("count","span",li[i]);
			if (c.length > 0) {
				c = parseInt(c[0].innerHTML.replace("(","").replace(")","").replace(" ",""));
				if (c == 0) YUD.addClass(li[i].parentNode,"empty");
			}
		}
	},
	
	totalProducts: function() {
		var dst = document.getElementById("pg_deviceSelectorText");
		if (dst) {
			var s = YUD.getElementsByClassName("selected","div",dst);
			if (s.length > 0) {
				// get the count
				var cnt = tabs.getCount();
				if (cnt > 0) {
					cnt = number_format(cnt, 0,"",",") + " titles available for:";
					
					var st = YUD.getElementsByClassName("title","div",s[0])[0];
					var c = YUD.getElementsByClassName("current","div",dst);
					st.innerHTML = cnt;
					
					if (c.length > 0) {
						c = c[0];
						var ct = YUD.getElementsByClassName("title","div",c)[0];
						ct.innerHTML = st.innerHTML;
					}
				}
			}
		}
	},
	getCount: function() {
		var total = 0;
		var t = YUD.getElementsByClassName("drop","li",tabs.t);
		for (var i=0; i<t.length; i++) {
			if (YUD.hasClass(t[i].parentNode,"tabs") && !YUD.hasClass(t[i],"dynamic")) {
				var sp = YUD.getElementsByClassName("count","span",t[i]);
				if (sp.length > 0) {
					total += parseInt(sp[0].innerHTML.replace("(","").replace(")","").replace(" ",""));
				}
			}
		}
		return total;
	},
	
	addAll: function() {
		// add an "All X" category to the bottom of any Level 1 list
		var ult = YUD.getElementsByClassName("tabs","ul",tabs.t);
		if (ult.length > 0) {
			var top = Array();
			var li = ult[0].getElementsByTagName("li");
			for (var i=0; i<li.length; i++) {
				if (li[i].parentNode == ult[0]) {
					var ul = li[i].getElementsByTagName("ul");
					if (ul.length > 0) {
						top.push(Array(li[i],ul[0]));
					}
				}
			}
			for (i=0; i<top.length; i++) {
				var a = top[i][0].getElementsByTagName("a")[0];
				
				var lilast = null;
				var li = top[i][1].getElementsByTagName("li");
				for (var j=0; j<li.length; j++) {
					if (li[j].parentNode == top[i][1] && YUD.hasClass(li[j],"last")) lilast = li[j];
				}
				if (a && lilast) {
					var newa = a.cloneNode(true);
					var sp = newa.getElementsByTagName("span");
					for (j=0; j<sp.length; j++) sp[j].parentNode.removeChild(sp[j]);
					newa.innerHTML = "All " +newa.innerHTML+ " Titles";
					
					var linew = document.createElement("li");
					YUD.addClass(linew,"last");
					linew.appendChild(newa);
					lilast.parentNode.appendChild(linew);
					YUD.removeClass(lilast,"last");
				}
			}
		}
	}
}

var click = {
	init: function() {
		click.makeClickable(null);
	},
	makeClickable: function(o) {
		if (!o) o = YUD.getElementsByClassName("clickable"); else o = Array(o);
		for (var i=0; i<o.length; i++) {
			var a = o[i].getElementsByTagName("a");
			if (a.length > 0) {
				YUE.removeListener(o[i]);
				YUE.addListener(o[i],"click",click.go,a[0].getAttribute("href"));
				YUE.addListener(o[i],"mouseover",click.toggle,o[i]);
				YUE.addListener(o[i],"mouseout",click.toggle,o[i]);
			}
		}
	},
	toggle: function(e,o) {
		if (e.type == "mouseover") {
			YUD.addClass(o,"on");
		} else {
			YUD.removeClass(o,"on");
		}
	},
	go: function(e,h) {
		window.location.href = h;
	}
}

var round = {
	init: function() {
		round.getParents();
		round.addCorners();
	},
	getParents: function() {
		var l = YUD.getElementsByClassName("roundedList");
		for (var i=0; i<l.length; i++) {
			var li = l[i].getElementsByTagName("li");
			for (var j=0; j<li.length; j++) {
				YUD.addClass(li[j],"rounded");
				YUD.addClass(li[j],"clickable");
			}
			
			// load up the account list backgrounds if we're on that page
			sizeImg.loadImg("images/account/purchase_history_on.gif");
			sizeImg.loadImg("images/account/wish_list_on.gif");
			sizeImg.loadImg("images/account/store_credits_on.gif");
			sizeImg.loadImg("images/account/edit_profile_on.gif");
			sizeImg.loadImg("images/account/manage_newsletters_on.gif");
			sizeImg.loadImg("images/account/manage_devices_on.gif");
			sizeImg.loadImg("images/account/credit_cards_on.gif");
			sizeImg.loadImg("images/account/change_password_on.gif");
			sizeImg.loadImg("images/account/change_email_on.gif");
		}
		
	},
	addCorners: function() {
		var corner = document.createElement("div");
		YUD.addClass(corner,"corner");
		
		var r = YUD.getElementsByClassName("rounded");
		for (var i=0; i<r.length; i++) {
			var tl = corner.cloneNode(true);
			YUD.addClass(tl,"topleft");
			var tr = corner.cloneNode(true);
			YUD.addClass(tr,"topright");
			var bl = corner.cloneNode(true);
			YUD.addClass(bl,"bottomleft");
			var br = corner.cloneNode(true);
			YUD.addClass(br,"bottomright");
			
			r[i].appendChild(tl);
			r[i].appendChild(tr);
			r[i].appendChild(bl);
			r[i].appendChild(br);
		}
	}
}

var background = {
	b: "",
	
	init: function() {
		var b = document.getElementById("background");
		if (!b) {
			b = document.createElement("div");
			b.innerHTML = "&nbsp;";
			b.setAttribute("id","background");
			document.body.appendChild(b);
		}
		background.b = b;

		background.width();
		YUE.addListener(window,"resize",background.width);
		
		var s = sizeImg.getSize(document.body);
		YUD.setStyle(b,"height",(s[1]+20)+"px");
		YUD.addClass(document.body,"gray");
	},
	width: function() {
		var body = sizeImg.getSize(document.body)[0];
		var back = sizeImg.getSize(background.b)[0];
		
		YUD.removeClass(document.body,"lefty");
		if (body <= back) YUD.addClass(document.body,"lefty");
	}
}

var redirects = {
	pgb: "",
	
	sites: Array(),
	text: Array(),
	
	init: function() {
		redirects.pgb = document.getElementById("pg_body");
		
		redirects.sites.push("PalmGear.com");
		redirects.text.push('<img class="logo" src="images/logos/PDAGear.gif" alt="PalmGear.com" />\n' +
			'<div class="text">\n' +
			'<h3>Great News!<br />PalmGear Joins NEW PocketGear!</h3>\n' +
			'<p>PalmGear, and its extensive catalogue of Palm OS&reg; software applications, is now part of our <em><b>new</b></em> PocketGear.com -\n' + 
			'	rapidly becoming one of the world\'s largest "superstores" for mobile applications. In addition to Palm OS&reg; applications, you will also \n' +
			'	find software for Windows Mobile&reg; devices and more...</p>\n' +
			'<h4>Making it better for you!</h4>\n' +
			'<ul>\n' +
			'<li><b>Improved design</b>, <b>improved navigation</b>, and an <b>improved shopping experience</b>.</li>\n' +
			'<li><b>EZ log in - just use your PalmGear account information.</b>  All PalmGear customer accounts have been migrated to PocketGear.</li>\n' +
			'<li><b>Content Specific for Your Device</b> - PocketGear.com features a <b>device selector</b>, so you\'ll easily select from applications compatible to your device.</li>\n' +
			'<li><b>More Savings!</b> A unified storefront allows our marketing team to run more site-relevant promotions, which in turn, means more savings for you!</li>\n' +
			'</ul>\n' +
			'<p>We hope you enjoy the <b>NEW PocketGear</b> and please be sure to change your PalmGear.com bookmarks to PocketGear.com!</p>\n' +
			'<img class="continue active" alt="Close This Window" src="images/buttons/closeThisWindow.gif" />\n' +
			'</div>');
		
		for (var i=0; i<redirects.sites.length; i++) {
			var a = Array("get",redirects.sites[i]);
			if (redirects.pgb && !redirects.cookie(null,a) && redirects.checkSite(redirects.sites[i])) {
				redirects.createDiv(redirects.sites[i], redirects.text[i]);
			}
		}
	},
	checkSite: function(s) {
		s = s.toLowerCase();
		var r = getQueryVariable("referrer");
		if (r == "") var r = document.referrer;
		if (r.search(s) >= 0) return true; 
		else return false;
	},
	
	cookie: function(e,a) {
		var action = a[0];
		var site = a[1];
		var c = site.replace(".net","").replace(".com","") + "Redirect";
		switch (action) {
			case "get":	return Get_Cookie(c); break;
			case "set":	return Set_Cookie(c,'Viewed',10000); break;
		}
	},
	
	createDiv: function(s,t) {
		var e = document.createElement("div");
		e.setAttribute("id","hideEverything");
		e.innerHTML = "&nbsp;";
		
		redirects.pgb.appendChild(e);
		sizeImg.fade(e,"in",0.5,0.4);
		
		var d = document.createElement("div");
		d.setAttribute("id","fullPopup");
		YUD.addClass(d,"palmGear");
		d.innerHTML = t;
		
		redirects.pgb.appendChild(d);
		sizeImg.fade(d,"in",1,1);
		
		ie6.toggleDropdowns(null,"on");

		var a = Array("set",s);
		YUE.addListener(d,"click",redirects.cookie,a);
		
		YUE.addListener(d,"click",ie6.toggleDropdowns,"off");
		YUE.addListener(d,"click",redirects.fadeDiv,d);
	},
	fadeDiv: function(e,o) {
		var d = document.getElementById("fullPopup");
		if (d) { sizeImg.fade(d,"out",0.5,1); }
		var e = document.getElementById("hideEverything");
		// if (e) { sizeImg.fade(e,"out",0.5,0.33); }
		e.parentNode.removeChild(e);
		if (e||d) setTimeout("redirects.removeDiv();",500);
	},
	removeDiv: function() {
		var e = document.getElementById("hideEverything");
		if (e) e.parentNode.removeChild(e);
		var d = document.getElementById("fullPopup");
		if (d) d.parentNode.removeChild(d);
	}
}

var notices = {
	today: 0,
	
	init: function() {
		var cd = document.getElementById("currentDate");
		if (cd) notices.today = cd.innerHTML.replace(/-/g,"").trim();
		
		var n = YUD.getElementsByClassName("notice","span");
		for (var i=0; i<n.length; i++) {
			var show = true;
			var d = n[i].getAttribute("expires");
			if (d && d != "") show = notices.check(d.replace(/-/g,"").trim());
			if (show) YUD.addClass(n[i],"active");
		}
	},
	check: function(d) {
		var r = false;
		if (d >= notices.today || notices.today == 0) r = true;
		return r;
	}
}

var qa = {
	q: Array(),
	a: Array(),

	init: function() {
		var W3CDOM = (document.createElement && document.getElementsByTagName);
		if (!W3CDOM) return;
		
		var div = YUD.getElementsByClassName("qa");
		for (var i=0; i<div.length; i++) qa.activate(div[i]);
	},
	activate: function(d) {
		qa.q = YUD.getElementsByClassName("qa_Question","*",d);
		qa.a = YUD.getElementsByClassName("qa_Answer","*",d);
		
		
		for (var i=0; i<qa.q.length; i++) {
			var id = qa.q[i].getAttribute("id");
			if (id) {
				for (var j=0; j<qa.a.length; j++) {
					if (YUD.hasClass(qa.a[j],id)) {
						var tmp = Array(qa.q[i],qa.a[j]);
						YUE.addListener(qa.q[i],"click",qa.toggle,tmp);
						YUE.addListener(qa.q[i],"mouseover",qa.hover,qa.q[i]);
						YUE.addListener(qa.q[i],"mouseout",qa.hover,qa.q[i]);
						YUD.addClass(qa.q[i],"ready");
					}
				}
			}
		}
	},
	hover: function(e,q) {
		if (e.type == "mouseout") {
			YUD.removeClass(q,"hover");
		} else {
			YUD.addClass(q,"hover");
		}
	},
	toggle: function(e,a) {
		var answers = qa.a; var questions = qa.q;
		var answer = a[1]; var question = a[0];
		
		YUD.removeClass(questions,"toggle");
		
		var qatmp = Array(question,answer);
		for (var i=0; i<answers.length; i++) {
			if (answers[i] == answer) {
				if (YUD.hasClass(answers[i],"toggle")) YUD.removeClass(qatmp,"toggle"); else YUD.addClass(qatmp,"toggle");
			} else {
				YUD.removeClass(answers[i],"toggle");
			}
		}
		
/*		var replace = document.createElement('img');
		for (var i=0; i<questions.length; i++) {
			img = questions[i].getElementsByTagName("img");
			if (img.length > 0) {
				img = img[0];
				var src = img.getAttribute("src");
				if (questions[i] == question && YUD.hasClass(questions[i],"toggle")) {
					src = src.replace(".gif","-toggle.gif").replace(".jpg","-toggle.jpg");
				} else {
					src = src.replace("-toggle.",".");
				}

				var newimg = replace.cloneNode(true);
				newimg.src = src;
				newimg.alt = img.firstChild.nodeValue;
				img.replaceChild(newimg,img.firstChild);
			}
		}
*/
	}
}

var productDetailTabs = {
	pd: '',
	sections: "",
	tabs: "",
	
	maxHeight: 0,
	incoming: "",
	
	init: function() {
		var pd = YUD.getElementsByClassName("productDetail","div");
		if (pd.length > 0) {
			productDetailTabs.load();
		
			for (var i=0; i<pd.length; i++) {
				if (YUD.hasClass(pd[i],"item")) {
					productDetailTabs.pd = pd[i];
					productDetailTabs.arrange();
					productDetailTabs.internal();
					productDetailTabs.goTabs();
				}
			}
		}
	},
	
	load: function() {
		sizeImg.loadImg("images/corners/rb-009933_333333-tl.gif");
		sizeImg.loadImg("images/corners/rb-009933_333333-tr.gif");
		sizeImg.loadImg("images/corners/rb-009933_333333-tl.gif");
		sizeImg.loadImg("images/corners/rb-66CC33_333333-tl.gif");
		sizeImg.loadImg("images/corners/rb-66CC33_333333-tr.gif");
		sizeImg.loadImg("images/corners/rb-FFFFFF_333333-tl.gif");
		sizeImg.loadImg("images/corners/rb-FFFFFF_333333-tr.gif");
		sizeImg.loadImg("images/corners/tab-bkg.jpg");
		sizeImg.loadImg("images/corners/tab-hover.jpg");
	},
	goTabs: function() {
		if (productDetailTabs.incoming != "" && productDetailTabs.incoming != "top") location.href = "#producttabs";
	},
					
	arrange: function() {
		var pds = YUD.getElementsByClassName("productSections","div",productDetailTabs.pd);
		if (pds.length > 0) {
			pds = pds[0];
			var s = YUD.getElementsByClassName("section","div",pds);
			var t = YUD.getElementsByClassName("productTabs","ul",productDetailTabs.pd);

			if (t.length > 0) {
				productDetailTabs.sections = s;
				productDetailTabs.tabs = t[0];
				
				var li = t[0].getElementsByTagName("li");
				
				for (var i=0; i<li.length; i++) {
					if (YUD.hasClass(li[i],"first")) YUD.addClass(li[i],"current");
				
					var a = li[i].getElementsByTagName("a");
					var h = a[0].getAttribute("href");
					h = h.substring(h.indexOf("#")+1);
					// var h = a[0].getAttribute("href").replace("#","");
					
					var hs = null;
					for (var j=0; j<s.length; j++) {
						var sa = s[j].getElementsByTagName("a");
						if (sa.length > 0) {
							if (sa[0].getAttribute("name") == h) hs = s[j];
						}
					}
					if (hs) {
						var hsh = sizeImg.getSize(hs)[1];
						if (hsh > productDetailTabs.maxHeight) productDetailTabs.maxHeight = hsh;
						
						if (YUD.hasClass(hs,"first")) YUD.addClass(hs,"current");
						if (!YUD.hasClass(hs,"current")) YUD.addClass(hs,"hidden");
						
						YUD.addClass(li[i],"tab_"+h);
						YUD.addClass(hs,"section_"+h);
						
						var arr = Array(li[i],hs);
						a[0].setAttribute("href","javascript:void(0);");
						YUE.addListener(li[i],"click",productDetailTabs.focus,arr);
						YUE.addListener(a[0],"click",productDetailTabs.focus,arr);
						YUE.addListener(li[i],"mouseover",productDetailTabs.hover,li[i]);
						YUE.addListener(li[i],"mouseout",productDetailTabs.hover,li[i]);
					}
				}
				sizeImg.setSize(pds,null,productDetailTabs.maxHeight);
				setTimeout("balanceColumns.productDetails('" +productDetailTabs.pd.getAttribute("id")+ "');",3000);
			}
		}
	},
	internal: function() {
		// find out if the URL already has a reference in it
		var p =  unescape(location.href);
		if (p.indexOf("#") > 0) {
			var i = p.substring(p.indexOf("#")+1);
			productDetailTabs.incoming = i;
			productDetailTabs.change(null,i);
		}
		
		// then also look for any other internal references on this page
		var a = productDetailTabs.pd.getElementsByTagName("a");
		for (var i=0; i<a.length; i++) {
			var h = a[i].getAttribute("href");
			if (h) {
				if (h.substring(0,1) == "#") {
					var y = YUD.getElementsByClassName("tab_"+h.substring(1),"*",productDetailTabs.pd);
					if (y.length > 0) {
						// a[i].setAttribute("href","#producttabs");
						a[i].setAttribute("href","javascript:void(0);");
						YUE.addListener(a[i],"click",productDetailTabs.change,h.substring(1));
					}
				}
			}
		}
	},
	
	hover: function(e,o) {
		if (e.type == "mouseout")
			YUD.removeClass(o,"hover");
		else	YUD.addClass(o,"hover");
	},
	
	change: function(event,value) {
		var t = YUD.getElementsByClassName("tab_"+value, "*", productDetailTabs.pd);
		var s = YUD.getElementsByClassName("section_"+value, "*", productDetailTabs.pd);
		if (t.length > 0 && s.length > 0) {
			var arr = Array(t[0],s[0]);
			productDetailTabs.focus(null,arr);
		}
	},
	
	focus: function(e,a) {
		// hide the current sections/tabs
		var s = YUD.getElementsByClassName("current","div",productDetailTabs.pd);
		for (var i=0; i<s.length; i++) YUD.removeClass(s[i],"current");
		for (i=0; i<productDetailTabs.sections.length; i++) YUD.addClass(productDetailTabs.sections[i],"hidden");
		
		var t = YUD.getElementsByClassName("current","li",productDetailTabs.tabs);
		for (i=0; i<t.length; i++) YUD.removeClass(t[i],"current");
		
		YUD.setStyle(a[1],"opacity","0");
		YUD.addClass(a,"current");
		YUD.removeClass(a,"hidden");
		sizeImg.fade(a[1],"in",1,1);
	}
	
}

var initialize = {
	init: function() {
		YUE.addListener(window,'load',initialize.onLoad);
		YUE.onDOMReady(initialize.onDOM);
	},
	
	onDOM: function() {
		advertising.init("pre");
		
		redirects.init();
		tabs.init();
		round.init();
		click.init();
		
		pageInfo.init();
		allCats.init();
		devSelect.init();
		
		cleanPage.init();
		activationCodes.init();
		folds.init();
		tooltips.init();
		popup.init();
		transitionCount.init();
		
		qa.init();
		collapse.init();
		highlights.init();
		notices.init();
	},
	
	onLoad: function() {
		messaging.init();
		sizeImg.init();
		cartItems.init();
		
		setTimeout("actionImages.init();",2000);
		setTimeout("getReviews.init();",3000);
		
		productDetailTabs.init();
		
		balanceColumns.init();
		background.init();
		advertising.init("post");
	}
}

// fire off the page
initialize.init();

// standalone functions go below here
function alwaysTrue() { return true; }
function alwaysFalse() { return false; }

function getQueryVariable(variable) {
	var r = "";
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			r = pair[1];
		}
	}
	return r;
}

function number_format(a, b, c, d) {
	// number_format(number, decimals, comma, formatSeparator)
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

String.prototype.trim = function () { return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"); }

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function prepField(e) {
	if (typeof(e) == "string") e = e.trim();
	// e = escape(e);
	// e = encodeURI(e);
	return e;
}

function getBase(u) {
	var nu = "";
	for (var i = 0; i < 3; i++) {
		nu += u.substr(0,u.indexOf("/")+1);
		u = u.substr(u.indexOf("/")+1);
	}
	return nu;
}

function getFieldValue(o,field,entry){
 try{
   value = o.getElementsByTagName(field)[entry].firstChild.nodeValue;
   return value;
 }catch(e){
   return "";
 }
}

function getFieldValueAsFloat(o,field,entry){
  value = getFieldValue(o,field,entry);
  if(value != null && value != "" ){
   return parseFloat(value);
  }
  return value;
}


/* Cookie functions from http://techpatterns.com/downloads/javascript_cookies.php */
function Set_Cookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires ) expires = expires * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
function Get_Cookie( check_name ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ) cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) return null;
}
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) 
		document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}



// functions migrated from functions_swc.jsp

function getParameter ( queryString, parameterName ) {
	// Add "=" to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + "=";
	if ( queryString.length > 0 ) {
	// Find the beginning of the string
		begin = queryString.indexOf ( parameterName );
		// If the parameter name is not found, skip it, otherwise return the value
		if ( begin != -1 ) {
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf ( "&" , begin );
			if ( end == -1 ) {
				end = queryString.length
			}
			// Return the string
			return unescape ( queryString.substring ( begin, end ) );
		}
		// Return "null" if no parameter has been found
		return "null";
	}
}	

	// FUNCTION FOR EXPANDING or COLLAPSING ANY SINGLE WIDGET

function toggleWidget(WidgetID,Action) {
 
  if(Action=='open')
  {
  document.getElementById(WidgetID).style.display='block';
  document.getElementById(WidgetID+'-hide').style.display='block';
  document.getElementById(WidgetID+'-show').style.display='none';
  }
  else
  {
  document.getElementById(WidgetID).style.display='none';
  document.getElementById(WidgetID+'-show').style.display='block';
  document.getElementById(WidgetID+'-hide').style.display='none';
  }
}

// END


// FUNCTIONS FOR EXPANDING/COLLAPSING TITLE LISTS ON HOME/CATEGORY/MY SWC PAGES

function initializeTabs () {
	openLists = "null"
	if(top.location.search)
  	{
		// Open each list that is specified in the query string
  		QueryString=top.location.search.toString();
  		openLists = getParameter(QueryString, 'openLists');
  	}
  	
  	if (openLists != "null")
  	{
		divider=","
  		openListNames=openLists.split(divider);
		for (i = 0; i < openListNames.length; i++)
		{
	      	toggleTitleList(openListNames[i],'');
		}
	}
  	else
  	{
  		collapseAllTabs();
		toggleTitleList('bestsellers','');
  		toggleTitleList('premiertitles','');
  	}
}

counter=0		
tabcounter=0

		
function toggleTitleList(ListName,Option){

  
listID=ListName+'list';

 if (document.getElementById(listID) != null) {
		if(Option=='open') 
		  {
		   if(counter==0) 
		   {
		   document.getElementById(listID).style.display='block';
		   counter=1;
		   }
		   else 
		   {
		   }
		}
		
		  if(Option=='otherlink')
		  {
		    if(document.getElementById(listID).style.display=='block')
		    {
      }
      else
      {
      document.getElementById(listID).style.display='block';
      document.getElementById(ListName+'-show').style.display='none';
      document.getElementById(ListName+'-hide').style.display='block';
      }
		  }
		  else
		  {
		    if(document.getElementById(listID).style.display=='block')
		    {
	  	  document.getElementById(listID).style.display='none';
      document.getElementById(ListName+'-hide').style.display='none';
      document.getElementById(ListName+'-show').style.display='block';
      }
      else 
      {
      document.getElementById(listID).style.display='block';
      document.getElementById(ListName+'-show').style.display='none';
      document.getElementById(ListName+'-hide').style.display='block';
      }
    }

tabcounter=0;

  for (x = 0; x < ListNames.length; x++)
  {
  	var list = document.getElementById(ListNames[x]+'list');	
	if(list != null && list.style.display=='none')
	{
    	tabcounter++;
    }
    else 
    {
      if(list != null && list.style.display=='')
      {
      	tabcounter++;
      }
      else 
      {
      }
    }
  }
 
  if(tabcounter==ListNames.length)
  {
    for (x = 0; x < ListNames.length; x++) 
    {
    	var all_show = document.getElementById(ListNames[x]+'-all-show');
    	var all_hide = document.getElementById(ListNames[x]+'-all-hide');
    	if (all_show != null)
    	{
    		all_show.style.display='block';
    	}
    	if (all_hide != null)
    	{
    		all_hide.style.display='none';
    	}
    }
  }
  else 
  {
  }

tabcounter=0;
 
  for (x = 0; x < ListNames.length; x++)
  {
    var list = document.getElementById(ListNames[x]+'list');
    if(list != null && list.style.display=='block') 
    {
    	tabcounter++;
    }
    else 
    {
    }
  }

  if(tabcounter==ListNames.length)
  {
    for (x = 0; x < ListNames.length; x++) 
    {
    	var all_show = document.getElementById(ListNames[x]+'-all-show');
    	var all_hide = document.getElementById(ListNames[x]+'-all-hide');
    	if (all_show != null)
    	{
    		all_show.style.display='none';
    	}
    	if (all_hide != null)
    	{
    		all_hide.style.display='block';
    	}
    }
  }
  else 
  {
  }
 }
}
 
		
function expandAllTabs() {
  for (x = 0; x < ListNames.length; x++)
  {
  		var list = document.getElementById(ListNames[x]+'list');
		if (list != null)
		{
			list.style.display='block';
  			document.getElementById(ListNames[x]+'-show').style.display='none';
  			document.getElementById(ListNames[x]+'-hide').style.display='block';
  			document.getElementById(ListNames[x]+'-all-show').style.display='none';
  			document.getElementById(ListNames[x]+'-all-hide').style.display='block';
  		}
  }
}
		
function collapseAllTabs() {
  counter=1;   		
  for (x = 0; x < ListNames.length; x++)
  {
  		var list = document.getElementById(ListNames[x]+'list');
  		if (list != null)
  		{
			list.style.display='none';
  			document.getElementById(ListNames[x]+'-hide').style.display='none';
  			document.getElementById(ListNames[x]+'-show').style.display='block';
  			document.getElementById(ListNames[x]+'-all-show').style.display='block';
  			document.getElementById(ListNames[x]+'-all-hide').style.display='none';
  		}
  }
}

function collapseAllHelps() {

  for (x = 0; x < HelpNames.length; x++)
  {
  document.getElementById(HelpNames[x]+'help').style.display='none';
  document.getElementById(HelpNames[x]+'help-hide').style.display='none';
  document.getElementById(HelpNames[x]+'help-show').style.display='block';
  }
}
		
// END

//preferred for "image" rollovers
/*
	Standards Compliant Rollover Script
	Author : Daniel Nolan
	http://www.bleedingego.co.uk/webdev.php
*/

function initRollovers() {
	if (!document.getElementById) return
	
	var aPreLoad = new Array();
	var sTempSrc;
	var aImages = document.getElementsByTagName('img');

	for (var i = 0; i < aImages.length; i++) {		
		if (aImages[i].className == 'imgover') {
			var src = aImages[i].getAttribute('src');
			var ftype = src.substring(src.lastIndexOf('.'), src.length);
			var hsrc = src.replace(ftype, '_over'+ftype);

			aImages[i].setAttribute('hsrc', hsrc);
			
			aPreLoad[i] = new Image();
			aPreLoad[i].src = hsrc;
			
			aImages[i].onmouseover = function() {
				sTempSrc = this.getAttribute('src');
				this.setAttribute('src', this.getAttribute('hsrc'));
			}	
			
			aImages[i].onmouseout = function() {
				if (!sTempSrc) sTempSrc = this.getAttribute('src').replace('_over'+ftype, ftype);
				this.setAttribute('src', sTempSrc);
			}
		}
	}
}

window.onload = initRollovers;
 
// END


// FUNCTION FOR OPENING URL IN A PARENT WINDOW FROM A CHILD POPUP WINDOW

function OpenInParentWindow(ExtURL,CloseChild){
if(top.opener==null){
window.open(ExtURL,"")
}
else{
top.opener.focus()
top.opener.location=ExtURL
}

	 				if(CloseChild=='close'){
parent.top.close()
}
}

// END



// FUNCTION FOR OPENING POPUP WINDOW
// always include a value for "winname" - this ensures that only content designed for that popup loads in the window

function NewNamedWindow(pageurl,winname,wide,tall,scroll) { 
	window.open(pageurl,winname,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + scroll + ",resizable=0,width=" + wide + ",height=" + tall + ",left=25,top=25");
}	

// END

// FUNCTION TO OPEN A NEW FULL BROWSER
                                                                                                                        
function NewBrowser(pageurl) {
        window.open(pageurl);
}
                                                                                                                        
// END


// FUNCTIONS FOR NAVIGATING TO URL IN PARENT WINDOW FROM FORM SELECTION IN POPUP
FormSelectValue=''

function SelectVariable (whichItem) {
var whichDest = whichItem[whichItem.selectedIndex].value;
    
  if (whichDest == "") 
  {
  whichItem.selectedIndex = 0;
  } 
  else 
  {
  FormSelectValue = whichDest; 
  }
}

function ForwardToSelectedURL (errormsg) {
  if(FormSelectValue=='')
  {
  window.alert(errormsg)
  }
  else
  {
  OpenInParentWindow(FormSelectValue,'close')
  }
}
// END
//FUNCTIONS FOR SWITCHING STATE FIELD TO TEXTBOX OR COMBOBOX
var usaStates = new Array("AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY");
var canadaProvinces = new Array("ON","QC","NS","NB","MB","BC","PE","SK","AB","NL","NT","YT","NU");
var controlType = false;//false textbox, true combobox
function createElementDOM(id, value,controlName){
	if(value instanceof Array){
    	listValues = value;
    	defaultValue = listValues[0];

    	var newSelect = document.createElement('select');
        newSelect.setAttribute("id",id);
        newSelect.setAttribute("name",controlName);
      	newSelect.setAttribute("onKeyPress","return submitenter(this,event)");
      	newSelect.onChange = function(){ setStateToHandler(); };
      	for(i = 0; i < listValues.length; i++){
        	var newOpt = document.createElement('option');
        	newOpt.text  = listValues[i];
        	newOpt.value = listValues[i];
			try {
    	 		newSelect.add(newOpt, null); // standards compliant; doesn't work in IE
		  	}catch(ex) {
    			 newSelect.add(newOpt); // IE only
		  	}
     	}
     	return newSelect;
    }
    var newInput = document.createElement('input');
  	newInput.setAttribute("maxlength","50");
  	newInput.setAttribute("class", "text");
  	newInput.setAttribute("type",'text');
  	newInput.setAttribute("id",id);
  	newInput.setAttribute("name",controlName);
  	newInput.setAttribute("onKeyPress","return submitenter(this,event)");
	return newInput;
}

function createHiddenControl(controlName){
	var newInput = document.createElement('input');
	newInput.setAttribute("type","hidden");
	newInput.setAttribute("name","_D:"+controlName);//
	return newInput;
}

function createStateOption(page){

	var id = "state";
	if(page){
		name = "/motricity/userprofiling/OmniRegistrationFormHandler.value.billingAddress.state";
	}else{		
        name = "/atg/commerce/order/purchase/CreateCreditCardFormHandler.creditCard.billingAddress.state";
    }
 	var stateControl = document.getElementById(id);
 	var actualState = stateControl.value;

	var countryCombo = document.getElementById("country");
	var index = countryCombo.options.selectedIndex;
	var country = countryCombo.options[index].value;
	var options = new Array("us","ca","");

	var control = false; // false means textBox, true means comboBox.
	if(country != options[2]){
		if(country == options[0]){ //selected country is USA
			element = createElementDOM(id, usaStates, name);
			control = true;
		}else{
			if(country == options[1]){ // selected country is Canada
				element = createElementDOM(id, canadaProvinces, name);
				control = true;
			}else{
				element = createElementDOM(id, null, name);
			}
		}
	}else{
		element = createElementDOM(id, null, name);
	}
	var div = document.getElementById("stateDiv");
	div.innerHTML = '';
	div.appendChild(element);
	div.appendChild(createHiddenControl(name));

	stateControl = document.getElementById(id);
	if(control){//combobox
		var index = 0;
		var optionsLength = stateControl.options.length;
		var match = false;
		while((index<optionsLength)&&!match){
			if(stateControl.options[index].text == actualState){
				stateControl.options.selectedIndex = index;
				match = true;
			}else{
				index++;
			}
		}
	}else{//textbox
		if(controlType){
			stateControl.value = "";
		}else{
			stateControl.value = actualState;
		}
	}
	controlType = control;
}
//END

// FUNCTIONS FOR SUBMITTING FORMS USING ENTER
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
//alert(navigator.appName);
if (keycode == 13 && navigator.appName == "Microsoft Internet Explorer")
   {
   myfield.form.submit();
   return false;
   }
else
   return true;
}

// FUNCTION TO SET THE CURSOR FOCUS ON A GIVEN ELEMENT
function setFocus(elementId) 
{ 
	var e = document.getElementById(elementId);
	if (e) if (e.getAttribute("type") != "hidden") e.focus();
}

function highlightCVVBox(obj, e)
{  
   elem = document.getElementById('cvvBox');
   if( obj.value.length >= 3 ){
     elem.className = 'existingCC box boxOutlineGray';
   }else{
     elem.className = 'existingCC box boxOutlineBlue msgHighlight';
   }
 }

