var customer = new Object({ isWholesale: false, isRetail: true, queried: false });

function pagePrev() {
	if(! docReady) {
		return;
	}
	
	history.back();
}

function pageNext() {
	if(! docReady) {
		return;
	}
	
	history.back();
}

function pageInitCustomer() {
	var i;
	
	if(customer.isWholesale) {
		for(i = 0; i < displays.length; i++) {
			displays[i].setActiveItem(displays[i].currentItem().index);
		}
	}
}

var lastAddTime = 0;

var displayindexsave;

function renderReview(data) {
	var response = eval(data);

	var html = new Array();
	var displayindex = displayindexsave;
	var display = displays[displayindex];
	var item = display.displayedItem();
	var itemid = item.itemid;
	var profile = siteprofile[siteid];

	var imgsrc = item.Photo(0, 'thumb');
	
	if(response.count == 0) {
		html.push('<p class="body">There are no reviews for this item. <a href="javascript:Review(' + displayindex + ');">Click here</a> if you would like to write the first review.</p>');
		item.review = html.join('');
		$("#revhtml" + displayindex).html(html.join(''));
		return;
	}
	
	var r;
//	html.push('<div style="height: 60px; padding-top: 5px; padding-left: 65px;">');
//	<p class="review">A' + response.avgrating.toFixed(2) + '<br />');
//	html.push('<p class="review"><a href="javascript:Review(' + displayindex + ');">Click here</a> to write your own review</p></div>');
	html.push('<div class="reviewlist" id="rvd' + displayindex + '">');
	var i;
	for(i = 0; i < response.count; i++) {
		var review = response.review[i];
		for(r = 0; r < 5; r++) {
			html.push('<div class="heartrating' + (r < review.rating ? 1 : 0) + '" />');
		}
		
		if(InternetExploderSix || InternetExploderSeven) {
			html.push('<br style="line-height: 14pt" />');
		}
		else {
			html.push('<br />');
		}
		
		html.push('<p class="review"><b>by ' + review.nickname + ' on ' + review.datestring + '</b>');

		if(review.isowned) {
			html.push('<br /><span style="font-size: 9pt;"><i>this customer purchased this product from us</i></span>');
		}
		
		html.push('</p>');
		html.push('<p class="review" style="margin-bottom: 15px;">' + unescape(review.reviewtext) + '</p>');
	}

	html.push('</div>');

	item.review = html.join('');
	$("#revhtml" + displayindex).html(html.join(''));
}

function WriteReview(displayindex) {
	var display = displays[displayindex];
	document.location.href = protocol + shophost + aburi + '/writereview?itemid=' + display.currentItem().itemid;
}

function UploadPhoto(displayindex) {
	var display = displays[displayindex];
	document.location.href = protocol + shophost + aburi + '/choosephoto?itemid=' + display.currentItem().itemid;
}

var aqrcount = 0;
var _recommend;

function renderAddMessage(html, item, closefunc, extramsg) {
	//========================
	html.push('<table class="lb" id="reccomend' + aqrcount + '" cellpadding="0" cellspacing="0">');
	html.push('<tr>');
	html.push('<td class="lbtl"></td>');
	html.push('<td class="lbtop" style="width: 627px;">');
	//========================
	html.push('<table class="bare" cellspacing="0" cellpadding="0"><tr><td style="width: 600px;">Shopping Bag</td><td style="text-align: right; width: 27px;"><a class="titlelink"  href="javascript:' + closefunc + '()">X</a></td></tr></table></td>');
	//========================
	html.push('<td class="lbtr"></td>');
	html.push('</tr>');
	html.push('<tr>');
	html.push('<td class="lbl"></td>');
	html.push('<td class="lbmid" style="width: 627px;">');

	var imguri = item.Photo(0, 'normal');
	//========================
	html.push('<table cellpadding="0" cellspacing="0" style="margin-top: 15px;"><tr>');
	html.push('<td class="addcheckbox">&nbsp</td>'); 
	html.push('<td style="width: 490px; vertical-align: top;"');
	html.push('<p class="bigmsg" style="margin-bottom: 5px;">This item was added to your shopping bag</p><span style="width: 500px; font-size: 9pt;">');
	
	if(customer.isWholesale || item.hasCustomLetters()) {
		html.push(item.FormattedDesc(false));
	}
	else {
		html.push(item.FormattedPrice() + "&nbsp;" + item.FormattedDesc(false));
	}
	
	html.push('</span>');
	
	html.push(extramsg);
	html.push('</td>');
	html.push('<td rowspan="2" style="vertical-align: top;"><img class="photo" style="margin-top: 3px; width: 107px; height: 107px; margin-right: 15px; margin-bottom: 15px;" src="' + imguri + '" /><td>');
	html.push('</tr>');
	html.push('<tr><td colspan="3">');

	//========================
	html.push('<table><tr>');
	html.push('<td class="morethanone">Want more than one? <a class="mto" href="javascript:showbag();">click here</a></td>');
	html.push('<td style="vertical-align: top; width: 284px; padding: 8px; background: url(/images/gplogo7.png) -20px -580px; height: 80px;">');
	html.push('<p class="addsubtotal">Order subtotal ');
	html.push(addresponse.formattedsubtotal);
	html.push('</p>');
	
	if(addresponse.shipreduced == 1 && addresponse.subtotal > 0) {
		var needed = addresponse.shipminimum - addresponse.subtotal;
		if(needed > 0) {
			html.push('<p class="saverrate">Add $' + needed.toFixed(2) + ' to your order to receive special Bonus Rate Shipping!</p>');
		}
		else {
			html.push('<p class="saverrate2">Your order qualifies for special Bonus Rate Shipping!</p>');
		}
		html.push('<p class="savedetails">(Free shipping in U.S. or $5 off International shipping)</p>');
	}
	
	html.push('</td></tr><tr><td style="height: 5px;"></td></tr></table>');
	//========================
	html.push('</td></tr></table>');
	//========================

	html.push('</td>');
	html.push('<td class="lbr"></td>');
	html.push('</tr>');

	html.push('<tr>');
	html.push('<td class="lbl"></td>');
	html.push('<td class="lbmid" style="width: 627px;">');

	//========================
	html.push('<table cellpadding="0" cellspacing="0"><tr>');
	html.push('<td style="width: 480px;">');
	html.push('</td><td><div class="button" style="float: right; display: inline; width: 478px;">');
	var profile = siteprofile[siteid];
	html.push('<a class="button" href="javascript:' + closefunc + '()"><span>Continue Shopping</span></a><a class="button" href="https://' + shophost + aburi + '/checkout"><span>Checkout</span></a>');
	
	html.push('</div></td></tr></table>');
	//========================
	html.push('</td>');
	html.push('<td class="lbr"></td>');
	html.push('</tr>');
	html.push('<tr>');
	html.push('<td class="lbbl"></td>');
	html.push('<td class="lbbot"></td>');
	html.push('<td class="lbbr"></td>');
	html.push('</tr>');
	html.push('</table>');
}

function showbag()
{
	modalClose();
	go('bag');
}

function quickAddedMessage(itemindex, itemid) {
	var modal = modalDiv();
	var html = new Array();
	var display = displays[itemindex];
	var item = display.addedItem();

	renderAddMessage(html, item, "modalClose");

	var h = html.join('');
	modalReplaceContent(h);
	modalCenter();
	BagDisplaySummary(bag);
}

var zoomedimg;

var Z = null;

function zchangePhotoDisplay(zoomer) {
	var display = zoomer.display;
	var item = display.displayedItem();
	var src = item.Photo(zoomer.cbimgno, 'normal');
	loadImg("#displayphoto" + display.displayid, src, "/images/photoloading500.gif");
	item.setPhoto(zoomer.cbimgno);
}

function zoom(displayid) {
	if(pageNotLoaded("zoom(" + displayid + ")")) {
		return;
	}

	var display = displays[displayid];
	var item = display.displayedItem();

	var desc = item.itemid + ' - ' + item.desc;
	_gaq.push(['_trackEvent', 'Shopping', 'ZoomProduct', escape(desc)]);

	if(Z == null) {
		Z = new Zoomer();
	}

	Z.setGalleryCallback(zchangePhotoDisplay);
	Z.cbtv = null;
	Z.display = display;
	
	var html = zoomButton(item.custom ? "AddCustomZoom" : "AddZoom", item, display, false);
	Z.zoomgallery({ tv: item.photoViewer(),
					sourceimg: "#displayphoto" + display.displayid,
					imgno: item.currentPhoto('index'),
					normalpics: arrayOf('normal', item.photos),
	 				zoompics: arrayOf('zoom', item.photos),
				  	width: 500,
					height: 500,
					caption: arrayOf('note', item.photos),
					by: arrayOf('desc', item.photos),
					css: "ivztvbar",
					html: html,
					htmlheight: 120,
					slots: 6 });
}

function zoomCustomer(display, imgno) {
	if(Z == null) {
		Z = new Zoomer();
	}

	Z.setGalleryCallback(null);
	Z.cbtv = null;

	var item = display.currentItem();
	var desc = item.itemid + ' - ' + item.desc;
	_gaq.push(['_trackEvent', 'Shopping', 'ViewCustomerPhotos', escape(desc)]);
	
	var html = zoomButton("AddZoom", item, display, false);
	Z.zoomgallery({ tv: item.cpvtv,
					sourceimg: item.cpvtv.getImage(imgno),
					imgno: imgno,
					normalpics: arrayOf('normal', item.custphotos),
					zoompics: arrayOf('zoom', item.custphotos),
					caption: arrayOf('note', item.custphotos),
					by: arrayOf('desc', item.custphotos),
			  		width: 500,
					height: 500,
					css: "ivztvbar",
					html: html,
					slots: 6,
					htmlheight: 120,
					display: display,
					initialloadimg: "/images/photoloading500.gif",
					displayCallback: function(tv, imgno) {
						displayZoomedImage(tv, imgno);
					} });
}

function AddZoom(displayid) {
	ge("zoomercl").Zoomer.closeZoomWithoutAnimation();
	BagAdd(displayid);
}

function AddCustomZoom(displayid) {
	ge("zoomercl").Zoomer.closeZoomWithoutAnimation();
	BagAddCustom(displayid);
}

function zoomSimilar(display, imgno) {
	if(Z == null) {
		Z = new Zoomer();
	}

	Z.setGalleryCallback(null);
	Z.cbtv = null;

	var theitem = display.currentItem();
	item = theitem.coordinatingitems[imgno];
	var desc = item.itemid + ' - ' + item.desc;
	_gaq.push(['_trackEvent', 'Shopping', 'ViewRelatedItem', escape(desc)]);
	
	var html = zoomButton("AddCrossSell", item, display, true);
	Z.zoomgallery({ tv: theitem.sivtv,
					sourceimg: theitem.sivtv.getImage(imgno),
					imgno: imgno,
					normalpics: arrayOfPhotos('normal', theitem.coordinatingitems),
					zoompics: arrayOfPhotos('zoom', theitem.coordinatingitems),
			  		width: 500,
					height: 500,
					caption: null, by: null,
					css: "ivztvbar",
					html: html,
					slots: 6,
					htmlheight: 120,
					display: display,
					itemarray: theitem.coordinatingitems,
					initialloadimg: "/images/photoloading500.gif",
					displayCallback: function(tv, imgno) {
						displayZoomedImage(tv, imgno);
						var item = tv.Zoomer.itemarray[imgno];
						tv.Zoomer.display.setCrossSellItem(item);
						$("#zoomprice").html(item.FormattedPrice());
						$("#zoomdesc").html(item.FormattedDesc(false));
						$("#zoomlink").attr("href", linkto(item));
					} });

	display.setCrossSellItem(item);
	detailHover();
}

function displayZoomedImage(tv, imgno) {
	var zoomer = tv.Zoomer;

	zoomer.cbtv = tv;
	zoomer.cbimgno = imgno;
	zoomer.imgno = imgno;
	zoomer.renderCaption();
	
	loadImg("#zoomer", zoomer.zmURI[imgno], "/images/photoloading500.gif");
}

function zoomRecommended(display, imgno) {
	if(Z == null) {
		Z = new Zoomer();
	}

	Z.setGalleryCallback(null);
	Z.cbtv = null;

	var theitem = display.currentItem();
	var item = theitem.recommended[imgno];
	var desc = item.itemid + ' - ' + item.desc;
	_gaq.push(['_trackEvent', 'Shopping', 'ViewRecommendation', escape(desc)]);

	var html = zoomButton("AddRecommended", item, display, true);
	Z.zoomgallery({ tv: theitem.rivtv,
					sourceimg: theitem.rivtv.getImage(imgno),
					imgno: imgno,
					normalpics: arrayOfPhotos('normal', theitem.recommended),
					zoompics: arrayOfPhotos('zoom', theitem.recommended),
			  		width: 500,
					height: 500,
					caption: null, by: null,
					css: "ivztvbar",
					html: html,
					slots: 6,
					htmlheight: 120,
					display: display,
					itemarray: theitem.recommended,
					initialloadimg: "/images/photoloading500.gif",
					displayCallback: function(tv, imgno) {
						displayZoomedImage(tv, imgno);
						var item = tv.Zoomer.itemarray[imgno];
						tv.Zoomer.display.setRecommendedItem(item);
						$("#zoomprice").html(item.FormattedPrice());
						$("#zoomdesc").html(item.FormattedDesc(false));
						$("#zoomlink").attr("href", linkto(item));
					} });

	display.setRecommendedItem(item);
	detailHover();
}

function detailHover() {
	$("#zoomlink")
		.mouseenter(function() { $(this).css( { 'text-decoration' : 'underline' } ); })
		.mouseleave(function() { $(this).css( { 'text-decoration' : 'none' } ); });
}

function zoomButton(addfunc, item, display, needlink) {
	var html = new Array();
	html.push('<div class="p2zprice"><p id="zoomprice">' + item.FormattedPrice() + '</p>');
	html.push('<div class="p2zdesc"><span id="zoomdesc">' + item.FormattedDesc(false) + '</span>');
	if(needlink) {
		html.push(' [<a class="p2zlink" id="zoomlink" href="' + linkto(item) + '">details...</a>]');
	}
	html.push('</div>');
	html.push('<div><a class="smaddbutton" href="javascript:' + addfunc + '(' + display.displayid + ')">');
	html.push('Add to Bag</a></div></div>');

	return(html.join(''));
}

function linkto(item) {
	var url = aburi + "/page2/item/";
	if(item.parentitemid !== 0) {
		url += item.parentitemid + '#' + item.itemid;
	}
	else {
		url += item.itemid;
	}
	
	return(url);
}

function flipimages() {
	tvrec.setImageURIs(tvrec.realimages);
}

var addBagTimer;
var addBagRetries;
var bagCallback;

function BagAdd(displayid) {
	if(pageNotLoaded("BagAdd(" + displayid + ")")) {
		return;
	}

	var display = displays[displayid];
	var item = display.displayedItem();
	
	bagCallback = "quickAddedMessage";
	_BagAdd(displayid, item, 1, null);
}

function AddCrossSell(displayid) {
	if(pageNotLoaded("AddCrossSell(" + displayid + ")")) {
		return;
	}

	Z.hideZoomer(true);
	var display = displays[displayid];
	var item = display.crossSellItem();
	
	bagCallback = "quickAddedMessage";
	_BagAdd(displayid, item, 1, null);
}

function AddRecommended(displayid) {
	if(pageNotLoaded("AddRecommended(" + displayid + ")")) {
		return;
	}

	Z.hideZoomer(true);
	var display = displays[displayid];
	var item = display.recommendedItem();
	
	bagCallback = "quickAddedMessage";
	_BagAdd(displayid, item, 1, null);
}

function _BagAdd(displayid, item, quantity, custom) {
	var display = displays[displayid];

	display.setAddedItem(item);
	var hascookies = CookiesTest();
	if(hascookies == false) {
		modalMessage("Cookies Required", '<p class="body" style="margin-top: 15px;">Our website requires the use of &ldquo;Cookies&rdquo; and your browser currently has Cookies turned off.</p><p class="body">Please turn cookies on and try to add the item to your bag again.</p>');
		return;
	}

	if(item.discontinued == 1) {
		modalMessage("Discontinued Item", '<p class="body" style="margin-top: 15px;">We\'re sorry, that item has been discontinued, so you cannot add it to your bag</p>', 325);
		return;
	}
	
	var desc = item.itemid + ' - ' + item.desc;
	_gaq.push(['_trackEvent', 'Commerce', 'BagAdd', escape(desc)]);
	
	if(ajaxbag) {
		ajaxadd(displayid, item.itemid, quantity, custom);
	}
	else {
		addtobag(item.itemid, quantity, custom);
	}
}

function BagAddCustom(displayid) {
	if(pageNotLoaded("BagAddCustom(" + displayid + ")")) {
		return;
	}

	var display = displays[displayid];
	if(display.customValueCount() == 0) {
		modalMessage("Custom Item", '<p class="body" style="margin-top: 15px;">Unable to add item to your shopping bag.</p><p class="body">Please enter the text you want to use to customize this item, then click "Add to Bag" again.</p>', 325);
		return;
	}

	var customstring = display.customValueString();
	var item = display.displayedItem();
	
	bagCallback = "quickAddedMessage";
	_BagAdd(displayid, item, 1, customstring);
}

function BagAddWholesale(itemindex) {
	if(pageNotLoaded("BagAddWholesale(" + itemindex + ")")) {
		return;
	}

	var quantity = $("#qty" + itemindex).val();
	if(quantity < 6) {
		alert("There is minimum quantity of 6 units for wholesale customers.\n\nPlease increase your quantity to 6 or more.");
		return;
	}

	bagCallback = "quickAddedMessage";

	var display = displays[itemindex];
	var item = display.displayedItem();

	_BagAdd(itemindex, item, quantity, null);
}

var addreq;

function ajaxadd(itemindex, item, qty, custom) {
	var display = displays[itemindex];
	display.additemid = display.curitemid;
	var now = new Date();
	addreq = new Object;
	addreq.success = "pg2addBagSuccess";
	addreq.failure = "pg2addBagFailure";
	addreq.itemindex = itemindex;
	addreq.itemid = item;
	addreq.quantity = qty;
	if(custom) {
		addreq.custom = custom;
	}

	var html = '<p class="body" style="margin-top: 15px; text-align: center;">Adding item to bag</p><img src="/images/pinkprogressbar.gif" />';
	modalDialog("Shopping Bag", html, 220, 'addbagnotice', 'NoClOsE');
		
	if(AjaxAddToBag(addreq)) {
		addBagRetries = 0;
		addBagTimer = window.setTimeout("pg2retryAdd()", 10000);
	}
	else {
		modalMessage("Shopping Bag Busy", '<p class="body" style="margin-top: 15px;">Sorry, we cannot add an item to your shopping bag at the moment because your shopping bag is busy.</p><p class="body">Please try again in a few seconds.</p>', 500);
	}

	lastAddTime = now.getTime();
}

function addtobag(item, quantity, custom) {
	if(! docReady) {
		return;
	}
	
	var now = new Date();
	if(now.getTime() - lastAddTime > 2000) {
		var d = new Date();
		document.bagadd.itemid.value = item;
		document.bagadd.quantity.value = quantity;
		document.bagadd.custom.value = custom;
		document.bagadd.tzoff.value = d.getTimezoneOffset();
		document.bagadd.submit();
		lastAddTime = now.getTime();
	}
}

var addresponse;

function pg2addBagSuccess(bagresponse, statusText) {
	if(addBagTimer) {
		window.clearTimeout(addBagTimer);
		addBagTimer = null;
	}
	
	window.setTimeout("bagBusy = false;", 1500);
	bag = bagresponse;
	
	DeleteCookieInDomain("girlprops.com", "itemtracker");
	if(bag.count > 0) {
		SetCookie("itemtracker", $.toJSON(bag.itemtracker));
	}
	else {
		SetCookieInDomain(thishost, "itemtracker", "");
	}

	var e = ge("bag" + bagresponse.itemindex + "_adding");
	if(e) { e.style.display = "none"; }
	
	if(customer.queried == false) {
		var req = new Object;
		AjaxQueryCustomerType(req);
	}
	
	var now = new Date();
	var currentTime = now.getTime();
	addresponse = bagresponse;
	window.setTimeout(bagCallback + "(" + bag['itemindex'] + "," + bag['itemid'] + ")", 500);
}

function pg2addBagFailure(p) {
	if(addBagTimer) {
		window.clearTimeout(addBagTimer);
		addBagTimer = null;
	}
	
	addtobag(addreq.itemid, addreq.quantity, typeof(addreq.custom) == "undefined" ? null : addreq.custom);
	return;
}

function pg2retryAdd() {
	addBagTimer = null;
	if(addBagRetries == 2) {
		pg2addBagFailure();
		return;
	}
	
	addBagRetries += 1;
	addBagTimer = window.setTimeout("pg2retryAdd()", 10000);
	AjaxAddToBag(addreq);
}

function AddWishlist(displayindex) {
	if(! docReady) {
		modalMessage("Page Loading", '<p class="body" style="margin-top: 15px;">Please wait for the page to finish loading, then click Add to Wishlist again</p>', 300);
		return;
	}

	var hascookies = CookiesTest();
	if(hascookies == false) {
		modalMessage("Cookies Required", '<p class="body" style="margin-top: 15px;">Our website requires the use of &ldquo;Cookies&rdquo; and your browser currently has Cookies turned off.</p><p class="body">Please turn cookies on and try to add the item to your Wish List again.</p>');
		return;
	}

	var display = displays[displayindex];

	if(ajaxbag) {
		var req = new Object;
		req.success = "pg2addWishlistSuccess";
		req.failure = "pg2addWishlistFailure";
		req.wishlistid = -1;
		req.itemid = display.curitemid;
		req.quantity = 1;
		AjaxAddToWishlist(req);
	}
}

function pg2addWishlistSuccess(resp, statusText) {
	alert("Item added to wishlist");
}

function pg2addWishlistFailure(resp, statusText) {
}

function displayPropaganda(tv, i) {
	if(Z == null) {
		Z = new Zoomer();
	}
	
	Z.htmlheight = 0;
	Z.zoom(tv.getImage(i), thumb[i], photo[i], pw[i], ph[i]);
}

function pageInitPropaganda() {
	curphoto = 0;

	var profile = siteprofile[siteid];
	var tvrec = new ThumbViewer('ptv');
	tvrec.setImageURIs(thumb);
	tvrec.displayCallback = displayPropaganda;
	tvrec.thumbPad = 8;
	tvrec.thumbWidth = profile.propThumbWidth;
	tvrec.thumbHeight = profile.propThumbHeight;
	tvrec.divheight = profile.propDivHeight;
	tvrec.divwidth = profile.propDivWidth;
	tvrec.shadow = profile.propShadow;
	tvrec.shadowh = profile.propShadowh;
	tvrec.shadoww = profile.propShadoww;
	tvrec.thumbSlots = 3;
	tvrec.arrowPrevOff = '/images/tarrowprevoff.png';
	tvrec.arrowPrevOn =  '/images/tarrowprevon.png';
	tvrec.arrowNextOff = '/images/tarrownextoff.png';
	tvrec.arrowNextOn =  '/images/tarrownexton.png';
	tvrec.css = 'tvprop';
	tvrec.divcss = 'tvdivcss';
	tvrec.acss = 'ziphoto';
	tvrec.thumbcss = 'ziphoto';
	tvrec.widthArrow = profile.propWidthArrow;
	tvrec.arrowCss = 109;
	tvrec.loadingimg = '/images/photoloading180.gif';
	tvrec.generate();
	tvrec.loadViewableImages();

	SetCookie('propagandafrom', '');
}

function dealVerificationCallback(response) {
	if(response.status == 0) {
		if(response.dealstatus !== 0) {
			document.location.href = "http://" + shophost + aburi + '/nodeal/' + response.deal.dealcode + '/' + response.dealstatus;
		}
	}
}

function pg2customerTypeCallback(resp, statusText) {
	if(resp.status == 0) {
		customer.queried = true;
		if(resp.customerType == 2 || resp.customerType == 4) {
			customer.isWholesale = true;
			customer.isRetail = true;
		}
	}
	
	pageInitCustomer();
}	

function arrayOf(property, list) {
	var ret = new Array();
	var i;
	for(i = 0; i < list.length; i++) {
		if(list[i]) {
			var obj = list[i];
			ret[ret.length] = obj[property] ? obj[property] : "";
		}
	}
	
	return(ret);
}

function arrayOfPhotos(property, items) {
	var ret = new Array();
	var i;

	for(i = 0; i < items.length; i++) {
		if(items[i]) {
			var obj = items[i].photos[0];
			if(obj) {
				ret[ret.length] = obj[property] ? obj[property] : "";
			}
		}
	}
	
	return(ret);
}

function arrayOfPriceAndDesc(items) {
	var ret = new Array();
	var i;

	for(i = 0; i < items.length; i++) {
		if(items[i]) {
			var s = items[i].Price() + ' ' + items[i].Desc();
			ret[ret.length] = s;
		}
	}
	
	return(ret);
}

function pg2Init() {
	var profile = siteprofile[siteid];
	var req;

	pageCommonInit();
	pageInitNavbar();
	if(haspropaganda) {
		pageInitPropaganda();
	}

	if(ajaxbag) {
		req = new Object();
		req.success = "pg2customerTypeCallback";
		req.failure = "pg2customerTypeCallback";
		AjaxQueryCustomerType(req);
	}
	
	docReady = true;

	pngifyLabels();
	if(Gecko && Macintosh) {
		$("img.ziphoto").each(function(i) { this.style.cursor = "-moz-zoom-in"; });
		$(".p2photo").each(function(i) { this.style.cursor = "-moz-zoom-in"; });
	}

	$("div.p2controls: a").attr("onmouseover", "this.style.textDecoration='underline';"); 	
	$("div.p2controls: a").attr("onmouseout", "this.style.textDecoration='none';");
	
	if(ajax && dealcode.length > 0) {
		req = new Object;
		req.dealcode = dealcode;
		req.success = "dealVerificationCallback";
		req.failure = null;
		AjaxVerifyDeal(req);
	}

	var i;
	for(i=0; i < displays.length; i++) {
		var display = displays[i];
		display.activetabcss = "tab";
		display.inactivetabcss = "tabinactive";
		display.activebuttcss = "tabbutt";
		display.inactivebuttcss = "tabbuttinactive";
		display.activejointcss = "tabjoint";
		display.inactivejointcss = "tabjointinactive";
		display.activetableadcss = "tablead";
		display.inactivetableadcss = "tableadinactive";
		display.primarytabcss = "primarytab";
		display.secondarytabcss = "secondarytab";
	}
	var n = displays.length < 4 ? displays.length : 4;
	if($.browser.msie == true && $.browser.version == '6.0' && n > 1) {
		n = 1;
	}
	
	for(i=0; i < n; i++) {
		displays[i].initialize();
	}

	if(ajax) {
		req = new Object();
		req.success = "pg2customerTypeCallback";
		req.failure = "pg2customerTypeCallback";
		AjaxQueryCustomerType(req);
	}
	
	$(window).scroll(function() {
		var i;
		var dh = displays[0].height();
		for(i = 0; i < displays.length; i++) {
			var display = displays[i];
			var wbottom = $(window).scrollTop() + $(window).height();
			if(display.isDisplayed) {
				continue;
			}
			
			if(wbottom + (2 * dh) > display.top()) {
				display.initialize();
			}
		}
	});
	
	BagCheckDeal("pg2GenerateDiscountedPrices");
}

function pg2GenerateDiscountedPrices(deal) {
	var i;
	for(i = 0; i < displays.length; i++) {
		displays[i].applyDiscount(deal.dealdiscount / 100);
	}
}

function pngifyLabels() {
	if(InternetExploderSix) {
		$("img.p2discontinued").each(function(i) { el_fnFixPng(this); });
		$("img.p2soldout").each(function(i) { el_fnFixPng(this); });
	}
}

var customkeyup = new Array(
	function () {		// custom type 0 - one necklace with n custom letters
		keyupCommon(this);
	},
	null,				// custom type 1 - e-gift card
	function () {		// custom type 2 - one necklace with n custom names
		keyupCommon(this);
		if(! InternetExploderSeven && ! InternetExploderEight) {
			$(this).css("border", "");
		}
	}
);

function keyupCommon(el) {
	var maxlength = $(el).attr('maxlength');
	var display =  $(el).data("display");
	var id = display.displayid;
	var validchars = display.currentItem().custom.validChars();
	var s = $(el).val();
	var t = "";
	var i;
	for(i = 0; i < s.length; i++) {
		var c = s.substr(i, 1).toUpperCase();
		if(validchars.indexOf(c) != -1) {
			t += c;
		}
	}

	if(s !== t) {
		$(el).val(t.substr(0, maxlength).toUpperCase());
	}
	
	$("#cc" + id).html("" + (maxlength - t.length));
	display.displayItem(display.displayedItem());
}

function DisplayPage2(obj) {
	if(obj) {
		for(var key in obj) {
			this[key] = obj[key];
		}
		
	}

	this.state='pv';
	this.curcoordindex=0;
	this.items=new Array();
	this.disabledItems=new Array();
	this.curItemno = 0;
	this.curTabno = 0;
	this.isDisplayed = false;

	this.initialize = function() {
		this.curItemno = this.parseUrl();
		this.itemDisplayed = this.items[this.curItemno];
		this.tabbar = new TabBar({element: "tab" + this.displayid,
			callbackdata: this,
			callback: function(tabno, display) {
				display.selectTab(tabno);
			},
			tabcss: "tab",
			tabnames: new Array("Details","Customer Reviews")});
		this.tabbar.initialize();

		this.positionThumbViewers();

		var i;
		for(i=0; i < this.items.length; i++) {
//			if(this.items[i].photos.length > 1) {
				this.createItemPhotoViewer(this.items[i]);
//			}
			this.createCustomerPhotoViewer(this.items[i]);
			this.createSimilarItemViewer(this.items[i]);
			this.createRecommendedItemViewer(this.items[i]);
		}

		$("#mag" + this.displayid).css({'display' : "block"});
		if(InternetExploderFive || InternetExploderSix) {
			el_fnFixPng(ge("mag" + this.displayid));
		}

		$("#zl" + this.displayid).attr('href', "javascript:zoom(" + this.displayid + ");");
		
		this.initItemSelector();
		this.setActiveItem(this.curItemno);
		if(typeof(this.itemDisplayed.custom) !== 'undefined') {
			$("#custom" + this.displayid).data("display", this);
			$(".custom" + this.displayid).data("display", this);
			if(typeof(customkeyup[this.itemDisplayed.custom.type]) == 'function') {
				$(".inpcustom").keyup(customkeyup[this.itemDisplayed.custom.type]);
			}
			
			if(this.itemDisplayed.custom.type == 2) {
				for(i = 0; i < this.itemDisplayed.custom.data.maxcount; i++) {
					var el = $("#customopt" + this.displayid + "_" + i);
					this.updateCustomOptions(el);
				}
				
				$(".customoptchoice").change(function() {
					var display = $(this).data("display");
					display.updateCustomOptions(this);
				});
			}
		}
		
		this.isDisplayed = true;
	};

	this.updateCustomOptions = function(el) {
		var display = $(el).data("display");
		var idstr = $(el).attr("id");
		idstr = idstr.substr(9);
		var i = $(el).val();
		var maxlength = display.itemDisplayed.custom.data.options[i].maxcount;
		$("#custom" + idstr).attr("maxlength", maxlength);
		val = $("#custom" + idstr).val();
		if(val.length > maxlength) {
			$("#custom" + idstr).val(val.substr(0, maxlength));
			if(! InternetExploderSeven && ! InternetExploderEight) {
				$("#custom" + idstr).css("border", "3px solid red");
			}
		}
		$("#customdiv" + idstr).attr("style", display.itemDisplayed.custom.data.options[i].css);
	};
	
	this.top = function() {
		return($("#itemdisplay" + this.displayid).offset().top);
	};

	this.height = function() {
		return($("#itemdisplay" + this.displayid).innerHeight());
	};

	this.positionThumbViewers = function() {
		var i;
		this.pvclass = new Object;
		this.pvslots = new Object;
		this.pvtracker = new Object;
		this.pvtypes = new Array('iv','cv','sv','rv');
		this.pvtracker['cv'] = true;
		this.pvslots['iv'] = 4;
		for(i=0; i < this.items.length; i++) {
			var item = this.items[i];
			if(item.photos.length > 0) {
				this.pvtracker['iv'] = true;
			}
			
			if(item.coordinatingitems.length > 0) {
				this.pvtracker['sv'] = true;
			}

			if(item.recommended.length > 0) {
				this.pvtracker['rv'] = true;
			}			
		}

		if($.browser.msie == true && $.browser.version == '6.0' && displays.length > 4) {
			this.pvtracker['sv'] = false;
			this.pvtracker['rv'] = false;
			this.pvtracker['cv'] = false;
		}
		
		var n = 0;
		var ltype;
		for(i=0; i < this.pvtypes.length; i++) {
			var type = this.pvtypes[i];
			if(this.pvtracker[type] == true) {
				if(this.itemDisplayed.custom) {
					if(this.itemDisplayed.custom.type == 2) {
						if(n % 2 == 1) {
							n += 1;
						}
					}
				}
				
				this.pvclass[type] = "p2v" + n;
				this.pvslots[type] = n & 1 ? 6 : 4;
				ltype = type;
				n += 1;
			}
			else {
				this.pvclass[type] = "p2vempty";
			}
		}
		
		if(n == 3) {
			this.pvclass[ltype] = "p2vw";
			this.pvslots[ltype] = 12;
		}
	};
	
	this.parseUrl = function() {
		var array = document.location.href.split('#');
		var i;
		for(i = 0; i < this.items.length; i++) {
			if(this.items[i].itemid == array[1]) {
				return(i);
			}
		}
		
		array = document.location.href.split('/');
		for(i = 0; i < this.items.length; i++) {
			if(this.items[i].itemid == array[array.length - 1]) {
				return(i);
			}
		}
		
		return(0);
	};
	
	this.initItemSelector = function() {
		if(this.items.length < 2) {
			return;
		}
		
		var i;
		this.sorteditems = new Array();
		for(i = 0; i < this.items.length; i++) {
			this.sorteditems[i] = this.items[i];
		}
		
		this.sorteditems.sort(function(a, b) {
			if(a.variation < b.variation) {
				return(-1);
			}
			
			if(a.variation > b.variation) {
				return(1);
			}
			
			return(0);
		});
		
		var html = new Array();
		html.push('<select class="itemsel" id="sel' + this.displayid + '">');
		for(i = 0; i < this.sorteditems.length; i++) {
			this.sorteditems[i].sindex = i;
			html.push('<option value="' + this.sorteditems[i].index + '">' +
						this.sorteditems[i].variation + '</option>');
		}
		
		html.push('</select>');
		$("#itemselector" + this.displayid).css({"display" : "block"});
		$("#select" + this.displayid)
			.html(html.join(''))
			.removeClass()
			.addClass("itemsel")
			.css({"display" : "block"}
		);
		$("#sel" + this.displayid)
			.data("display", this)
			.change(function() {
				var itemid = $(this).val();
				var display = $(this).data("display");
				display.setActiveItem(itemid);
			}
		);
		
		switch(this.theme)
		{
			case 1: $("#slabel" + this.displayid).text("Available Styles"); break;
			case 2: $("#slabel" + this.displayid).text("Available Colors"); break;
			case 3: $("#slabel" + this.displayid).text("Available Sizes"); break;
		}
		
		$("#slabel" + this.displayid).css("left", "34px");
		
		this.createItemSelectorViewer();
	};
	
	this.selectTab = function(tabno) {
		this.curTabno = tabno;
		if(tabno == 0) {
			$("#nar" + this.displayid).css({"display" : "block"});
			$("#rev" + this.displayid).css({"display" : "none"});
		}
		
		if(tabno == 1) {
			$("#rev" + this.displayid).css({"display" : "block"});
			$("#nar" + this.displayid).css({"display" : "none"});
			var html = this.displayedItem().review;
			if(html.length < 1) {
				displayindexsave = this.displayid;
				var item = this.items[this.curItemno];
				var desc = item.itemid + ' - ' + item.desc;
				_gaq.push(['_trackEvent', 'Shopping', 'ReadReviews', escape(desc)]);
				$.get(aburi + "/review/" + 
						this.items[this.curItemno].itemid, renderReview);
			}
			else {
				$("#revhtml" + this.displayid).html(html);
				if(Gecko && Windoze) {
					$('#rvd' + displayindex).attr("class", "reviewlist");
				}
			}
		}
		
		this.tabbar.selectTab(tabno);
	};

	this.addItem = function(item) {
		item.index = this.items.length;
		this.items[this.items.length] = item;
		item.display = this;
	};
	
	this.applyDiscount = function(discount) {
		var i;
		for(i=0; i < this.items.length; i++) {
			this.items[i].applyDiscount(discount);
		}
		
		if(this.isDisplayed) {
			this.displayItem(this.itemDisplayed);
		}
	};
	
	this.refresh = function() {
		var i;
		for(i=0; i < this.items.length; i++) {
			this.items[i].clearSpecs();
		}
		this.setActiveItem(this.curItemno);
	};
	
	this.setActiveItem = function(i) {
		this.curItemno = i;
		var p;
		p = this.displayedItem();
		$("#ipv" + this.displayid + "_" + p.itemid).css({'display' : 'none'});
		$("#cpv" + this.displayid + "_" + p.itemid).css({'display' : 'none'});
		$("#siv" + this.displayid + "_" + p.itemid).css({'display' : 'none'});
		$("#riv" + this.displayid + "_" + p.itemid).css({'display' : 'none'});

		var item = this.items[i];
		this.displayItem(item);

		if(item.pvtv) {
			item.pvtv.loadViewableImages();
		}
		if(item.cpvtv) {
			item.cpvtv.loadViewableImages();
		}
		if(item.sivtv) {
			item.sivtv.loadViewableImages();
		}
		if(item.rivtv) {
			item.rivtv.loadViewableImages();
		}

		$("#upl" + this.displayid).css("display", (item.custphotos.length > 0 ? "block" : "none"));
		$("#itemphotos" + this.displayid).css("display", (item.photos.length > 1 ? 'inline-block' : 'none'));
		$("#ipv" + this.displayid + "_" + item.itemid).css('display', 'inline-block');
		$("#cpv" + this.displayid + "_" + item.itemid).css('display', 'inline-block');
		$("#siv" + this.displayid + "_" + item.itemid).css('display', 'inline-block');
		$("#riv" + this.displayid + "_" + item.itemid).css('display', 'inline-block');
		
		$("#sel" + this.displayid).val(i);
	
		this.itemDisplayed = item;
		this.selectTab(this.curTabno);
	};
	
	this.displayItem = function(item) {
		loadImg("#displayphoto" + this.displayid, item.currentPhoto('normal'), "/images/photoloading2.gif");
		this.itemDisplayed = item;
		
		var price = item.FormattedPrice();
		$("#pp" + this.displayid).html(price);
		if(customer.isWholesale) {
			$("#pp" + this.displayid).removeClass().addClass("p2wholesale");
			if($("#add" + this.displayid).has("span").length == 0) { 
				var html = '<span class="p2wholesaleadd">Qty: <input class="p2wholesaleadd" type="text" id="qty' + this.displayid + '" value="6" /></span><br />';
				$("#add" + this.displayid).prepend(html);
			}
			$("#addbutton" + this.displayid).attr("href", "javascript:BagAddWholesale(" + this.displayid + ")");
		}

		if(item.custom) {
			var c = this.customValueLength() > 0 ? "addbutton" : "disabledaddbutton";
			var s = this.customValueLength() > 0 ? "" : "p2pricecustom";
			$("#addbutton" + this.displayid).removeClass().addClass(c);
			if(this.customValueLength() > 0) {
				$("#addbutton" + this.displayid).attr("href", "javascript:BagAddCustom(" + this.displayid + ")");
			}
			else {
				$("#addbutton" + this.displayid).removeAttr("href");
			}
			$("#pp" + this.displayid).removeClass().addClass(s);
			var item2 = this.items[this.curItemno];
			$("#validcustom" + this.displayid).html(item2.custom.validCharsPrettyDisplay());
			
			if(item.custom.type == 2) {
				var n = this.customValueCount();
				if(typeof(this.itemDisplayed.pvtv) != "undefined") {
					this.itemDisplayed.pvtv.displayitem(n);
				}
			}
		}
		
		$("#reg" + this.displayid).html(item.FormattedDesc(true));
		$("#specs" + this.displayid).html(item.Specs());
		if(this.isvtv) {
			this.isvtv.animatedslideto(item.sindex);
			this.isvtv.highlight(item.sindex);
		}
		
		this.updateSocialLinks();
	};
	
	this.updateSocialLinks = function() {
		this.updateFacebook();
		this.updatePinterest();
		this.updateTwitter();
	};
	
	this.updateFacebook = function() {
		var el = $("#facebook" + this.displayid + " iframe");
		var url = el.attr("src");
		if(typeof(url) === 'undefined') {
			return;
		}
		var n = url.indexOf('?');
		var p = url.substr(n + 1);
		var src = url.substr(0, n) + "?";
		var params = parseParameters(p);
		var item = this.currentItem();
		var first = true;
		for(var k in params) {
			if(k === 'origin') {
				alert(params[k]);
				params[k] = protocol + thishost + aburi + '/page2/item/' + item.itemid;
			}
			
			if(k === 'media') {
				params[k] = item.currentPhoto('normal');
			}
			
			if(! first) {
				src = src + '&';
			}
			first = false;
			src = src + k + '=' + escape(params[k]);
		}
		$("#facebook" + this.displayid + " > div > span > iframe").attr("src", src);
	};
	
	this.updatePinterest = function() {
		var url = $("#pinterest" + this.displayid + " > iframe").attr("src");
		if(typeof(url) === 'undefined') {
			return;
		}
		var n = url.indexOf('?');
		var p = url.substr(n + 1);
		var src = url.substr(0, n) + "?";
		var params = parseParameters(p);
		var item = this.currentItem();
		var first = true;
		for(var k in params) {
			if(k === 'url') {
				params[k] = protocol + thishost + thisuri + "#" + item.itemid;
			}
			
			if(k === 'media') {
				params[k] = item.currentPhoto('normal');
			}
			
			if(! first) {
				src = src + '&';
			}
			first = false;
			src = src + k + '=' + escape(params[k]);
		}
		$("#pinterest" + this.displayid + " > iframe").attr("src", src);
	};
	
	this.updateTwitter = function() {
		var url = $("#twitter" + this.displayid + " > a").attr("href");
		if(typeof(url) === 'undefined') {
			return;
		}
		var n = url.indexOf('?');
		var p = url.substr(n + 1);
		var href = url.substr(0, n) + "?";
		var params = parseParameters(p);
		var item = this.currentItem();
		var first = true;
		for(var k in params) {
			if(k === 'url' || k === 'original_referer') {
				params[k] = protocol + thishost + thisuri + "#" + item.itemid;
			}
			
			if(! first) {
				href = href + '&';
			}
			first = false;
			href = href + k + '=' + escape(params[k]);
		}
		$("#twitter" + this.displayid + " > a").attr("href", href);
	};
	
	this.currentItem = function() {
		return(this.items[this.curItemno]);
	};

	this.displayedItem = function() {
		return(this.itemDisplayed);
	};

	this.setAddedItem = function(item) {
		this.theAddedItem = item;
	};
	
	this.addedItem = function() {
		return(this.theAddedItem);
	};

	this.setCrossSellItem = function(item) {
		this.theCrossSellItem = item;
	};
	
	this.crossSellItem = function() {
		return(this.theCrossSellItem);
	};

	this.setRecommendedItem = function(item) {
		this.theRecommendedItem = item;
	};
	
	this.recommendedItem = function() {
		return(this.theRecommendedItem);
	};

	this.createItemPhotoViewer = function(item) {
		if(this.pvtracker['iv'] == true) {
			var i;
			var titlearray = new Array();
			for(i=0; i < item.photos.length; i++) {
				titlearray[i] = "Click to see different photo of item";
			}
			var tag = 'ipv' + this.displayid + "_" + item.itemid;
			item.pvtv = this.createThumbViewer({
								tag: tag,
								urilist: arrayOf('thumb', item.photos),
								title: titlearray,
								thumbcss: 'tvthumboff',
								thumboncss: 'tvthumbon',
								callback: function(tv, imgno) {
									var display = tv.display;
									var item = display.currentItem();
									item.setPhoto(imgno);
									$('#displayphoto' + display.displayid).attr('src', item.Photo(imgno, 'normal'));
								}, slots: this.pvslots['iv'], css: "ivtvbar"});
			item.setPhoto(0);
		}
		$("#itemphotos" + this.displayid).removeClass().addClass(this.pvclass['iv']);
	};

	this.createCustomerPhotoViewer = function(item) {
		var tag = 'cpv' + this.displayid + "_" + item.itemid;
		if(item.custphotos.length > 0 && this.pvtracker['cv'] == true) {
			item.cpvtv = this.createThumbViewer({
									tag: tag,
									urilist: arrayOf('thumb', item.custphotos),
									title: arrayOf('note', item.custphotos),
									thumbcss: 'tvthumb',
									callback: function(tv, imgno) {
										zoomCustomer(tv.display, imgno);
									}, slots: this.pvslots['cv'], css: "cvtvbar"});
			if(this.cpvtv) {
				this.cpvtv.highlight(0);
			}
		}
		else {
			var html = '<p class="emptycpv">No customer photos available.<br /><a href="javascript:UploadPhoto(';
			html += this.displayid + ')">Upload</a> yours and be the first!</p>';
			$("#" + tag).removeClass().addClass("emptycpv").html(html);
		}

		$("#custphotos" + this.displayid).removeClass().addClass(this.pvclass['cv']);
	};

	this.createSimilarItemViewer = function(item) {
		var tag = "siv" + this.displayid + "_" + item.itemid;
		if(item.coordinatingitems.length > 0 && this.pvtracker['sv'] == true) {
			item.sivtv = this.createThumbViewer({
									tag: tag,
									urilist: arrayOfPhotos('thumb', item.coordinatingitems),
									title: arrayOfPriceAndDesc(item.coordinatingitems),
									thumbcss: 'tvthumbof',
									callback: function(tv, imgno) {
										zoomSimilar(tv.display, imgno);
									}, slots: this.pvslots['sv'], css: "ustvbar"});
									
			$("#" + tag).css({ "width" : item.sivtv.width() + "px"});
			if(this.sivtv) {
				this.sivtv.highlight(0);
			}
		}
		else {
			$("#" + tag).html("");
		}

		$("#siv" + this.displayid).removeClass().addClass(this.pvclass['sv']);
	};
	
	this.createRecommendedItemViewer = function(item) {
		var tag = "riv" + this.displayid + "_" + item.itemid;
		if(item.recommended.length > 0 && this.pvtracker['rv'] == true) {
			item.rivtv = this.createThumbViewer({
									tag: tag,
									urilist: arrayOfPhotos('thumb', item.recommended),
									title: arrayOfPriceAndDesc(item.recommended),
									thumbcss: 'tvthumb',
									callback: function(tv, imgno) {
										zoomRecommended(tv.display, imgno);
									}, slots: this.pvslots['rv'], css: "ustvbar"});
			$("#" + tag).css({ "width" : item.rivtv.width() + "px"});
			if(this.rivtv) {
				this.rivtv.highlight(0);
			}
		}
		else {
			$("#" + tag).html("");
		}

		$("#riv" + this.displayid).removeClass().addClass(this.pvclass['rv']);
	};
	
	this.createItemSelectorViewer = function() {
		if(this.sorteditems.length < 1) {
			return;
		}

		if(this.theme == 3) {
			$("#isv" + this.displayid).css({'display' : 'none'});
			$("#select" + this.displayid).removeClass().addClass("altitemsel");
		}
		else {
			this.isvtv = this.createThumbViewer({
				tag: 'isv' + this.displayid,
				urilist: arrayOfPhotos('thumb', this.sorteditems),
				title: arrayOfPriceAndDesc(this.sorteditems),
				thumbcss: 'tvthumboff',
				thumboncss: 'tvthumbon',
				thumbPad: 4,
				thumbBorder: 1,
				callback: function(tv, imgno) {
					var display = tv.display;
					var item = display.sorteditems[imgno];
					var desc = item.itemid + ' - ' + item.desc;
					_gaq.push(['_trackEvent', 'Shopping', 'SelectProduct', escape(desc)]);
	//				$('#displayphoto' + display.displayid).attr('src', item.Photo(0, 'normal'));
					display.setActiveItem(item.index);
				}, slots: 4, css: "istvbar"});
			this.isvtv.loadViewableImages();
		}
	};


	this.createThumbViewer = function(args) {
		var profile = siteprofile[siteid];
		var tv = new ThumbViewer(args.tag);
		tv.tag = args.tag;
		tv.thumbBorder = args.thumbBorder ? args.thumbBorder : 0;
		tv.thumbPad = args.thumbPad ? args.thumbPad : 6;
		tv.thumbcss = args.thumbcss;
		tv.thumboncss = args.thumboncss;
		tv.thumbSlots = args.slots;
		tv.setImageURIs(args.urilist);
		tv.displayCallback = args.callback;
		tv.itemid = this.itemid;
		tv.display = this;
		tv.css = args.css;
		tv.divcss = 'tvdivcss';
		tv.shadow = profile.pvShadow;
		tv.divheight = profile.pvDivHeight;
		tv.divwidth = profile.pvDivWidth;
		tv.loadingimg = "/images/photoloading50.gif";
		if(args.title) {
			tv.title = args.title;
		}
		tv.generate();
		return(tv);
	};

	this.customValueLength = function() {
		var s;
		if(this.itemDisplayed.custom.type == 0) {
			s = $("#custom" + this.displayid).val();
			return(s.length);
		}
		
		if(this.itemDisplayed.custom.type == 2) {
			var i;
			var ret = 0;
			for(i = 0; i < this.itemDisplayed.custom.data.maxcount; i++) {
				s = $("#custom" + this.displayid + "_" + i).val();
				ret = s.length > ret ? s.length : ret;
			}
			return(ret);
		}
		return(0);
	};

	this.customValueString = function() {
		var s;
		if(this.itemDisplayed.custom.type == 0) {
			s = $("#custom" + this.displayid).val();
			return(s);
		}
		
		if(this.itemDisplayed.custom.type == 2) {
			var i;
			var ret = "";
			var n = 1;
			for(i = 0; i < this.itemDisplayed.custom.data.maxcount; i++) {
				s = $("#custom" + this.displayid + "_" + i).val();
				var shape = $("#customopt" + this.displayid + "_" + i).val();
				if(s.length > 0) {
					if(ret.length > 0) {
						ret = ret + "&";
					}
					
					ret += "name" + n + "=" + s + "&shape" + n + "=" + shape;
					n += 1;
				}
			}
			
			ret += "&count=" + (n - 1);
			
			return(ret);
		}
		return("");
	};

	this.customValueCount = function() {
		if(this.itemDisplayed.custom.type == 0) {
			return(1);
		}
		
		if(this.itemDisplayed.custom.type == 2) {
			var i;
			var ret = 0;
			for(i = 0; i < this.itemDisplayed.custom.data.maxcount; i++) {
				var s = $("#custom" + this.displayid + "_" + i).val();
				if(s.length > 0) {
					ret += 1;
				}
			}
			return(ret);
		}
		return(0);
	};
}

function Item(obj) {
	this.curphoto=0;
	this.coordinatingitems=new Array();
	this.photos=new Array();
	this.custphotos=new Array();
	this.recommended=new Array();
	this.review = "";
	this.qrec = false;

	if(obj) {
		for(var key in obj) {
			this[key] = obj[key];
		}
	}

	this.currentPhoto = function(type) {
		return(this.Photo(this.curphoto, type));
	};
	
	this.Photo = function(index, type) {
		return(this.photos[index][type]);
	};

	this.setPhoto = function(index) {
		this.curphoto = index;
		this.pvtv.highlight(index);
	};

	this.addPhoto = function(p) {
		p.index = this.photos.length;
		this.photos[this.photos.length] = p;
	};

	this.addCustphoto = function(p) {
		this.custphotos[this.custphotos.length] = p;
	};
	
	this.addCoordinatingItem = function(p) {
		this.coordinatingitems[this.coordinatingitems.length] = p;
	};

	this.addRecommendedItem = function(p) {
		this.recommended[this.recommended.length] = p;
	};

	this.addRecommendedItems = function(array) {
		var i;
		var item;
		for(i = 0; i < array.length; i++) {
			item = new Item(array[i]);
			item.title = item.FormattedPrice();
			item.title += ' ' + item.FormattedDesc(false);
			this.recommended[this.recommendedd.length] = item;
		}
	};

	this.applyDiscount = function(percentage) {
		if(customer.isWholesale == false) {
			if(typeof(this.regprice) == "undefined") {
				this.regprice = this.price;
				var theprice = parseFloat(this.price);
				this.price = theprice - (theprice * percentage) + 0.01;
				this.price = this.price.toFixed(2);
			}
		}
	};

	this.FormattedPrice = function() {
  		var s = "<b>";

		if(customer.isWholesale) {
			var dprice = discount(this.price, 0.5) * 12;
//			var hprice = discount(this.price, 0.45) * 6;
			var theprice = dprice.toFixed(2);
			theprice = theprice - dprice.toFixed(0) == 0 ? dprice.toFixed(0) : theprice;
			s = "$" + theprice + " doz.";
		}
		else {
			if(typeof(this.regprice) !== "undefined") {
				if(this.regprice !== this.price) {
					s += '<span class="regprice">$' + this.regprice + '</span> ';
				}
			}
			else {
			}
			s += '$' + this.price;
			if(this.perpair.length > 0) {
				s += this.perpair;
			}
		}
		
		if(this.custom) {
			s = "$$$";
			var c = this.display.customValueLength();
			if(c > 0) {
				s = "$" + this.custom.priceFor(this.display);
			}
		}
		
		s += "</b>";
		
		return(s);
	};
	
	this.Price = function() {
  		var s = "";

		if(customer.isWholesale) {
			var dprice = discount(this.price, 0.5) * 12;
//			var hprice = discount(this.price, 0.45) * 6;
			var theprice = dprice.toFixed(2);
			theprice = theprice - dprice.toFixed(0) == 0 ? dprice.toFixed(0) : theprice;
			s = "$" + theprice + " doz.";
		}
		else {
			s += '$' + this.price;
			if(this.perpair.length > 0) {
				s += this.perpair;
			}
		}

		if(this.custom) {
			s = "$$$";
			var c = this.display.customValue();
			if(c.length > 0) {
				s = "$" + this.custom.priceFor(this.display);
			}
		}

		return(s);
	};

	this.FormattedDesc = function(flag) {
		var s = this.desc;
		if(this.qtylimit > 0) {
			s += (flag ? '<br />' : ' ');
			s += '<b>Limit ' + this.qtylimit + ' per customer.</b>';
		}
		
		return(s);
	};
	
	this.Desc = function() {
		var s = this.desc;
		if(this.qtylimit > 0) {
			s += ' Limit ' + this.qtylimit + ' per customer.';
		}
		
		return(s);
	};
	
	this.addCustom = function(p) {
		this.custom = p;
	};

	this.parseSpecs = function() {
		this.spec = new Array();
		
		if(! this.specs) {
			return;
		}
			
		var pairs = this.specs.split('&');
		for(i = 0; i < pairs.length; i++) {
			var field = pairs[i].split('=');
			this.spec[field[0]] = decodeURI(field[1]);
		}
	};
	
	
	this.Specs = function() {
		if(this.spechtml) {
			return(this.spechtml);
		}
		
		this.parseSpecs();
			
		var html = new Array();

		if(this.spec.w || this.spec.h || this.spec.l || this.spec.d) {
			var metric = GetCookie("metric");
			html.push(metric && metric == 1 ? '<span class="metric"><a class="metric" href="javascript:inches();">Inches</a></span>' : '<span class="metric"><a class="metric" href="javascript:metric();">Metric</a></span>');
		}
		
		html.push('<p class="p2dim">');
		if(this.spec.w) {
			html.push('<span class="p2dimhdr">Width</span><span class="p2dimdata"> ');
			html.push(MetricEnglish(this.spec.w));
			html.push('&nbsp;</span>');
		}
		if(this.spec.h) {
			html.push('<span class="p2dimhdr">Height</span><span class="p2dimdata"> ');
			html.push(MetricEnglish(this.spec.h));
			html.push('&nbsp;</span>');
		}
		if(this.spec.l) {
			html.push('<span class="p2dimhdr">Length</span><span class="p2dimdata"> ');
			html.push(MetricEnglish(this.spec.l));
			html.push('&nbsp;</span>');
		}
		if(this.spec.d) {
			html.push('<span class="p2dimhdr">Diameter</span><span class="p2dimdata"> ');
			html.push(MetricEnglish(this.spec.d));
			html.push('&nbsp;</span>');
		}
		html.push('<span class="p2dimhdr">Item #</span><span class="p2dimdata"> '+this.itemid+'&nbsp;</span></p>');
	
		if(this.spec.ax) {
			html.push('<p class="p2dim">Designed and manufactured exclusively by GirlPROPS.com ');
			if(this.spec.au) {
				html.push(this.spec.au ? 'and<br />Made in USA!</p>' : '</p>');
			}
		}
		else {
			if(this.spec.au) {
				html.push('<p class="p2dim">Made in USA!</p>');
			}
		}
		if(this.spec.ah || this.spec.al || this.spec.an || this.spec.aa) {
			html.push('<p class="p2dim">');
			var s = this.spec.ah ? 'Hypoallergenic' : '';
			s += this.spec.al ? (s.length > 1 ? ' / ' : '') + 'Lead Free' : '';
			s += this.spec.an ? (s.length > 1 ? ' / ' : '') + 'Nickel Free' : '';
			s += this.spec.aa ? (s.length > 1 ? ' / ' : '') + 'Size is adjustable' : '';
			html.push(s + '</p>');
		}
		
		html.push(this.spec.av ? '<p class="p2dim">Vintage item, at least 25 or more years old, discoloration or other visible imperfections may be present, adding to the character of this piece.</p>' : '');
		if(this.custom) {
			html.push('<p class="p2dim">Ships within 5 business days</p>');
		}
		else {
			if(this.onorder) {
				if(this.restocklongdate) {
					html.push('<p class="p2dim">Ships by ');
					html.push(this.restocklongdate);
					html.push('</p>');
				}
				else {
					html.push('<p class="p2dim">Temporarily out of stock, <a href="javascript:contact(\'');
					html.push(this.itemid);
					html.push('\')">Contact us</a> for information</p>');
				}
			}
			else {
				html.push('<p class="p2dim">Ships within 1 business day</p>');
			}
		}
		
		this.spechtml = html.join('');
		return(this.spechtml);
	};
	
	this.clearSpecs = function() {
		this.spechtml = null;
	};
	
	this.hasCustomLetters = function () {
		if(typeof(this.customletters == 'undefined')) {
			return(false);
		}
		
		return(this.customletters);
	};
	
	this.photoViewer = function() { return(this.pvtv); };
	this.custphotoViewer = function() { return(this.cpvtv); };
	this.similarItemViewer = function() { return(this.sivtv); };
}

function Photo(obj) {
	if(obj) {
		for(var key in obj) {
			this[key] = obj[key];
		}
	}
}

function Custom(obj) {
	if(obj) {
		for(var key in obj) {
			this[key] = obj[key];
		}
		
	}
	
//	this.data = parseURI(this.data);
	
	this.priceFor = function(display) {
		var count;
		var val;
		var first;
		var addl;
		if(this.type == 0) {
			count = display.customValueLength();
			first = parseFloat(this.data.first);
			addl = parseFloat(this.data.addl);
			val = first + (count - 1) * addl;
		}
		
		if(this.type == 2) {
			count = display.customValueCount();
			val = parseFloat(this.data.price);
			var i;
			for(i = 0; i < display.itemDisplayed.custom.data.maxcount; i++) {
				var s = $("#custom" + display.displayid + "_" + i).val();
				if(s.length > 0) {
					var selection = $("#customopt" + display.displayid + "_" + i).val();
					val += parseFloat(this.data.options[selection].price);
				}
			}
		}
		
		return(count == 0 ? 0 : val.toFixed(2));
	};
	
	this.validChars = function() {
		return(this.data.valid);
	};
	
	this.validCharsPrettyDisplay = function() {
		var ret = "A-Z ";
		if(this.data.valid.length > 26) {
			var i;
			for(i = 26; i < this.data.valid.length; i++) {
				ret = ret + this.data.valid.substr(i, 1) + " ";
			}
		}
		return(ret);
	};
};

function discount(price, discount) {
	var n = (price - price * discount) * 1000;
	n = parseInt(n, 10);
	var round = n % 10 > 0 ? 10 : 0;
	n += round;
	n -= n % 10;
	n /= 1000;
	return(n.toFixed(2));
}

function parseURI(s) {
	var i;
	
	var obj = new Object();
	var pairs = s.split('&');
	for(i = 0; i < pairs.length; i++) {
		var field = pairs[i].split('=');
		obj[field[0]] = decodeURI(field[1]);
	}
	
	return(obj);
}

function metric() {
	SetCookie("metric", 1);
	RefreshDisplays();
}

function inches() {
	DeleteCookie("metric");
	RefreshDisplays();
}

function RefreshDisplays() {
	var i;
	for(i=0; i < displays.length; i++) {
		displays[i].refresh();
	}
}

function MetricEnglish(inches) {
	var metric = GetCookie("metric");
	if(metric && metric == 1) {
		if(inches > 1) {
			var cm = inches * 2.54;
			return(cm.toFixed(1) + "cm");
		}
		else {
			var mm = inches * 25.4;
			return(mm.toFixed(0) + "cm");
		}
	}
	
	return(DecimalToFraction(inches));
}

function DecimalToFraction(inches) {
	if(inches == 0) {
		return("");
	}
	
	var wh = parseInt(inches, 10);
	var fr = parseInt((inches - wh) * 1000,10);
	
	if(fr == 120) { fr = 125; }
	if(fr == 380) { fr = 375; }
	if(fr == 620) { fr = 625; }
	if(fr == 880) { fr = 875; }
	
	var numerator = fr / 125;
	var ret = "";
	ret = (wh > 0 ? wh : "");
	ret += (wh > 0 && numerator > 0 ? "-" : "");
	ret += (numerator == 1 || numerator == 3 || numerator == 5 || numerator == 7 ? (numerator + "/8") : "");
	ret += (numerator == 2 || numerator == 6 ? ((numerator / 2) + "/4") : "");
	ret += (numerator == 4 ? "1/2" : "");
	
	return(ret + '"');
}

