var opop, dopop=false;

var itemHandler = {};
var shvHandler = {};

function getEltByTagClass(t, c, ctx) {
	if (!ctx) ctx=document;
	var elts=ctx.getElementsByTagName(t);
	var schfor = ' '+c+' ';
	for (var i=0, elt; elt=elts[i]; ++i) { if ((' '+elt.className+' ').indexOf(schfor)!=-1) return elt; }
}

function cart_popup(html, className, f) {
  var e = getEltByTagClass('div', 'cartpopup', f);
	if (e) {
		var e2 = getEltByTagClass('div', 'popup_cont', e);
		if (e2) {
			e.style.visibility = 'hidden';
			e.style.position = 'absolute';
			e2.innerHTML = html;
			var endht = e.offsetHeight;
			e.style.height = '0';
			e.style.position = 'relative';
			e.style.visibility = 'visible';
			e.className = 'cartpopup '+className;

			var anim = new YAHOO.util.Anim(e, {height: {from: 0, to: endht}}, 1, YAHOO.util.Easing.easeBoth);
			anim.animate();
		}
	}
}

function getAncestorWithClass(e, cls) {
	var schfor = ' '+cls+' ';
	while (e && (' '+e.className+' ').indexOf(schfor)==-1) e=e.parentNode;
	return e;
}

function getAncestorWithId(e, id) {
	while (e && e.id!=id) e=e.parentNode;
	return e;
}

function show_opop() {
	if (!opop) opop = document.getElementById('ordering_pop');
	if (opop) {
		opop.innerHTML = '<div class="wait">Adding to cart...</div>';

		var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
		if (!window.YD) YD=YAHOO.util.Dom;
		opop.style.top = (Math.floor((YD.getViewportHeight()-50)/2)+scrollTop)+'px';
		opop.style.left = Math.floor((YD.getViewportWidth()-300)/2)+'px';
		opop.style.display = 'block';
	}
}

itemHandler.showWaiting = function(f) {
	dopop = true;
	itemHandler.pdelt = getAncestorWithClass(f, 'product_detail');
}

itemHandler.addedText = '<b>Item Added to Cart</b>.&nbsp;&nbsp;'+
							'<b><a href="http://order.store.yahoo.net/cgi-bin/wg-order?scrapbook-dot-com">View Cart</a></b>&nbsp;|&nbsp;'+
							'<b><a href="http://order.store.yahoo.net/cgi-bin/wg-order?scrapbook-dot-com">Checkout</a></b>';

itemHandler.oosText = '<b>Item out of stock.</b>';

itemHandler.oosTextMulti = 'The requested quantity was not available. Some may have been added to your cart.';

itemHandler.success = function(total, icount) {
	if (dopop) {
		var emsg = '<div class="itemadded">'+itemHandler.addedText+'</div>';
		if (itemHandler.pdelt) cart_popup(emsg, '', itemHandler.pdelt);
		if (window.quicklookSetup) window.quicklookSetup();
		window.scroll(0,0);
	}
}

itemHandler.oos = function(total, icount) {
	if (dopop) {
		var emsg = addqty>1 ? '&nbsp;&nbsp;<span class="qtyunav">'+itemHandler.oosTextMulti+'</span>' : '<span class="qtyoos">'+itemHandler.oosText+'</span>';
		if (icount>0) {
			emsg += '&nbsp;<b><a href="http://order.store.yahoo.net/cgi-bin/wg-order?scrapbook-dot-com">View Cart</a></b>';
		}
		if (itemHandler.pdelt) cart_popup(emsg, 'cpwarn', itemHandler.pdelt);
		if (window.quicklookSetup) window.quicklookSetup();
		window.scroll(0,0);
	}
}

shvHandler.showWaiting = function(f) {
	show_opop();
}

shvHandler.success = function(total, icount) {
	if (opop) opop.style.display = 'none';
	if (shopt && shopt.statusPopIn) shopt.statusPopIn(itemHandler.addedText);
}

shvHandler.oos = function(total, icount) {
	if (opop) opop.style.display = 'none';
	if (shopt && shopt.statusPopIn) shopt.statusPopIn(itemHandler.oosText);
}

var key, addqty=0, handler=null;

function cart_bkgnd() {
	var c = document.getElementById('ncarthldr');
	if (!c) {
		setTimeout(cart_bkgnd, 500);
		return;
	}

	key = Math.floor(Math.random()*0x7fffffff);
	handler = null;
	var callback="";
	if (window.location.hostname=="dev.scrapbook.com") callback="_1";
	else if (window.location.hostname=="store.scrapbook.com") callback="_2";
	else if (window.location.hostname=="devstore.scrapbook.com") callback="_3";
	var framename = "shcart_"+key+callback;
	c.innerHTML = "<iframe name='"+framename+"' style='display:none;' src='http://order.store.yahoo.net/cgi-bin/wg-order?scrapbook-dot-com'></iframe>";
}

function ck_cart() {
	var e = document.getElementById('cartttl');
	if (!e) {
		setTimeout(ck_cart, 500);
		return;
	}

	var cartre = /; ?cartval=([\d.]+),(\d+),(\d+);/;
	if (cartre.test(";"+document.cookie+";")) {
		var total = RegExp.$1;
		var icount = RegExp.$2;
		var expts = RegExp.$3;
		var nowts = (new Date().getTime());
		if (nowts<expts) {
			e.innerHTML = icount+" item"+(icount==1 ? '' : 's')+"\u00a0\u00a0$"+total;
			return;
		}
	}

	cart_bkgnd();
}
setTimeout(ck_cart, 500);

function cart_common(total, icount) {
	var e = document.getElementById('cartttl');
	if (e) e.innerHTML = icount+" item"+(icount==1 ? '' : 's')+"\u00a0\u00a0$"+total;

	var d = new Date();
	var expt = d.getTime() + 1000*60*60;
	d.setTime(expt); // One hour
	document.cookie = "cartval="+total+","+icount+","+expt+"; expires="+d.toGMTString()+"; path=/; domain=.scrapbook.com";
}

function cart_success(total, icount) {
	cart_common(total, icount);
	if (handler && handler.success) handler.success(total, icount);
	var forms=document.getElementsByTagName('form');
	for (var i=0, form; form=forms[i]; ++i) {
		if (form.className=='cartadding') form.className='cartadded';
	}
}

function cart_oos(total, icount) {
	cart_common(total, icount);
	if (handler && handler.oos) handler.oos(total, icount);
	var forms=document.getElementsByTagName('form');
	for (var i=0, form; form=forms[i]; ++i) {
		if (form.className=='cartadding') form.className='cartoos';
	}
}

function cart_fail() {
	window.location = 'http://order.store.yahoo.net/cgi-bin/wg-order?scrapbook-dot-com';
}

function cartmsg2(s) {
	args=s.split(',');
	if (args[0]==key) {
		key = Math.floor(Math.random()*0x7fffffff);
		if (args[1]=='ok') {
			cart_success(args[2], args[3]);
		} else if (args[1]=='out') {
			cart_oos(args[2], args[3]);
		} else {
			cart_fail();
		}
		handler = null;
	}
}

function quicksubmit(f, h) {
	var c = document.getElementById('ncarthldr');
	if (f && c) {
		key = Math.floor(Math.random()*0x7fffffff);
		var callback="";
		if (window.location.hostname=="dev.scrapbook.com") callback="_1";
		else if (window.location.hostname=="store.scrapbook.com") callback="_2";
		else if (window.location.hostname=="devstore.scrapbook.com") callback="_3";
		var framename = "shcart_"+key+callback;
		c.innerHTML = "<iframe name='"+framename+"' style='display:none;'></iframe>";

		if (f.vwquantity) {
			addqty = +f.vwquantity.value;
			if (addqty==0) {
				f.vwquantity.value = "1";
				addqty = 1;
			}
		}

		var curkey=key;
		setTimeout(function() {if (key==curkey) cart_fail()}, 15000);

		handler = h;
		if (handler && handler.showWaiting) handler.showWaiting(f);

		f.className = 'cartadding';
		f.target = framename;
		f.submit();
		return false;
	}
	return true;
}

function toggleShowObject(obj) {
	if(document.getElementById(obj) != null) {
		document.getElementById(obj).className = document.getElementById(obj).className == 'hideit' ? 'showit' : 'hideit';
	}
}

function popAvailable(URL, height, width) {
window.open(URL,"thewindow","toolbar=no,width="+width+", height="+height+", status=no, scrollbar=no, resize=no, menubar=no");
}

var enlargePanel;

function onEnlargeHidden() {
	YE.removeListener(document.body, "mousedown", enlargeMouseDown);
	YD.setXY(enlargePanel.element, [0,0]);
	enlargePanel=null;
}

function enlargeMouseDown(ev) {
	if (enlargePanel && !ptIn(YE.getXY(ev), YD.getRegion(enlargePanel.element))) {
		enlargePanel.hide();
	}
}

function enlargeImage(name, href, wd, ht) {
	enlargePanel = new YAHOO.widget.Panel("enlargeImg",
    {
      close:true,
      visible:false,
      constraintoviewport:true,
      zIndex:30
    }
  );
  enlargePanel.setHeader('Image');
  var i = document.createElement('img');
  i.width = wd;
  i.height = ht;
  i.src = href;
  enlargePanel.setBody(i);
  enlargePanel.render(document.body);
  enlargePanel.center();
  enlargePanel.show();
  enlargePanel.subscribe('hide', onEnlargeHidden);

	YE.addListener(document.body, "mousedown", enlargeMouseDown);

  return false;
}

function availableHTML2(s,sku,pid,btnReplace) {
	var elts = document.getElementsByTagName('span');
	// Can't use getElementById because there might be more than one!
	for (var i=0, elt; elt=elts[i]; ++i) {
		if (elt.id=='avail_'+sku) {
			elt.innerHTML = s;
			if (btnReplace) {
				var w = getAncestorWithClass(elt, 'prod-info-wrapper');
				if (w) {
					var e = getEltByTagClass('div', 'prod-info-bottom', w);
					if (e) e.innerHTML = btnReplace;
				}
			}
		}
	}
}

function skuShareData(sku, emailHTML, shareHTML, printHTML, favHTML, wishHTML) {
	var elts = document.getElementsByTagName('div');
	// Can't use getElementById because there might be more than one!
	for (var i=0, elt; elt=elts[i]; ++i) {
		if (elt.id=='share_'+sku) {
			elt.setAttribute('downloaded', 1);
		
			var shv_mode = !(!getAncestorWithId(elt, 'shdetail'));
			var e;
			if (!shv_mode) {
				if (e=getEltByTagClass('div', 'share_email_txt', elt)) e.innerHTML = emailHTML;
				if (e=getEltByTagClass('div', 'share_share_txt', elt)) e.innerHTML = shareHTML;
				if (e=getEltByTagClass('div', 'share_print_txt', elt)) e.innerHTML = printHTML;
			}
			if (e=getEltByTagClass('div', 'share_fav_txt', elt))   e.innerHTML = favHTML;
			if (e=getEltByTagClass('div', 'share_wish_txt', elt))  e.innerHTML = wishHTML;
		}
	}
}

function shareTab(btn, cls) {
	var e = getAncestorWithClass(btn, 'sku_share');
	if (e) {
		e.className = 'sku_share '+cls;
		if (e.id.substr(0,6)=="share_") {
			var sku=e.id.substr(6);
			
			if (!e.getAttribute('downloaded')) {
				var newelt = document.createElement('script');
				newelt.src = "http://www.scrapbook.com/products/sku_share.php?sku="+escape(sku)+'&r='+Math.floor(Math.random()*(1<<30));
				e.appendChild(newelt);
			}
		}
	}
}

function shareEmail(btn) { shareTab(btn, 'sku_share_email'); }
function shareShare(btn) { shareTab(btn, 'sku_share_share'); }
function sharePrint(btn) { shareTab(btn, 'sku_share_print'); }
function shareFav(btn) { shareTab(btn, 'sku_share_fav'); }
function shareWish(btn) { shareTab(btn, 'sku_share_wish'); }

function openProdPage(url) { window.location = url; }

function shareClose(btn) {
	var e = getAncestorWithClass(btn, 'sku_share');
	if (e) e.className = 'sku_share';
}

function clearElt(elt) {
	elt.innerHTML = '';
}

function setWishlist(obj, product_id) {
	var v = obj.checked ? 1 : 0;

	var e = document.createElement('script');
	e.src = 'http://www.scrapbook.com/wishlist/?m=ajaxwish&p='+product_id+'&chk='+v;
	document.body.appendChild(e);

	var msgObj = getEltByTagClass('div', 'wishMsg', obj.parentNode);
	if (msgObj) {
		msgObj.innerHTML = v ? '<img src="http://www.scrapbook.com/images/littlesaved.gif">' : '<img src="http://www.scrapbook.com/images/littleremoved.gif">';
		setTimeout(function() {clearElt(msgObj);}, 1000);
	}
}

function setFavorite(obj, product_id) {
	var v = obj.checked ? 1 : 0;

	var e = document.createElement('script');
	e.src = 'http://www.scrapbook.com/wishlist/?m=ajaxfav&p='+product_id+'&chk='+v;
	document.body.appendChild(e);

	var msgObj = getEltByTagClass('div', 'favMsg', obj.parentNode);
	if (msgObj) {
		msgObj.innerHTML = v ? '<img src="http://www.scrapbook.com/images/littlesaved.gif">' : '<img src="http://www.scrapbook.com/images/littleremoved.gif">'
		setTimeout(function() {clearElt(msgObj);}, 1000);
	}
}
