//functions used by some generic pages

function goGalleryByName(galName) {
	goGalleryPageByName('', galName);
}

function goGalleryPageByName(pageName, galName) {

	f = document.galNameform;
	f.name.value=galName;
	f.page.value=pageName;
	f.submit();
}

function goGallery(galleryId) {
	goGalSeq(galleryId, 0);
}
	
function goGalleryStore(galleryId) {
	f = document.galform;
	setBid(f, false);
	goGalSeqF(f, galleryId, 0, '');
}

function goGalleryBoutique(thisBid, galleryId) {
	f = document.galform;
	if (typeof(f.bid) == 'undefined') {
		//UNEXPECTED
	}
	f.bid.disabled = false;
	f.bid.value = thisBid;

	goGalSeqF(f, galleryId, 0, '');
}

function goGalSeqIfNum(galleryId, max, multiplier, page, value) {
	value = parseInt(value);
	if (isNaN(value) || value < 1 || value > max) {
		alert("You must enter a page number between 1 and " + max + ".");
		return;
	}
	goGalSeq(galleryId, multiplier * (value - 1), page);
}

function goGalSeq(galleryId, seq, page) {
	f = document.galform;
	setBid(f, true);
	goGalSeqF(f, galleryId, seq, page);
}

function goGalSeqF(f, galleryId, seq, page) {
	if (galleryId != '') {
		f.gallery_id.value=galleryId;
	}
	if (typeof(f.page) != 'undefined') {
		f.page.value = typeof(page) != 'undefined' ? page : '';
	}
	f.sequencenum.value=seq;
	//window.alert("submitting " + f + " to " + f.action);
	f.submit();
}

function goPage(p) {
	f = document.pageform;
	f.page.value = p;
	f.submit();
}


function goCart() {
	f = document.gocart;
	//assure not secure
	var l = f.action.replace(/^https?:/, 'http:') 
			+ '?process=display';
	if (f.elements.provider_id) 
		l += '&provider_id=' + f.elements.provider_id.value;
	location.href = l;
}

function goAccount() {
	goPtpProcess('account');
}

function goPtpProcess(proc) {

	f = document.gocart;
	f.process.value = proc;

	if (typeof inPopup == 'undefined' &&
			(typeof daughterWindow == "undefined" || daughterWindow != 'false')) {
		tgt = 'ptp_' + providerID,
		win = window.open('', tgt,
			'scrollbars=yes, resizable=yes, toolbar=no, '
			+ 'status=yes,width=650,height=500, menubar=no');
		f.target = tgt;
		f.submit();
		win.focus();
	} else {
		f.submit();
	}
}

//default is to store
function goHome() {
	f = document.gohome;
	setBid(f, false);
	f.submit();
}

function goHomeBoutique() {
	f = document.gohome;
	setBid(f, true);
	f.submit();
}

function goDeliver(pg) {
	f = document.godeliver;
	f.page.value = pg;
	setBid(f, true);
	f.submit();
}

function goDeliverStore(pg) {
	f = document.godeliver;
	f.page.value = pg;
	setBid(f, false);
	f.submit();
}

function setBid(f, inBoutique) {
	if (typeof f.bid == 'undefined')
		//nothing to do
		return;
	
	if (!inBoutique || typeof bID == 'undefined') {
		//turn off including case of not set 
		f.bid.value = '';
		return;
	}
	f.bid.value = bID;
}


function goCategory(t) {
	f = document.category_form;
	f.value1.value = t;
	f.page.value = t;
	f.submit();
}

function populateGalSelect(sel) {
	//grab galleries from list and add to select
	if (typeof galleryList == "undefined")
		return;

	var inx = sel.options.length;
	for(i = 0; i < galleryList.length; i++) {
		sel.options[inx] = new Option(galleryList[i][1], galleryList[i][0]);
		inx++;
	}
}

function isLoggedIn() {
	if (typeof(providerID) == 'undefined')
		return false;

	var l = ReadCookie("ptp_log_" + providerID);
	return (l == '1');
}

function writeAccountDivs(divClass, aClass) {
	writeAccountDivsWithSep(divClass, aClass, '');
}

//separate elements if necessary
function writeAccountDivsWithSep(divClass, aClass, sep) {
	if(isLoggedIn()) {
		document.write(
			'<div class="' + divClass + '">'
			+ '<a href="javascript:goAccount();" class="' + aClass + '">Your Account</a>'
			+ '</div>'
			+ sep
			+ '<div class="' + divClass + '">'
			+ '<a href="' + progname + '?process=logout&provider_id=' 
			+ providerID + '" class="' + aClass + '">Log out</a>'
			+ '</div>');
		return;
	}
	document.write(
		'<div class="' + divClass + '">'
		+ '<a href="javascript:goPtpProcess(' + "'go_register'" 
		+ ');" class="' + aClass + '">Log In/Register</a>'
		+ '</div>');
}

function ReadCookie(cookieName) {
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return "";
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length;
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

//cookie will expire at session end
function writeCookie(name, value, expires, path, domain, secure) {
	//alert('write:' + name + ' v=' + value);
	if (expires && (expires.constructor == String) && expires.match(/^\+\d+h$/)) { 
		var msec = parseInt(expires.replace(/^\+/,'').replace('h$')) * 3600000;
		expires = new Date();
		expires.setTime(expires.getTime() + msec);
	}
  document.cookie = name + "=" + escape (value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		"; path=" + (path ? path : "/") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}

//incrementCookie and return current value (zero if not set)
function incrementCookie(cookieName, max) {
	var c = ReadCookie(cookieName);
	c = (c == '') ? 0 : parseInt(c);
	writeCookie(cookieName, new String(c >= max - 1 ? 0 : c + 1), false, '/');
	return (c >= max ? max - 1 : c);
}

function setRandImgLink(cookieName, vals, cl, imgSuffix) {
	if (typeof(vals) == 'undefined' || vals.length == 0)
		return;

	var n = ReadCookie(cookieName);
	if (n == '')
		n = Math.floor(Math.random() * vals.length);
	else
		n = (parseInt(n) == vals.length - 1) ? 0 : parseInt(n) + 1;

	var v = '<a href="' + vals[n][1] + '"><img class="' + cl + '" src="' 
		+ vals[n][0] + imgSuffix + '"/></a>';
	//alert('n=' + n + ' ' + vals[0][0] + '=' + vals[0][1] + ' towrite=' + v);
	
	document.write(v);
	writeCookie(cookieName, n);
}


//new turner pieces


/*
 *	dir is +1 or -1 if backwards or forwards
 *  arr is array of image IDS
 *	turner is an associative array containing
 *	imgName name of first image in set
 *	numVisible number of images
 *	name of elements
 *	size of images
 * 	prev/next - div for previous
 * 	prevDead, prevLink
 *  nextDead, nextLink
 *  currentOffset
 */

function turnerShift(turner, dir) {
	
	var arr = turner["arr"];

	//can't go past start or end
	if (turner["currentOffset"] + dir * turner["numVisible"] < 0
			|| turner["currentOffset"] + dir * turner["numVisible"] >= arr.length) 
		return;
	
	turner["currentOffset"] += dir * turner["numVisible"];
	turnerSet(turner);
}

function turnerSet(turner) {

	var arr = turner["arr"];

	//adjust imagery
	for (var i = 0; i < turner["numVisible"]; i++) {
		var img = document.images[turner["name"] + "Img_" + i];
		if (typeof(img) == 'undefined')
			continue;

		if (turner["currentOffset"] + i >= arr.length ) {
			img.src = "/images/spacer.gif";
			continue;
		}
		img.src = image_progname + '?size=' + turner["size"] +'&amp;ptp_photo_id='
					+ ptpPhotoIds[turner["currentOffset"] + i]
					+ '&amp;provider_id=' + (bID == '' ? providerID : bID);
	}

	//set turners 
	if (typeof(turner["prev"]) != "undefined") 
		if (turner["currentOffset"] == 0) 
			turner["prev"].innerHTML = turner["prevDead"];
		else 
			turner["prev"].innerHTML = 
			'<a href="javascript:turnerShift(' + turner["name"] + ', -1);">'
			+ turner["prevLink"] + '</a>';
	
	if (typeof(turner["next"]) != "undefined") { 
		if (turner["currentOffset"] + turner["numVisible"] > arr.length)
			turner["next"].innerHTML = turner["nextDead"];
		else
			turner["next"].innerHTML = 
			'<a href="javascript:turnerShift(' + turner["name"] + ', 1);">'
			+ turner["nextLink"] + '</a>';
	}

	//set keys
	var step = 0;
	var re = new RegExp('\\$num');
	for (var i = 0; i < arr.length; i+= turner["numVisible"]) {
		var div = document.getElementById(turner["name"] + "Key_" + step);
		step++;

		if (div == null)
			continue;

		if (turner["currentOffset"] >= i 
				&& turner["currentOffset"] < i + turner["numVisible"]) {
				div.innerHTML = turner["keyDead"].replace(re, step);
		} else 
			div.innerHTML = 
			'<a href="javascript:turnerJump(' + turner["name"] + ', ' 
			+ i + ');">' + turner["keyLink"].replace(re, step)
			+ '</a>';
	}
}

function turnerJump(turner, pos) {
	turner["currentOffset"] = pos;
	turnerSet(turner);
}

function turnerGo(turner, pos) {
	
	var arr = turner["arr"];

	hotlink(arr[turner["currentOffset"] + pos]);
}

function magnifierPop(img, css, w, h) {
	var magWin = window.open('', 'ptpmagnifier',
		'scrollbars=no,resizable=no, toolbar=no,status=no,titlebar=no'
		+ 'menubar=no,width=' + w + ',height=' + h);
	try {
		magWin.focus();
	} catch(e) {
		window.blur();
	}

	var scr = '';
	var onl = '';
	if (typeof(rightClickMessage) != 'undefined') {
		onl = ' onLoad="setW();"';
		scr = '<script language="javascript" type="text/javascript" src="/ptp/std2/ptp.js">'
			+ '//include</script>'
			+ '<script language="javascript"  type="text/javascript">'
			+ "var popRightClickMessage = '" + escape(rightClickMessage) + "';"
			+ 'function setW() {'
			+ "document.getElementById('popImg').onmousedown = popImgWarning;"
			+ "document.getElementById('popImg').oncontextmenu = popImgWarning;"
			+ '}'
			+ '</script>'
	}

	var d = magWin.document;
	d.open();
	d.write('<html><head>'
	+ '<meta http-equiv="imagetoolbar" content="no">'
	+ '<title>Magnified View</title>'
	+ scr
	+ '<link href="/ptp/gal/styles.css" type="text/css" rel="stylesheet">'
	+ (css != '' ? 
		'<link href="' + css + '" type="text/css" rel="stylesheet"></head>'
		: ''
		)
	+ '<body class="ptpPopUp" ' + onl + '>'
	+ '<div align="center"><table height="100%">'
	+ '<tr><td valign="middle" height="100%">'
	+ '<img id="popImg" src="' + img + '" >'
	+ '<p style="text-align:right;"><a href="javascript:window.close();">'
	+ '<img src="/images/spacer.gif" border="0" class="ptpCloseButton"/>'
	+ '</a></p></td></tr>'
	+ '</table></div>'
	+ '</body></html>');
	d.close();
}

//functions for scrolling bar
function runScroll(sName) {
	var s = eval(sName);
	
	if (typeof s.inSetup == 'undefined') {
		if (typeof s.mayNeedRestart == 'undefined') {
			//wait for a moment
			s.mayNeedRestart = true;
			s.tmr = setTimeout("runScroll('" + sName + "')",10);
			return;
		}
		//okay then attempt to reset
		s.inSetup = true;
		s.tmr = setTimeout("setScroller('" + sName + "')", 1);
		return;
	} 
	if (s.inSetup)
		return;

	if (s.tmr)
		clearTimeout(s.tmr);
		
	if (s.dir == 0) 
		s.dir = -1;
	var l = parseInt(s.div.style.left);

	//may switch directions
	if ((s.dir == -1 && (s.width + l) <= s.containerWidth)
			|| (s.dir == 1 && l >= 0)) {
		s.dir *= -1;
		s.pause = s.pauseCycles;
	} 

	if (s.pause) 
		s.pause--;
	else
		s.div.style.left = (l + s.dir * s.speed) +"px";

	//remember action 
	writeCookie('ptp_' + s.dName + '_' + providerID, 
			s.div.style.left + '_' + s.dir, false, '/');

	s.tmr = setTimeout("runScroll('" + sName + "')",s.timeout);
}

//sName is name of scroller object; 
//contains already set these values
// s.speed = 3 - distance to move 
// s.timeout = 30 - milliseconds between moves;
// s.pauseCycles = 20 =- milliseconds to pause at ends;
// s.dName = the name of the div is being moved
function setScroller(sName){
	var s = eval(sName);
	s.inSetup = true;

	//in case we have looped here
	if (s.tmr2)
		clearTimeout(s.tmr2);
	
	s.width = 0;
	s.div = document.getElementById(s.dName);

	for (var i  = 1; document.getElementById(s.dName + i) != null; i++) {
		var img = document.getElementById(s.dName + i);
		if ((typeof img.complete != 'undefined' && !img.complete)
				|| (typeof img.complete == 'undefined' && img.width == 0)) {
			//wait for a moment for image
			s.tmr2 = setTimeout("setScroller('" + sName + "')", 5);
			return;
		}
		s.width += img.width + s.cellPadding;
	}

	//and set for div too
	s.div.style.width = s.width;
	
	//state parameters
	s.dir = 0;
	s.tmr = 0;
	s.pause = 0;

	//see if already stored
	var c = ReadCookie('ptp_' + s.dName + '_' + providerID);
	if (c != '') {
		s.dir = parseInt(c.replace(/.*_/,''));
		s.div.style.left = c.replace(/_.*/,'');
	}

	s.inSetup = false;
	//and start running
	runScroll(sName);
}

function stopScroll(s){
	if (s.tmr) clearTimeout(s.tmr);
}

function moveScrollLeft(s){
	stopScroll(s);
	s.div.style.left=0+"px";
}

//outputs an href image line 
function outImgHref(u, img, title) {
	var t = typeof(title) != 'undefined' ? ' title="' + title + '" ' : '';
	document.write('<a href="' + u + '">'
			+ '<img src="' + img + '" border="0" ' + t + '/>'
			+ '</a>');
}

//outputs an href text line
function outTxtHref(u, txt, title) {
	var t = typeof(title) != 'undefined' ? ' title="' + title + '" ' : '';
	document.write('<a href="' + u + '">'
			+ txt
			+ '</a>');
}

function writeImage(src, link) {
	if (link != null) 
		document.write('<a href="' + link + '">');

  document.write('<img src="' + src + '">');

	if (link != null) 
		document.write('</a>');
}

//THIS is used for any dynamic messaging
var addLbxInProgress = 0;
var lbxMsgDiv = null;
function addLightbox(url, dv) {
	//avoid race by auto-incrementing on test
	if (addLbxInProgress++) {
		alert("An add is currently in progress.");
		return void(0);
	}
	urlPost(url, dv, '');
}

//dontworry about race here
function formPost(f, dv, msg) {
	f.target = "lbxFrame";
	lbxMsgDiv = dv;
	if (msg != null) {
		document.getElementById(dv).innerHTML = '<div class="ptpPendMessage">' + msg + '</div>';
		show(dv);
	}
	f.submit();
}

function urlPost(url, dv, msg) {
	lbxMsgDiv = dv;
	if (msg != null) {
		document.getElementById(dv).innerHTML = '<div class="ptpPendMessage">' + msg + '</div>';
		show(dv);
	}
	frames["lbxFrame"].location.href = url;
}

function completeLightboxAdd(msg, emsg) {
	completePostDisplay(msg,emsg, lbxMsgDiv, false);
	addLbxInProgress = 0;
}
function completePostDisplay(msg,emsg, dv, withCartLink) {
	if (dv == null)
		dv = lbxMsgDiv;

	var m = '';
	if (msg) 
		m += '<div class="ptpMessage">' + msg +  
			(withCartLink ? '<div class="start"><a href="javascript:goCart();">View Cart</a></div></div>' : '');
	if (emsg) 
		m += '<div class="ptpErrorMessage">' + emsg + '</div>';

	if (m != '') {
		show(dv);
		document.getElementById(dv).innerHTML = m;
	} else 
		hide(dv)
}

/*
 *DynamicTurner Functions
 */
var dynamicTurners = [];
function dynamicTurnerSet(turner) {
	//always remember
	dynamicTurners[turner.name] = turner;

	//may require get of more data...will be available in chunks
	var needGrabMin = null;
	var needGrabMax = null;
	for (var i = 0; i < turner.count; i++) {
		if (i + turner.currentOffset < turner.photoCount
				&& typeof(turner.photos[i + turner.currentOffset]) == 'undefined') {
			if (needGrabMin == null)
				needGrabMin = i + turner.currentOffset;
			needGrabMax = i + turner.currentOffset;
		}
	}
	if (needGrabMin != null) {
		//go grab...as much as possible up to limit
		var off = needGrabMax < turner.minPos
			? Math.max(0, Math.min(turner.minPos - turner.grabLimit, needGrabMin))
			: (turner.maxPos + turner.grabLimit < needGrabMax
			? needGrabMax - turner.grabLimit + 1
			: turner.maxPos + 1
			);
		/*
		var myAjax = new Ajax.Request(
			turner.grabUrl.replace(/\%s/, off),
			{
			method: 'get',
			onComplete: dynamicTurnerSetValues
			});
		*/
		var myAjax = ajaxRequest(
			turner.grabUrl.replace(/\%s/, off),
			{
			method: 'get',
			onComplete: dynamicTurnerSetValues
			});
		return;
	}
	
	//first prev and next
	var dv = document.getElementById(turner.name + '_prev');
	if (dv != null) 
		dv.innerHTML = turner.currentOffset != 0
				? '<a href="javascript:dynamicTurnerShift('
				 + turner.name + ',' + (-turner.count) + ');void(0)">'
				 + turner.prevLink 
				 + '</a>'
				: turner.prevDead;

	dv = document.getElementById(turner.name + '_next');
	if (dv != null) 
		dv.innerHTML = turner.currentOffset + turner.count < turner.photoCount
				? '<a href="javascript:dynamicTurnerShift('
				 + turner.name + ',' + turner.count + ');void(0)">'
				 + turner.nextLink 
				 + '</a>'
				: turner.nextDead;
			
	dynamicTurnerPhotoSet(turner);

	//here so turner in scope
	function dynamicTurnerSetValues(req) { 
		var out = null;
		try {
			eval ("out = " + req.responseText);
		} catch(e) {
			//reply failed...ignore
			return;
		} 
		var snum = out.sequencenum;
		for (var i = 0; i < out.gallery_photo.length; i++) 
			turner.photos[snum + i] = loadPhotoData(
					out.gallery_photo[i], 
					turner.photoFieldNames);

		//and go set up
		dynamicTurnerSet(turner);
	}
}
			
function loadPhotoData(p, photoFieldNames) {
	var values= {
		qid : p.qid,
		title : p.title,
		width : (typeof(p.orig_width) != 'undefined'
			? p.orig_width : p. width),
		height : (typeof(p.orig_height) != 'undefined'
			? p.orig_height : p. height),
		photoFields : []
		};

	//get photoFields
	for (var i = 0; i < photoFieldNames.length; i++) {
		var name = photoFieldNames[i];

		if (name.substr(0, 9) == 'metadata/') {
			name = name.substr(9);
			if (typeof(p.metadata) != 'undefined' 
					&& typeof(p.metadata[name]) != 'undefined')
				values.photoFields.push(escape(p.metadata[name]));
		} else if (name == 'gallery_name') {
			if (p && p.gallery && typeof(p.gallery) != 'undefined') {
				for (var j = 0 ; j < p.gallery.length; j++) {
					var v = p.gallery[j].gallery_name;
					var inx = v.indexOf('/');
					while (inx != -1) {
						values.photoFields.push(escape(v.substr(0, inx)));
						v = v.substr(inx + 1);
						inx = v.indexOf('/');
					}
					values.photoFields.push(escape(v));
				}
			}
		} else {
			if (typeof(p[name]) != 'undefined') 
				values.photoFields.push(escape(p[name]));
		}
	}
	return values;
}

function dynamicTurnerPhotoSet(turner) {
	//we init turnerDivs if need be
	if (typeof(turner.divs) == 'undefined') {
		turner.divs = new Array();
		for (var i = 0; i < turner.count && i < turner.photoCount; i++) {
			turner.divs[i] = new Array();
			turner.divs[i]['imgs'] = new Array();

			var dvName = turner.name + '_' + i;
			imgs = document.getElementById(dvName).getElementsByTagName('IMG');
			for (var j = 0; j < imgs.length; j++) {
				if (!imgs[j].src.match(/[\&\?]ptp_photo_id=/)) 
					continue;
				turner.divs[i]['imgs'].push(imgs[j]);
			}
		}
	}
	for (var i = 0; i < turner.count; i++) {
		var dvName = turner.name + '_' + i;
		if (i + turner.currentOffset >= turner.photoCount) {
			hide(dvName);
			continue;
		}
		show(dvName);
		//replace imgs with ptp_photo_id set
		for (var j = 0; j < turner.divs[i].imgs.length; j++) {
			var im =  turner.divs[i].imgs[j];
			//swap out
			im.src = im.src.replace(/([\&\?])ptp_photo_id=[^\&]*/,
					"$1ptp_photo_id=" + turner.photos[i + turner.currentOffset].qid);
			im.title = turner.photos[i + turner.currentOffset].title;
			//and add in conditional
			if (turner.type == 'shufflePhotos') {
				setShuffleTurnerObserver(im, turner, i);
			}
		}
	}
}

function dynamicTurnerShift(turner, delta) {
	//nothing to do if on edges
	if (delta <= 0) {
		if (turner.currentOffset == 0)
			return;
		turner.currentOffset = Math.max(turner.currentOffset + delta, 0);
	} else {
		if (turner.currentOffset + turner.count >= turner.photoCount)
			return;
		//if off end reduce to one movement (this should never happen
		if (turner.currentOffset + delta >= turner.photoCount)
			delta = turner.count;
		turner.currentOffset += delta;
	}
	dynamicTurnerSet(turner);
}

function dynamicTurnerGo(turner, step) {
	hotlinkSeq(turner.photos[turner.currentOffset + step].qid, turner.currentOffset);
}
function dynamicTurnerPageGo(turner, step, page) {
	hotlinkPageSeq(turner.photos[turner.currentOffset + step].qid, turner.currentOffset, page);
}

function writeCartSummary(pns, pfx, divClass, aClass, alt) {
	var v = cartSummary(
			'pct_' + pns, 
			pfx, divClass, aClass, 
			'http://' + location.host + '/perl/ptp/' + pns + '?process=display',
			alt);
	if (v.length) 
		document.write(v);

}

function cartSummary(cname, pfx,divClass,aClass, hr, alt) {
	var c = ReadCookie(cname);
	if (c.length != 0
		&& (isNaN(c) || c != 0)
		) {
		return '<div class="' + divClass + '">' 
			+ '<a class="' + aClass + '" href="' + hr + '">'
			+ pfx
			+ c + '</a>'
			+ '</div>';
	} else if (alt.length) {
		return alt;
	}
	return '';
}

function returnShopping(pId, galPName) {
  var u=ReadCookie('ptp_url_' + pId);

	if (u.length == 0) {
    //go to opener first, not home
		if (window.opener && !window.opener.closed && window.opener != self) {
			var ok = true;
			try{
				window.opener.focus();
			}catch(e){
				ok = false;
			}
			if (ok) 
				return;
		}
		goHome();
	}

	var u1 = (!unescape(u).match(/^\//)
			? galPName + '?'
			:''
		)
		+ unescape(u)
		+ (u.match(/provider_id/)
			? ''
			: '&amp;provider_id=' + pId
		);
	location.href = u1;
}

//writes a standard maxbox
function writeMaxTableBox(pId, qid, title, link, size) {
	document.write('<div class="ptpImageContainer">'
	+ '<table border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle" class="ptpImageCell">'
	+ '<div style="text-align:center;">'
	+ '<a href="' + link + '">'
	+ '<img src="/perl/get_image?size=' + size + '&amp;provider_id='+pId+'&amp;ptp_photo_id='+qid+'" />'
	+ '</a></div></td></tr></table>'
	+ '<div>'
	+ '<div class="ptpThumbCaption">'
	+ '<a href="' + link + '">' + title + '</a>'
	+ '</div>'
	+ '</div>'
	+ '</div>');
}

//flops qty box to text box
function swapQtyBox(inId) {
	var sel = document.getElementById("ptpQtySelect_" + inId);
	var v = parseInt(sel.options[sel.selectedIndex].value);
	//ignore non-numeric cases
	if (v >= 0) {
		//remember value anyway
		document.getElementById("ptpQtyValue_" + inId).value = v;
		return;
	}

	setQtyBox(inId, -v);
}
function setQtySelect(inId, v) {
	var sel = document.getElementById("ptpQtySelect_" + inId);
	for (var i = 0; i < sel.options.length; i++) {
		var opt = sel.options[i];
		if (opt.value == v) {
			opt.selected = true;
			sel.selectedIndex = i;
			break;
		}
	}
	document.getElementById("ptpQtyValue_" + inId).value = v;
}

function setQtyBox(inId, v) {
	//negative means more; go to box
	hide("ptpQtySelect_" + inId);
	document.getElementById("ptpQtySelect_" + inId).disabled = true;
	document.getElementById("ptpQtyValue_" + inId).value = v;
	show("ptpQtyValue_" + inId);
}

function checkPositiveInteger(fld, v) {
	var n = new Number(v);
	if (isNaN(n) || n <= 0 || n != parseInt(v)) {
		alert(fld + " must be a positive number.");
		return false;
	}
	return true;
}

function checkAndAdd(fld, v, prod) {
	if (!checkPositiveInteger(fld, v)) 
		return void(0);

	addProdToCart(prod,v);
}

//for full page section switch
function changeSectionType(sel, secSel) {

	var sections = sectionTypes[sel.options[sel.selectedIndex].value];
	//get rid of the old bring in the new
	secSel.options.length = 0;
	for(var i = 0; i < sections.length; i++) {
		secSel.options[i] = new Option(
				sections[i],
				sections[i],
				false,
				false
				);
	}
	//select first 
	secSel.selectedIndex = 0;
}

//add element grabber
document.getElementsByClassName = function(className) {
	var children = document.getElementsByTagName('*') || document.all;
	var elements = new Array();
	for (var i = 0; i < children.length; i++) {
		var child = children[i];
		var classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child);
				break;
			}
		}
	}
	return elements;
}


//special use by request page
function switchLicensePurpose(f, rName, d) {
	for (var i = 0; i < f.elements.length; i++) {
		if (f.elements[i].name != rName)
			continue;
		var el =  f.elements[i];
		if (!el.checked)
			continue;
		performLicenseSwitch(el.value, d);
		break;
	}
}

function performLicenseSwitch(value, d) {
	if (value == 'License') 
		show(d);
	else
		hide(d);
}

function clearSearch(el) {
	var val = el.value;
	 if(val == 'Search') {
		el.value = '';
	}
}
function resetSearch(el) {
	var val = el.value;
	if(val == '') {
		el.value = 'Search';
		return;
	}
}

function searchClear(fld, v) {
	if (!v) 
		v = 'Search'
	if (fld.value == v)
		fld.value = '';
}

function resetSearchFld(fld, v) {
	if (!v) 
		v = 'Search'
	if (fld.value == '')
		fld.value = v;
}

function subSearch(fName) {
	var f = document.forms[fName];
	if (f.name2) 
		f.name2.value = '';
	if (f.value2) 
		f.value2.value = '';
	f.submit();
	return true;
}

function subReSearch(fName,id) {
	var f = document.forms[fName];
	f.name2.value = 'gallery_id';
	f.value2.value = id;
	f.submit();
	return true;
}

function completeGiftIdeas() {
	var imRatio = giftIdeaImg.width/giftIdeaImg.height;

	var inx = 0;
	for (var i = 0; i < giftIdeas.products.length; i++) {
		var ok = false;
		for (j = 0; j < giftIdeas.productIds.length; j++) {
			if (giftIdeas.productIds[j] == giftIdeas.products[i].productId) {
				ok = true;
				break;
			}
		}
		if (!ok)
			continue;

		var param = giftIdeas.products[i].params;
		var imLayer = document.getElementById('giftIdea_' + (inx + 1));
		if (imLayer == null)
			break;
		var im = imLayer.getElementsByTagName('img')[0];
		//compute best fit
		var thisRatio = param.opening.width/param.opening.height > imRatio
				? param.opening.height/giftIdeaImg.height
				: param.opening.width/giftIdeaImg.width;
		//adjust by delta
		thisRatio *= giftIdeas.dim / param.width;
		im.src = giftIdeaImg.src;
		var w = Math.floor(giftIdeaImg.width * thisRatio);
		var h = Math.floor(giftIdeaImg.height * thisRatio);
		//and adjust locale
		move(imLayer,
				Math.floor((param.opening.width * (giftIdeas.dim / param.width) - w)/2),
				Math.floor((param.opening.height * (giftIdeas.dim / param.width) - h)/2),
				true);
		//and adjust image height & width
		im.width = w;
		im.height = h;

		inx++;
	}
}

function displayGiftIdeas(products, img, ptpPhotoId, contextQuerySet) {

	//check if no gifts available and hide div
	if (!products.length) {
		hide('giftIdeasDiv');
		return;
	}

	var s = '';
	if (giftIdeas.header) 
		s += '<div class="header">' + giftIdeas.header + '</div>';

	var inx = 0;
	show('giftIdeasDiv');
	giftIdeas.productIds = [];
	for (var row = 0; 
			inx < products.length
			&& (giftIdeas.rows == 0 || row < giftIdeas.rows); 
			row++) {
		s += '<div class="' + giftIdeas.rowClass + '">';
		for (var col = 0; 
				col < giftIdeas.cols && inx < products.length;
				col++) {
			if (giftIdeas.row != 0 
					&& (row == giftIdeas.rows - 1)
					&& (col == giftIdeas.cols - 1)
					&& document.getElementById('moreGiftLinkCell')) {
				s += '<div class="giftDesc">'
					+ '<a href="' + giftIdeas.baseMoreGiftLink + ptpPhotoId + contextQuerySet + '">'
					+ document.getElementById('moreGiftLinkCell').innerHTML
					+ '</a>'
					+ '</div>';
				continue;
			}
				
			var product = products[inx];
			giftIdeas.productIds.push(product.productId);
			inx++;
			var ratio =  giftIdeas.dim / product.params.width;
			s += '<div class="giftDesc">'
					+ '<div class="giftImg" style="position:absolute">'
					+ '<div id="giftIdea_' + inx + '"'
					+ ' style="position:absolute;'
					+ 'left:' + (ratio * product.params.opening.xOffset) + 'px;'
					+ 'top:' + (ratio * product.params.opening.yOffset) + 'px;'
					+ 'display:block;z-index:2;">'
					+ '<img style="border:0;" width="1" height="1"'
					+ ' src="/images/spacer.gif"/>'
					+ '</div>'
					+ (needsPngDiv() && product.params.imageMaskUrl.match(/\.png$/) != null
						? '<div style="position:relative;left:0;top:0px;z-index:3;'
							+ 'width:' + giftIdeas.dim + 'px;'
							+ 'height:' + (ratio * product.params.height) + 'px;'
							+ 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''
							+ product.params.imageMaskUrl + '\', sizingMethod=\'scale\');z-index:3;"><!-- --></div>'
						: '<img style="position:absolute;left:0;top:0;border:0;z-index:3"'
							+ ' width="' + giftIdeas.dim + '"'
							+ ' height="' + (ratio * product.params.height) + '"'
							+ ' src="' + product.params.imageMaskUrl + '"/>'
					)
					+ '</div>'
					+ '<div class="title">' + product.ideaTitle + '</div>'
					+ '<div class="select">'
					+ '<a href="' 
					+ (giftIdeas.asLayer
						? 'javascript:setGiftId(\'gift\',\'' 
						+ product.productId + '\');'
						: giftIdeas.baseGiftLink 
					+ '&ptp_photo_id=' + ptpPhotoId  
					+ '&product_id=' + product.productId + contextQuerySet 
						)
					+ '">'
					+ '<img src="/images/spacer.gif" width="113" height="36" border="0" />'
					+ '</a>'
					+ '</div>'
					+ '</div>';
		}
		s += '</div>';
	}

	document.getElementById('giftIdeasDiv').innerHTML = s;

	//and possibly set image
	if (img != null)
		giftIdeaImg = img;

	//setTimeout("displayGiftImg()",3);
	displayGiftImg();
}

function displayGiftImg() {
	if (giftIdeaImg.complete) {
		completeGiftIdeas();
		return;
	}
	setTimeout("displayGiftImg()",3);
}

				
//magic for ie print without dialog box
function printit(){
	if (0 && window.print) {
		window.print() ;
	} else if (document.all) {
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box
		WebBrowser1.outerHTML = "";
	}
}











