//Do we have prototype?
if (typeof($) != 'function')
	document.write('<script src="/javascripts/prototype.js" type="text/javascript"></script>');

//init globals...
MACIE5 = false;

var firstpictureonpage = ( typeof(firstpictureonpage) != 'undefined' ? firstpictureonpage : 0 );
//if (typeof(pshown) == 'undefined')
//	pshown = 0;
var snum = ( snum ? snum : 0 );
var tset = ( tset ? tset : 'on' );
var showstartnumber_trap = 0;
var currentlbname; 
var currentlblist;
var feat_requestview;
var typeoflbaction;
var sphotog;
var pre_q_args;
var winW;
var baseurl;
var carnit = 1; //flag to do once on load for cartview
//
gloCrop = '';
//
var currentLbdivMode; 	//when flipping between lb and cart, set this	
			//to say, "lightbox" or "cart" so that global refreshes in
			//subs like checkpageresize will know whether to draw
			//lb or cart or whatever else... 
currentLayer1Mode = (document.currentLayer1Mode ? currentLayer1Mode : 'searchresults');
document.currentLayer1Mode = currentLayer1Mode;
//enlarge shouldn't travel
if( document.currentLayer1Mode == 'enlarge' )
{
	document.currentLayer1Mode = 'searchresults';
        currentLayer1Mode = 'searchresults';
}
									//same thing but for the status of what is in Layer1 values are 
									//"searchresults", "cartview", or "enlarge" defaults to 
									//searchresults, as that is default page action 
var cartview = (cartview ? cartview : ''); //trip this flag to display cart in main window and draw cart in lightbox
var enlargeview = (enlargeview ? enlargeview : '');
var viewmode = ( (typeof(viewmode)!='undefined') ? viewmode : '' );

var lightbox_built = 0; //basically this is a check so when polllb comes around, if lightbox_built is 0 
			//and we're logged in, try and build the box!
currMousedOverObj = '';
// lbtosave = 0;
suspendpreviews=0;
scr='';

var d = new Date();
var currentYear = d.getFullYear();
document.currentlbstash = '';
if (typeof(dynimagesname) == 'undefined')
dynimagesname	='dyn_images';

if (typeof(Event) != 'undefined' && typeof(Event.observe) == 'function')
{
	//parse all commandline params into urlParams object, onload
	Event.observe(window, 'load', getVars);
	//set autosave cleanup
	Event.observe(window, 'load', function() {
        	if (EAD('share_control_sphotog'))
                	nextlink += 'site='+$F('share_control_sphotog')+'&';
        	if (EAD('share_control_status'))
                	nextlink += 'status_view='+$F('share_control_status')+'&';
		if (EAD('share_control_view'))
                	nextlink += 'view='+$F('share_control_view')+'&';
                if (EAD('share_control_release'))
                        nextlink += 'release_view='+$F('share_control_release')+'&';
	});
}


//-------------------------------
//begin page check for UA type...

var agt=navigator.userAgent;
var yourOS="PC";
if (agt.indexOf("Mac")!=-1)
   {yourOS='Mac';}
var yourBrowse="IE";
if (navigator.appName == 'Netscape')
   {yourBrowse="NS";}
if (navigator.appVersion.substr(22,1) >= "5")
{ver5="Yes";}

var now = new Date();
gfixDate(now);
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
var bad;

lbexpansionspace=0;
var pmousedelta=[20,-30]; //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
//cache loading img:
var loadImg = new Image();
loadImg.src = '/graphics/loading.png';

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
        browser = "Konqueror";
        OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari";
else if (checkIt('omniweb')) browser = "OmniWeb";
else if (checkIt('firefox')) browser = "Firefox";
else if (checkIt('opera')) browser = "Opera";
else if (checkIt('msie')) browser = "Internet Explorer";
else if (!checkIt('compatible'))
{
        browser = "Netscape Navigator";
        version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

var getpost = 'POST'; //had reports of IE caching ajax calls with a GET and firefox not able to complete fake POSTS, so..
if (browser == 'Firefox') // && parseInt(version) < 2)
	getpost = 'GET';
var pngsupport = 1;
if (browser == 'Internet Explorer' && parseInt(version) < 7)
	pngsupport = 0;

if (!OS)
{
        if (checkIt('linux')) OS = "Linux";
        else if (checkIt('x11')) OS = "Unix";
        else if (checkIt('mac')) OS = "Mac";
        else if (checkIt('win')) OS = "Windows";
        else OS = "an unknown operating system";
};

//-------------------------------
//setstyle
if((yourOS=="Mac" && yourBrowse=="NS")||(yourOS=="Mac" && yourBrowse=="IE" && ver5 != "Yes")){
        document.write('<LINK rel="stylesheet" href="/css/main2.css" type="text/css">');
}
else{
        document.write('<LINK rel="stylesheet" href="/css/main2.css" type="text/css">');
};

if (yourBrowse == "IE" || browser == "Internet Explorer")
{
	document.write('<LINK rel="stylesheet" href="/css/fixed4ie.css" type="text/css">');
};


//checking for login status
gsession = ggetCookie("gmpsess");
gusert = ggetCookie("usert");
gcartimages = ggetCookie("gcartimages");
gusername = ggetCookie("username");
gcurrency = ggetCookie("currency");
gfirstname = ggetCookie("firstname");

//
//	NON SEARCH PAGES 
//

if (typeof(scriptname) !="undefined"){
	//establish some init properties

	viewmode = ( viewmode || ggetCookie('gviewmode') );
	pixperpage=12;

	//initialize some page variables
	grange="legal";
	winW = 700;
	winH = 460;
	area = 12;
	resized=0;
	c=-1;
	fmstartnumber = 0;

	overflowtype = 'hidden';
	if ((agt.indexOf("Mac")!=-1) && (navigator.appName.indexOf("Microsoft")!=-1)){ 
		overflowtype = 'hidden';
	MACIE5=true;
	} else {
		MACIE5=false;
	}

	//optional configurations for this page varies from site to site
	optimizemenu = 0;
	showphotographer = 1;
	showrelease = 1;
	showfilesize = 1;
	showcaptionview = 1;

	nextlink=String(scriptname + "?" +
				(color ? "&color=" + color : '' ) + 
				( orient ? "&orient=" + orient : '' ) + 
				(spec_idx ? "&spec_idx=" + spec_idx : '' ) + 
				(sort ? "&sort=" + sort : '') + 
				(date ? "&date=" + date : '' ) + 
				(searchinclude ? "&searchinclude=" + searchinclude : '') + 
				((typeof(vcdbrowse) != 'undefined' && vcdbrowse) ? '&VCDBrowse='+vcdbrowse : '' )
			) ;

	if(typeof(q_args) != 'undefined' && q_args.match(/lb_view=1/)) //if viewing lightbox, nextlink is different
	{
		nextlink += '&n=1&lb_view=1';
	}
	else if(typeof(q_args) != 'undefined' && q_args.match(/rid=/)) //if viewing requests, nextlink is also different
	{
		var rid = q_args.match(/rid=([^\&]+)/);
		if(rid[1])
			nextlink += '&n=1&rid='+rid[1];
	}
	else if(typeof(q_args) != 'undefined' && q_args.match(/fn=/))
	{
		var fid = q_args.match(/fn=([^\&]+)/);
		if(fid[1])
                        nextlink += '&n=1&fn='+fid[1];
	}

	narrowurl = nextlink + "&snum=0";

	if(typeof(pre_q_args) != 'undefined') //append VMO= info for nextlinks on lightboxes
	{
		var vmo_arg = pre_q_args.match(/vmo=([^&]+)/);
		if (vmo_arg && vmo_arg[1])
			nextlink += '&vmo='+escape(vmo_arg[1]);
	}

	nextlink +=  "&method=" + method  + "&q_id=" + q_id + "&" + ucats;

	if (enlargeview)
		setTimeout("enlarge2('"+enlargeview+"', 0)", 500);
};


if(typeof(gsession) != 'undefined' && gsession){

	if (cartview)
	{
		document.currentLbdivMode = 'cart';	
		document.currentLayer1Mode = 'cartview';
		currMousedOverObj = 'shop_cart';
	}
	
	if ( (typeof(pagetype) != 'undefined' && pagetype=='lb') || (typeof(pre_q_args) != 'undefined' && ( pre_q_args.match(/lb_view=1/) || pre_q_args.match(/fn=/) )) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/lb_view=1/) )) )
	{
		pagetype='lb';
		gsetCookie('gwhichstartpage', '', '', '/', gGetCookieDom());
	}
	
}
else if (cartview)
{
	top.location="/bin/Cklb?ref=/SwishSearch?cartview=1";
};

tempW =  winW;

if (feat_requestview)
{
	document.thisIsFeatureView = true;
};

var lbdisplaymode = ggetCookie('ghidelightbox');
if (typeof(pagetype) != "undefined"){
	Event.observe(window, 'load', currentpage);
	Event.observe(window, 'resize', checkpageresize);
	Event.observe(window, 'click', hp);
};



var nodeTree;
if( typeof(Builder) != 'undefined' )
{
	nodeTree = $H({
	cart_build_act__buttons: 
		Builder.node('a', {href:'#',onclick:'lightbox_change(); return false;', title:'SWITCH TO YOUR LIGHTBOX'},[
				Builder.node('img', {src:'/graphics/cart_enabled_02.gif', border:0, width:127, height:18, hspace:0, vspace:0})	
			]),
	cart_build_act__actions:  Builder.node('span', {}, [
			Builder.node('a', {href:'#', onclick:'cart_display(); return false;', className:'lblink', style:'text-decoration:none; cursor:pointer;'}, 'View Cart and Calculate Usage Fees'),
			' | ',
			Builder.node('a', {href:'#', onclick:'cart_check(); return false;', className:'lblink', style:'text-decoration:none; cursor:pointer;'}, 'Checkout'),
			( document.thisIsFeatureView ? ' | ' : '' ),
			( document.thisIsFeatureView ?
						Builder.node('a', {href:'#', className:'lblink', onclick:'$("LBdiv").style.visibility = "hidden"', style:'cursor:pointer;'}, '[x] Hide Cart') 
					:
					''
			)
	])
	});
}
						



//******************************* SUBFUNCTIONS ****************************//


function maxscreen(){
        window.moveTo(0,0);
        window.resizeTo(screen.availWidth,screen.availHeight);
	if (self.location)
		self.location.href=self.location.href;
};

function price_image(pid,ttype){
	if (! pid || ! pid.match(/^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]?$/))  //did this longhand (instead of w/ curly brackets) b/c
		return false;							   //it screws up the compressors otherwise

	//get image info to retrieve pricing tier
	var url = '/AjaxHandlers/ImageInfo/'+ pid + '.json';
	ajax_JSON( url, 'POST', null ); 

	price_image_act(pid, 0, 0);
	return false;
};

function price_image_act(pid, tryCtr, force){
	if ( document.ajaxLoaded || force )
	{
		var supst = ( document.JSONobj.getImgDat('tier') || '' );
		launchwin('/bin/Rates?ln='+pid+'&calc_only=1&supst='+supst);	
	}
	else if ( tryCtr < 5 ) 
	{
		tryCtr++;
		setTimeout("price_image_act('"+pid+"','"+tryCtr+"', 0 )", 500);
	}
	else // nothing loaded, pop the page w/ missing data..
	{
		tryCtr++;
		price_image_act(pid,tryCtr,1);
	}
	return;
};

function center_panel(x,y,thehtml,tp){ // sub to center a panel and write the passed html with optional flag for search exp.
		if (typeof(winH) == 'undefined')
			setuppagesize();

        	var yoff = ( typeof(popupYoffset) != 'undefined' ) ? popupYoffset : 0;

        	if ((winW - x) < 0){
        	        panelx = 0;
        	} else {
        	        panelx = parseInt((winW - x)/2); // center it
        	}
        	if ((winH - y) < 0){
        	        panely = 41;
        	} else {
        	        panely = parseInt((winH - y)/2); //center it
        	}
		if(tp){
			var tx = Position.cumulativeOffset($('scontainer'));
			var ty = Position.cumulativeOffset($('row2'));
			panelx = tx[0];
			panely = ty[1];
		}
		createDisplayPanel();
		createCoverLayer();
		$('displaypanellayer').style.top = ( panely + yoff ) + 'px';
		$('displaypanellayer').style.left = panelx + 'px';
		$('displaypanellayer').style.width =x + 'px';
		$('displaypanellayer').style.height =y + 'px';
		$('coverlayer').style.visibility="visible";
		$('displaypanellayer').style.visibility="hidden";
		new Effect.Appear('coverlayer', {duration: 0.3, from:0, to: 0.7 });
	    $('displaypanellayer').innerHTML = thehtml;
	    setTimeout("displaypanelshow();",320);
};

function lightbox_new(){ // show the panel to create a new lightbox
	center_panel(290,200,Templates.lightbox_new__body.evaluate());
};

function test_valid_name(v){ // validator for new lightbox names
	if(v.match(/[^A-Za-z0-9 \-_]/)){//if it matches NOT the good chars
		alert("Lightbox names may only contain letters, numbers, spaces, hyphens, and underscores.");
	        return false;
	} else {
		return true;
	}
};

function lightbox_new_send(){ // URL call to make the LB in the database 
	var lbn = '';
	if ($('lightbox_new_name'))
		lbn = $F('lightbox_new_name');	

	if( lbn.length ==0 || lbn.length > 100){
		 alert('Lightbox names must be between 1 and 100 characters long.');
		if (lbn)
			lbn='';
	} else {
		if(test_valid_name(lbn)){
			polllb();
			var lbs = make_lightbox_string(gusername,lbn,[{id:1}]);
			currentlbname = lbn;  //must set this to let mod_act know focus has changed
			simplemessage('creating your lightbox ' + lbn + ' <blink>.</blink>', '', 'LB');
			ajax_JSON('/AjaxHandlers/LightboxNew/' + lbs + '.json', getpost, null);
		} 
	}
};

function lightbox_email_send(){ // URL call to send lightbox by email
	var theurl='/bin/Mail';

	var prams = 'ot=2&dsm=1&to_email=' + $('to_email').value + '&mail_text=' + escape($('mail_text').value);
	if($('allow_hrdl') && $('allow_hrdl').checked == true){ prams += (typeof(emaillburladd) != 'undefined' ? emaillburladd : ''); };

	if($('bill_to_customer') && $('bill_to_customer').value.toString().length > 0)
		prams += '&customer_id='+$('bill_to_customer').value;

	if($('email_project') && $('email_project').value.toString().length > 0)
		prams += '&project='+$('email_project').value;

	if($('email_notes') && $('email_notes').value.toString().length > 0)
		prams += '&notes='+$('email_notes').value;
	
	if($('notify').checked == true){ prams +='&notify=1'}; 
	if($('readonly').checked == true){ prams +='&readonly=1'}; 
	ajax_TEXT(theurl+'?'+prams, 'GET');//fire and forget the call to actually make the send...
	simplemessage('Sending your lightbox ' + ' <blink>.</blink>',0);
};

//call this after any ajax lightbox call..
//to wait on response and build the new box from it
function lightbox_mod_act (cruft){ 
	//console.log( currentLbdivMode );
	if ( currentLbdivMode == 'cart' )
		return false;
			
	var dover = 0;  
	if ( document.JSONobj && document.JSONobj.getLbDat('lbname') ) //otherwise  try again...
	{	
		var currentlb = document.JSONobj.getLbDat('lbname');
		if (currentlbname == currentlb || ! currentlbname)
		{
			hidedisplaypanel(1);
			var lbarray = document.JSONobj.getLbDat('lblist');
			//KEY: still using globals here for this.. (current active lb) although it gets passed first
			var lbl = document.JSONobj.getLbDat('lbnamelist');
			if (typeof(lbarray) != 'array' && typeof(lbarray) != 'object' || ! lbarray.length )
			{
				lbarray = new Array(1);
				lbarray[0] = { id:'1', rfcd: '' };
			}

			document.currentlbstash = lbarray;
			currentlbname = currentlb;	
			currentlblist = lbl;
			dover = 0;
			lightbox_build(lbarray, currentlb, '', lbl);
		}
		else
		{
			dover = 1;
		}
	}
	else
	{	
		dover = 1;
	}

	//people change lightboxes fast, so if you get an OBJ back, but it's not the one you want, 
	//or you got no OBJ at all then start over
	if (dover)
		setTimeout("lightbox_mod_act()", 500);
};

function simplemessage(m,mode,trg){ // Shows transition messages to the LB frame or centered based on param input
	if(trg && $('LBdiv')){
		$('LBdiv').style.height = '100px';
		$('LBdiv').innerHTML = Templates.simplemessage__body_lightbox.evaluate({message: m});
	} else {
		createDisplayPanel();
		if($('displaypanellayer').style.left=='0px'){
			$('displaypanellayer').style.left=parseInt(winW - 200)/2 + 'px';
		}
		if($('displaypanellayer').style.top=='0px'){
			$('displaypanellayer').style.top=parseInt(winH - 100)/2 + 'px';
		}
		if($('displaypanellayer').style.visibility=='hidden'){
			$('displaypanellayer').style.visibility='visible';
		}
		$('displaypanellayer').innerHTML = Templates.simplemessage__body.evaluate({message: m});
	}
	if (!mode){setTimeout("hidedisplaypanel(1);",700);}
};

function lightbox_email(mode){ // control for lightbox email state messages and menu
	if(mode=='sent'){
		simplemessage('Lightbox Sent!' + '<blink>.</blink>');
	} else if(mode=='close'){
		hidedisplaypanel(1);
	} else {
		var tdata = {	emaillbaddhtml: (typeof(emaillbaddhtml) != 'undefined' ? emaillbaddhtml : ' '),
				currentlbname: currentlbname};
		center_panel(390,280,Templates.lightbox_email__body.evaluate(tdata));
	}
};

function cart_mod_act (tryCtr){ // just wrap calls to redraw cart once the response is there... for any asynch cart actions
	tryCtr++;
	if ( ! document.JSONobj && ! document.TEXTresp && tryCtr < 10)
	{
		setTimeout("cart_mod_act('"+tryCtr+"')", 500);
	} 
	else
	{
		hidedisplaypanel(1);
		cart_build();
		if (document.currentLayer1Mode == 'cartview') 	// if we're viewing expanded cart, and you modify the cart from the lower panel
			cart_display('view');			// then main layer should immed get redrawn to avoid confusion
	}
};

function cart_reprice (args) { //maybe you're sending a promo-code  ..  or something.. this call simply forces you  to reprice images in your cart

            if ( typeof(args) == 'undefined' )
            {
                args = $H({ callback: 'cart_mod_act(0)' });
            }
            else if ( args.callback && args.callback.toString().length > 1)  //allready passed a callback so append..
            {
                args.callback += ' cart_mod_act(0);';
            }
            else
            {
                args.callback  = 'cart_mod_act(0)';
            }

            ajax_JSON('/AjaxHandlers/CartReprice/all.json', 'POST', args);
};

function cart_addto(id,args){
	if (gsession)//logged in user
	{
	    if( document.JSONobj.getCartDat && typeof(args) == 'undefined' )
	    {
                for (var cti=0;cti<document.JSONobj.getCartDat('total');cti++)
                {
                        if ( id == document.JSONobj.getCartDat('image_id',cti) )
			{
//need to do reprice thing here?
                        	alert('That image is already in your Cart');
				return;
			}
		}
	    }

	    if ( typeof(args) == 'undefined' )
	    {
		args = $H({ callback: 'cart_mod_act(0)' });
	    }
	    else if ( args.callback && args.callback.toString().length > 1)  //allready passed a callback so append..
	    {
		args.callback += ' cart_mod_act(0);';
	    }
	    else
	    {
		args.callback  = 'cart_mod_act(0)';
	    }

	    document.TEXTresp = null;
	    simplemessage('Adding image to Shopping Cart <blink>.</blink>','','LB');
            if ( typeof(args) == 'object' && args.Size_opname ) //meaning RF pricing data was sent along..
            {
                Object.extend(args, {
                    calc_rate: 1
                });
            }
	    ajax_JSON('/AjaxHandlers/CartAdd/' + id + '.json', 'POST', args);
	    //cart_mod_act(-1);
	}
	else //not
	{
		window.location='/bin/Cklb?ref=/SwishSearch%3FKeywords%3D'+escape(ukeys)+'%26cartview%3D1&atct='+id;
	}
};

function cart_delete_license (id,args) { //to remove a particular usage/license from an image...
	//need id, usage, opt id(s)

	if (typeof(args) != 'object')
		return;

	simplemessage('Removing License from Image<blink>.</blink>','','LB');
	var pos_opts = $A(args.opts).join('|');
	//only if a join produces results w/ array arg..
	if (pos_opts.toString().length)
		args.opts = pos_opts;

	if ( args.callback && args.callback.toString().length > 1)  //allready passed a callback so append..
        {
            args.callback += ' cart_mod_act(0);';
        }
        else
        {
            args.callback  = 'cart_mod_act(0)';
        }


	ajax_JSON('/AjaxHandlers/CartDelLicense/'+ id + '.json', 'POST', args); 
	
}

function cart_delete_image(id) {
	simplemessage('Deleting image from Shopping Cart <blink>.</blink>','','LB');
	ajax_JSON('/AjaxHandlers/CartDel/' + id + '.json', 'POST', 'callback=cart_mod_act(0)');
};

function lightbox_add2cart(){ 
	simplemessage('Adding lightbox images to Shopping Cart <blink>.</blink>','','LB');
	ajax_JSON('/AjaxHandlers/CartLbAdd/0000000000.json', 'POST', 'callback=cart_mod_act(0)');
};

function lightbox_delete(){ 
	simplemessage('Deleting your current lightbox ' + currentlbname,'','LB');
	var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');	
        var lbs = make_lightbox_string(gusername,currentlbname);
	currentlbname='';  
        ajax_JSON('/AjaxHandlers/LightboxDelete/' + lbs + '.json', getpost, mobid);
};

function lightbox_rename(){
	var tdata = { currentlbname: currentlbname };
	center_panel(290,200, Templates.lightbox_rename__body.evaluate(tdata));
};

function lightbox_rename_send(){
	var loclbn = $F('lightbox_new_name');
	if( loclbn.length ==0 || loclbn.length > 100){
		 alert('Lightbox names must be between 1 and 100 characters long.');
		loclbn='';
	} else {
		if(test_valid_name(loclbn)){
			simplemessage('renaming your lightbox ' + loclbn + ' <blink>.</blink>','LB');
			var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');
	                var lbs = make_lightbox_string(gusername,currentlbname,loclbn);
		        ajax_JSON('/AjaxHandlers/LightboxRename/' + lbs + '.json', getpost, mobid);
			currentlbname = loclbn;
		} 
	}
};

function lightbox_change(newlb){
	currentLbdivMode="lightbox"; 
	cartview=""; 
	document.currentLbdivMode="lightbox"; 

	var lbs = '';
	if (typeof(newlb) != 'undefined' && newlb.toString().length > 0)
	{
		simplemessage('Changing to Lightbox: ' + newlb + '<blink>.</blink>','','LB');
		polllb();//make sure and save changes
		currentlbname=newlb;
		lbs = make_lightbox_string(gusername,newlb);
	}
	
        ajax_JSON('/AjaxHandlers/LightboxInfo/' + lbs + '.json', getpost, null);
};

function lightbox_addto(id) { // adding an image to the current lightbox

	if (gsession)
	{
		var clb_exists = ( typeof(document.currentlbstash) == 'object' ? 1 : 0 );
		var temp= ( clb_exists ? document.currentlbstash.pluck('id').join(" ") : '');
		if(temp.indexOf(id)>=0){
			alert('That image is already in your Lightbox');
		} else {
			if (! currentlbname)
				currentlbname = 'newlb';

			if (!document.currentlbstash.push)
				document.currentlbstash = new Array();

			document.currentlbstash.unshift({id: id, rfcd: ''});
	
			var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');
			var lbs = make_lightbox_string(gusername,currentlbname,id);
			ajax_JSON('/AjaxHandlers/LightboxAddTo/' + lbs + '.json', getpost, mobid);

			if(clb_exists)
				lightbox_build(document.currentlbstash);
		}
	}
	else //not
	{
		self.location='/bin/Cklb?ref=/SwishSearch%3F'+escape(pre_q_args)+'&atlb='+id;
	}

};

//deleting lightbox from exlarge view (as opposed to local lb).
function lightbox_delete_image_enl(locid,callback) {
	var targetlb;
	var loc_mobj = '';
	var owner = gusername;
	if(typeof(mobject_id) != 'undefined' && mobject_id != '') //always sent in as a page var by template on VMO links
	{
		var pargs = new Array;
		pargs = mobject_id.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);
		targetlb = pargs[3];
		owner = pargs[2];
		loc_mobj = mobject_id;
	}
	else if (typeof(pagetype) != 'undefined' && pagetype == 'lb' ) //viewing local lightbox
	{
		targetlb = dsplkys;//so needs to also update lower lb
	}
	else if(typeof(q_args) == 'undefined' || ! q_args.match(/rid=/)) //if viewing requests, don't die
	{
		return; //do nothing if we can't find the full id of the lightbox viewed
	}

	//ajax call to delete lb image directly, since it may or not be the user's lb.
	if (document.thisIsFeatureView && typeof(feat_requestview) != 'undefined' && feat_requestview.toString().length > 0) //features already have an ajax-y handler for this
	{
		ajax_JSON('/R?del_id='+locid+'&rid='+feat_requestview, 'GET', null);
	}
	else
	{
		ajax_TEXT('/bin/CreateLightbox?delid='+locid+'&vmo='+loc_mobj+'&uname='+owner+'&lbname='+targetlb, 'GET', null);
	}
	
	//for removing images from lightbox viewed in enlarge mode, which may, or may not be also viewed in the lower panel.
	for(var tt=0; tt < id.length; tt++) // if we're in lbview need to also splice the image out
	{					//the display arrays
		if(id[tt] == locid)
		{
			cs.splice(tt,1);
			fs.splice(tt,1);
			o.splice(tt,1);
			rm.splice(tt,1);
			id.splice(tt,1);
			st.splice(tt,1);
			hrdl.splice(tt,1);
			rel.splice(tt,1);
			sw.splice(tt,1);
			pho.splice(tt,1);
			scp.splice(tt,1);

			//buildimages(0,0); don't register the build, just dispatch

        		var section = $H({ showstart:showstartnumber_trap+1, snum:showstartnumber_trap, viewmode:'lb', buildmode:'', resized:'' }).toJSON();
        		dispatchAll(section);

		}
	}

	//need nameof this viewed lightbox to compare against currentlbname
	//to see if we need to update the lightbox tray too
	if(targetlb == currentlbname && (typeof(callback == 'undefined') || callback != 1 ))
		lightbox_delete_image(locid,1);

};

function lightbox_delete_image(locid,callback) {// removing an image locally and updating status to save ad periodical update
	var nlb = new Array();
	var targetlb = '';
	var targetowner = '';
	for(var temp=0;temp<document.currentlbstash.length;temp++){
		if(document.currentlbstash[temp].id == locid){
			var tolightbox_delete_image=temp;
			if(typeof(mobject_id) != 'undefined' && mobject_id != '') //always sent in as a page var by template on VMO links
			{
				var pargs = new Array;
				pargs = mobject_id.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);
				targetlb = pargs[3];
			}
			else if (typeof(pagetype) != 'undefined' && pagetype == 'lb' ) //viewing local lightbox
			{
				targetlb = dsplkys;//so needs to also update lower lb
			}

		}
		else
		{
			nlb.push(document.currentlbstash[temp]);
		}
	}

	document.currentlbstash = nlb;
	
	if(targetlb && targetlb != '' && targetlb == currentlbname && callback != 1 ) //need to refresh expanded view too if we're viewing expanded local lb
		lightbox_delete_image_enl(locid,1);

	if (typeof(document.currentlbstash) != 'undefined' && document.currentlbstash.length == 0) //kill the lightbox if it is empty
	{
		lightbox_delete();
	}
	else
	{
		var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');
		var lbs = make_lightbox_string(gusername,currentlbname,locid);
		ajax_JSON('/AjaxHandlers/LightboxDelFrom/' + lbs + '.json', getpost, mobid);
		lightbox_build(document.currentlbstash);
	}
};

function lightbox_build(tlba,lname,secr,lbl){ // major code to build the lightbox area
	if(cartview && carnit)
	{
		carnit = 0;
		document.currentlbstash=tlba;
		cart_build('changing');//preempt initial lightbox build if we've been asked to go direct to cart.
		//cart_display();
		return;
	}

	hidedisplaypanel(1)	// clears the message that was saying loading lightbox or any other transition messages

	//I got called but there is no lightbox data anywhere
	if(typeof(tlba) != 'object' && typeof(document.currentlbstash) == 'undefined') 
		return;
	else if(typeof(document.currentlbstash) == 'object' && typeof(tlba) != 'object' )
		tlba=document.currentlbstash;

	currentLbdivMode = 'lightbox';
	
	if(lname)  // called from the LBframe results routine otherwise, usually we don't need to change lb just rebuild it
		currentlbname=lname;
	
	if(lbl)
		currentlblist=lbl.split('|');
	
	if(secr)
		scr=secr; // secret auth tag passed from server to prevent from an open lightbox security vulnerability

	var lbdPos = Position.cumulativeOffset($('LBdiv'));
	var lbbgH = winH - lbdPos[1] - 18; //18 being height of lbbuttons	

	document.currentlbstash=tlba;
	
	if($('LBdiv'))
	{
		// acts as the root node.. logical analog to the dom object they'll be apended to
		var thehtmlElements = $A([]); 
	
		thehtmlElements.push(  
		Builder.node('div', {id:'lbbuttons', style:'padding: 0px; margin: 0px; height:16px; width: 127px; overflow:hidden;'},[
			Builder.node('a', {href:'', onclick:"cart_build('changing'); return false;", title:'SWITCH TO YOUR CART'},[
				Builder.node('img', {src:'/graphics/lightbox_enabled_02.gif', border:0, width:127, height:18, hspace:0, vspace:0})
			])
		])	
		);
		
		var thehtmlLinkList = $A([]);
		if ( currentlblist && currentlblist.length > 0)
		{
			var hasplaceholder = 0;
			$A(tlba).each( function(lbItem) { if(lbItem.id == 1) hasplaceholder = 1; });
			var displen = ( hasplaceholder ? ( tlba.length - 1 ) : tlba.length );
						
			thehtmlLinkList.push(
			Builder.node('b', {}, currentlbname + ' Lightbox'),
			'  (' + displen + ')  ',
			Builder.node('b', {}, 'Change to  ')
			);
	
			//build selects longhand.. IE bugs... of course
			var selFix = document.createElement('select');
			selFix.setAttribute('name','n');
			selFix.setAttribute('id','lightbox_menu');
			selFix.setAttribute('class','smallmenu');
			//double IEfix.. must set this programatically (implied eval w/ setAttribute fails in IE7)
			selFix.onchange = function () { lightbox_change(this.options[this.selectedIndex].value); };
			
			for(var i=0;i<currentlblist.length;i++){
				if (currentlblist[i] != '')
				{
					var theOpt;
					theOpt = document.createElement('option');
					theOpt.setAttribute('value', currentlblist[i]);
					theOpt.appendChild(document.createTextNode(currentlblist[i].substring(0,25) 
						+ (currentlblist[i].length > 25 ? '...' : '')));
	
					if(currentlblist[i]==currentlbname)
						theOpt.setAttribute('selected', 'selected');
	
					selFix.appendChild(theOpt);
				}
			}
	
			thehtmlLinkList.push(selFix);
		}
	
		var tlb1 = '';
		var tlb2 = '';
		var tlb3 = '';
		var tlb4 = '';
		var tlb5 = '';
		var tlb6 = '';
		var tlb7 = '';
		var tlb8 = '';
		var tlb9 = '';
		if(winW>832){
			tlb1 ='New Lightbox';
			tlb2 ='View Expanded Lightbox';
			tlb3 ='Email Lightbox';
			tlb4 ='Add Lightbox to Cart';
			tlb5 ='Delete Lightbox';
			tlb6 ='Rename Lightbox';
			tlb7 ='Make LB a Feature';
			tlb8 ='Copy LB to User';
			tlb9 ='Resort LB';
		} else {
			tlb1 ='New LB';
			tlb2 = 'View LB';
			tlb3 = 'Email LB';
			tlb4 = 'Add LB to Cart';
			tlb5 ='Delete LB';
			tlb6 ='Rename LB';
			tlb7 ='Make Feature';
			tlb8 ='Copy LB';
			tlb9 ='Sort';
		}
	
		thehtmlLinkList.push(
  		Builder.node( "a", { 'href': "", 'class': "lblink", 'onclick': "lightbox_new(); return false;" }, tlb1),
		' | ',
  		Builder.node( "a", { 'href': "", 'onclick':"var d = new Date(); d.setMinutes(d.getMinutes()+5); gsetCookie('gprewhichstartpage', showstartnumber_trap, d, '/', gGetCookieDom()); toplightboxrefresh(); return false;", 'class': "lblink"}, tlb2),
		' | ',
  		Builder.node( "a", { 'href': "", 'class': "lblink", 'onclick':"lightbox_email(); return false;"}, tlb3),
		' | ',
  		Builder.node( "a", { 'href': "", 'class': "lblink", 'onclick':"lightbox_add2cart(); return false;"}, tlb4),
		' | ',
  		Builder.node( "a", { 'href': "", 'class': "lblink", 'onclick':"lightbox_delete(); return false;"}, tlb5),
		' | ',
  		Builder.node( "a", { 'href': "", 'class': "lblink", 'onclick':"lightbox_rename(); return false;"}, tlb6) 	
		);
	
		if(typeof(makelightboxfeature) != 'undefined')
		{
			thehtmlLinkList.push(
   			' | ',
			Builder.node('a', {'href':'', 'class':'lblink', 'onclick':"launchwin('"+makelightboxfeature + currentlbname+"', 'make feature', 500, 400, 100, 100); return false;"}, tlb7)
			);
		}
	
		if(typeof(copylightboxtouser) != 'undefined')
		{
			thehtmlLinkList.push(
   			' | ',
			Builder.node('a', {href:'', 'class':'lblink', 'onclick':"launchwin('" + copylightboxtouser + "', 'copy_lightbox', 300, 300, 300, 400); return false;"},tlb8)
			);
		}

		if(typeof(enlargedlbsort) != 'undefined')
		{
                        thehtmlLinkList.push(
                        ' | ',
                        Builder.node('a', {href:'', 'class':'lblink', 'onclick':"if(pagetype=='lb') { center_panel(390,120, '<div style=\"background:#F7E6A9;height:120px;font-size:6pt;text-align:center;padding:20px 10px 0 10px;\"><br/><h1>Your display will be refreshed once you close the Lightbox Sort popup window.</h1></div>'); } launchwin('" + enlargedlbsort + currentlbname + "', 'resort_lightbox', 450, 750, 200, 300); return false;"},tlb9)
                        );

		}

//	        if (viewmode == 'editing')
//		{
			thehtmlLinkList.push(
			' | ',
       			Builder.node('a', {'href':'', 'class':"lblink", 'onclick':"showhideLB(); return false;", style:"cursor:pointer"},'[+|-]')
			);
//		}

		var lbdisplaymode_style = 'block';
	      	if ( lbdisplaymode && viewmode == 'editing')
	        {
	                lbdisplaymode_style = 'none';
	        }
		
		thehtmlElements.push( 
		Builder.node('div', {'id':'lblinks','class':'lbname lbscroll', 'style':'overflow: auto; overflow-y:hidden'},[
			Builder.node('nobr', {}, thehtmlLinkList)
		])
		);
		
		var thehtmlLightboxStrip = $A([]);
		
		var heightOfLbDiv = 30;
		if(tlba.length>0){

			if ( lbdisplaymode_style == 'block')
				heightOfLbDiv = 130;
			else if (lbdisplaymode_style == 'none')
				heightOfLbDiv = 40;

			var scrollins = 'hidden';
			var perrow = parseInt(winW / 79);
			var wishwidth = '100%';
			if ( perrow < tlba.length )
			{
				scrollins = 'scroll';
				wishwidth = 79 * tlba.length;
				wishwidth = wishwidth + 'px';
			}
	
			
			var tofit=50;
			if(truevertHeight < 340){vlim=25;} else if(truevertHeight < 450){vlim=35;} else {vlim=58;}
			for (lbi=0;lbi<tlba.length;lbi++){
				if (tlba[lbi].id == '')
					continue;
	
				lbid=tlba[lbi].id;
				
				if ((lbid == 1 && tlba.length < 2) || lbid != 1){ // hide image 1 from view unless new box...
					var lbLinkArgs = { 'className':'lblink', 'title':'Enlarge this image' };
					var lbImgLinkArgs = { 'id': 'dlb'+lbi+'s_lbi' };
                                        if (tlba[lbi].rfcd && tlba[lbi].rfcd.toString().length) //myid is in the info for the link, hence this is the cover image
					{
			                     	var pm = unescape(tlba[lbi].rfcd.toString()).match(/SwishSearch\?n\=1\&fn\=(.*)\&supst\=cd/);
        			             	if(pm != null)
						{
                                			var thisisacoverimage_feature = pm[1];
	                                                lbLinkArgs.href = '/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd';
       		                                        lbImgLinkArgs.href = '/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd';
						}
                                        } else {
                                                lbLinkArgs.href = '';
						lbLinkArgs['onclick'] = "hp(); enlarge2('" + lbid + "','" + lbi + "'); return false;";
                                                lbImgLinkArgs.href = '';
						lbImgLinkArgs.onclick = "if (suspendpreviews==0) { hp(); enlarge2('" + lbid + "', '" + lbi + "'); } return false;";
					}
					var theSlug = ( lbid != 1 ?
							Builder.node('div', {'style':'padding-left: 2px; padding-right: 2px; padding-bottom:6px;'},[
							Builder.node('a', {'onclick':"lightbox_delete_image('" + lbid + "'); return false;", className:'lblink', 'title':'Remove this image from the lightbox'},'X'),

       							Builder.node('a', lbLinkArgs,'+')
		       					])
						:
				       			''
					);

					thehtmlLightboxStrip.push(
					Builder.node('div', {'id':'dlb_'+lbi, 'name':'dlb_'+lbi, 'style':'float:left; height:' + (tofit + 18) + 'px; overflow:hidden', 'align':'center'}, [
						Builder.node('a', lbImgLinkArgs,[
							Builder.node('img', {'id':'dlb_'+lbid, 'onmouseover':"prloadimg('"+lbid+"'); pmousedelta[1] = -180; sp(this, '" + lbid + "', '" + lbi +  "','" + tset + "');", onmouseout:"hp(); pmousedelta[1] = -30;", 'src':'http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + lbid + '.JPG', border:0, height:tofit, className:'lbimg', 'hspace':2})
						]),
						Builder.node('br'),
      						theSlug
					])
					);
				}
			}
		}
		else if (currentlbname)
		{
			thehtmlLightboxStrip.push(
			Builder.node('div', {'id':'dlb_0', 'name':'dlb_0', 'style':'float:left; height:' + (tofit + 18) + 'px; overflow:hidden;', 'align':'center'},[
				Builder.node('a',{'href':'', 'onclick':'return false;', 'id':'dlb0s_lbi', 'onmouseover':"prloadimg('1'); sp(this, '1', '0','" + tset + "');", 'onmouseout':"hp();"},[
					Builder.node('img', {'src':'http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/1.JPG', border:0, height:tofit, className:'lbimg', 'hspace':2})
				])
			])
			);
		}
		
		thehtmlElements.push(
		Builder.node('div', {'class':'lbscroll', 'style':'position: relative; overflow:'+scrollins+'; overflow-y:hidden; height:'+(heightOfLbDiv-50)+'px;'},[ 
				Builder.node('div', {'id':'LBimgdiv', 'style':'position:absolute; left:0; top:0; padding: 1px 0 0 0; height:'+(heightOfLbDiv-30)+'px; width:'+wishwidth+'; display:'+lbdisplaymode_style+';'},[
				thehtmlLightboxStrip
			])	
		])
		);
 
		//write the lb to the div
		$('LBdiv').replace('<div id="LBdiv"></div>');
		$('LBdiv').innerHTML = '';
		$('LBdiv').style.height = heightOfLbDiv+'px';


		thehtmlElements.each(function(domer){
			$('LBdiv').appendChild(domer);	
		});

                if ( lbdisplaymode == 1 && viewmode == 'editing') //minimize
                        $('LBimgdiv').hidden = 1;

   		//Mini Sortable used to go here.  Moved to expanded sort.

    }

	lightbox_built = 1;
	return;
};

function showhideLB () {
        if($('LBimgdiv').hidden == 1) {
                $('LBimgdiv').style.display = 'block';

                $('LBdiv').style.height = '130px';

                $('LBimgdiv').hidden = 0 ;
                gsetCookie("ghidelightbox","", "", "/", gGetCookieDom());
        } else {
                $('LBimgdiv').style.display = 'none';
		
		var gh = $('Layer1').getHeight() + 200;
		$('Layer1').style.height = gh + 'px';
		alert($('Layer1').style.height);
                $('LBdiv').style.height = '40px';

                $('LBimgdiv').hidden = 1
                gsetCookie("ghidelightbox","1", "", "/", gGetCookieDom());
        }

        currentpage();
};

//ALL THIS DOES IS SAVE YOUR CURRENT LIGHTBOX
function polllb(force, synch){ 
	var lbs = make_lightbox_string(gusername,currentlbname,(typeof(document.currentlbstash) != 'undefined' ? document.currentlbstash : 1));

	var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');

	var meths = getpost;
	if (typeof(document.currentlbstash) == 'object' && document.currentlbstash.length > 50)
	{
		var payload = document.currentlbstash.pluck('id').reverse().join('|');
		if (mobid)
			mobid+='&';
		mobid+= 'payload='+payload;
		meths = 'POST';
	}

	ajax_JSON('/AjaxHandlers/LightboxSave/' + lbs + '.json', meths, mobid );
};

//util function to prep lb save string
function make_lightbox_string(uname,lbname,lbarr) {
	//#lightbox_ownername|||lightboxname||id|id|id|id
	var newlba = '';
	if ( typeof(lbarr) == 'object' )
	{
		 newlba = lbarr.pluck('id');
	}
	else
	{
		newlba = [ lbarr ];
	}

	newlba = newlba.reverse();

	var newlb = newlba.join('|');

	if (newlb && newlb.length > 500) //failsafe
		newlb = '';

	var lb_string = uname + '|||' + lbname + ( newlb ? '||' + newlb : '');
	return lb_string;
};

function make_share_control_string(id,value) {

	if ( typeof id === 'object' && id.length )
		id = id.join('|');

	var sc_string = id + '|||' + value;
	return sc_string;
};

function cart_away() { //leave site for universal checkout
        top.location = "/bin/Cart?op=ckout";
};

function cart_check(){ //verifys all items in current cart are priced
	simplemessage('<a style="cursor:pointer; text-decoration:underline;" title="click here if you find you are waiting too long to load." onclick="cart_check();">Tabulating Shopping Cart <blink>.</blink> </a>','','LB');
	ajax_JSON( '/AjaxHandlers/CartInfo/open.json', 'POST', { 'callback': "cart_check_act(); cart_display();" } );
	//cart_check_act(0);
};

function cart_check_act(){
	if( document.JSONobj && typeof(document.JSONobj.getCartDat) == 'function')
	{
		var cart_good = 1;

		if(document.JSONobj.getCartDat('total') > 0){
			for (cti=0; cti < document.JSONobj.getCartDat('total'); cti++)
			{
				if(document.JSONobj.getCartDat('price',cti))
				{
					if(!( document.JSONobj.getCartDat('price',cti) != 'null' && document.JSONobj.getCartDat('price',cti) > 0)) 
						cart_good = 0;
				}
				else
				{
					cart_good = 0;
				}
			}
		}
		else
		{
			cart_good = 0;
		}

		if (cart_good == 1)
		{
			cart_away();	
		}
		else
		{
			alert("There are unlicensed images in your cart, or it is empty.  To license image(s) first click the 'specify usage and calculate fee' link for each image in your cart and use the Rate calculator. Rates vary based on usage.");
			topcartrefresh();
		}		
	};
};

function cart_display (flip) { // call to load shopcart display into Layer1
	if ( document.cart_display_lock )
		return;
        var section = $H({ showstart:'cartview', snum:firstpictureonpage, viewmode:'cartview', flp:flip }).toJSON();
	//make the call through the YAHOO registry.
	if (flip)
	{
		dispatchAll(section);
	}
	else
	{
        	try { YAHOO.util.History.navigate("nav", section); } catch (e) { dispatchAll(section); }
	}

};


function dispatchCart_display ( args ) {
        if ( typeof(args) != 'object' )
                return;

	var flip = args['flp'];

	document.cart_display_lock = 1; // it's pretty much incidental which functions should loop and which should never run concurrently
					// this is one where it hurts to spawm so many loads of itself...
	document.currentLayer1Mode = 'cartview';

        if($('cdheader'))
               $('cdheader').style.display = 'none';


	if(!flip)
		flip='view';

		ajax_HTML('Layer1', '/bin/Cart?op='+flip, 'GET');
		$('Layer1').style.height = truevertHeight + 'px';
		$('Layer1').style.overflow = 'scroll';
		$('Layer1').style.overflowX = 'hidden';
		if($('pagingrow') && document.currentLayer1Mode != 'searchresults')
	                $('pagingrow').innerHTML = '';

	document.cart_display_lock = 0;
};

function cart_build(mode) { //wrapper for asynch calls to cart data
	currentLbdivMode = 'cart';
	$('LBdiv').style.height = '130px';
	if(mode == 'changing'){
		simplemessage('<a style="cursor:pointer; text-decoration:underline;" title="click here if you find you are waiting too long to load." onclick="cart_build(\'changing_again\');"> Loading Shopping Cart <blink>.</blink></a>','','LB');
	}
 	ajax_JSON( '/AjaxHandlers/CartInfo/open.json', getpost, 'callback=cart_build_act()' ); 

	currMousedOverObj = 'shop_cart';
};

function cart_build_act(){
	if(! $('LBdiv'))
		return;
	
	if ( ! isNaN(document.JSONobj.getCartDat('total')) ) 
	{
		
		hidedisplaypanel(1)	// clears the message that was saying loading lightbox or any other transition messages
		
		var cartRoot = $A([]); //aka LBdiv
		
		var cartTotal = document.JSONobj.getCartDat('total');
				
		cartRoot.push(
		Builder.node('div', {id:'lbbuttons', style:'padding:0px; margin:0px; width:127px; height:16px; overflow:hidden'}, [
			nodeTree.cart_build_act__buttons,
			]),
		Builder.node('div', { className:'lbname', style:'padding:3px 0px 0px 3px; margin:0px;'},[
			Builder.node('b', {}, 'Shopping Cart  '+( cartTotal ? cartTotal : 0 ) + ' images '),
			nodeTree.cart_build_act__actions,
		]));

		
		if(document.JSONobj.getCartDat('total')>0){
			
			var tofit = parseInt((winW*0.65)/document.JSONobj.getCartDat('total'));
			if(winH < 340){vlim=25;} else if(winH < 450){vlim=35;} else {vlim=58;}
			if(tofit> vlim){
				tofit=vlim;
			} else if (tofit<18){
				tofit=18;
			}
			
			var cartimages = $A([]);
			for (cti=0;cti<document.JSONobj.getCartDat('total');cti++)
			{
				ctimid = document.JSONobj.getImgDat('id', cti);
				ctid = document.JSONobj.getCartDat('id',cti);				
				
				cartimages.push( Builder.node('div', { 	align:'center', id:'dct'+cti+'s', name:'dct'+cti+'s', valign:'bottom', style:'float:left; height:' + ( tofit + 18 ) + 'px; overflow:hidden;' },[
					Builder.node('a', {	href:'', onclick:'hp(); return false', id:'dct'+cti+'s_cti'},[
						Builder.node('img', { id:'ctimage_'+ctimid, onmouseover:'prloadimg("'+ctimid+'"); sp(this, "'+ctimid+'", "1", "'+tset+'");', onmouseout:'hp();', src: 'http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/'+ctimid+'.JPG', height: tofit, border: 0, className: 'lbimg', hspace: 2	} )
					]),
					Builder.node('div', { style:'padding:2px'}, [
						Builder.node('a', { href:'', onclick:'cart_delete_image("'+ctid+'"); return false;', className:'ctlink', title:'Remove this image from the cart'}, 'X')
					])
				]) );
				
			}
			
			cartRoot.push(
				Builder.node('div', {id:'LBimgdiv', style:'padding:6px 0 0 3px; height: 100%'}, [ cartimages, Builder.node('br', {style:'clear:both'}) ])
			);

			//set future cookie for remaining images in cart
			var date = new Date();
        		date.setTime(date.getTime()+(60*24*60*60*1000));
			gsetCookie('gcartimages',cti,date,'/',gGetCookieDom());
			
		}
		
		$('LBdiv').replace('<DIV id="LBdiv"></DIV>');
		cartRoot.each(function(carta){
			$('LBdiv').appendChild(carta);	
		});


		
	}
};	

function gfixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);   
};

function g() {
	if (typeof(g_custom) == 'function')
		g_custom();
	else
		g_standard();
};


function g_standard() {
	var url2 = $F('Keywords');
	var uname;
	if ( $('Username') )
		uname = $F('Username');  // for id of query in logs... to assoc with users
	pagetype = 'search';
	
	//SB>> search fix to preserve previous terms:
       	var prev_keys = '';
       	if(typeof(q_args) != 'undefined' && q_args)
       	{
               	prev_keys = q_args.match(/Keywords=(.*?)(\&|$)/);
		if(typeof(prev_keys) != 'undefined' && prev_keys && prev_keys.length > 1)
			prev_keys = prev_keys[1];
		else
			prev_keys = '';

               prev_keys = unescape(prev_keys);
       	}

       	if (url2.length<1 && prev_keys.length<1 && ! ( EAD('share_control_sphotog') || EAD('share_control_status') || EAD('share_control_view') || EAD('share_control_release') ) ){ //	if (url2.length<1){
		alert("You must first enter search criteria in the field next to the search button.");
	} else {
		if (prev_keys.length>0 && ( url2.length<1 || url2 == 'enter keywords') )
		{
			url2 = prev_keys;
                	$('Keywords').value = url2;
		}

		if ( (EAD('share_control_sphotog') || EAD('share_control_status') || EAD('share_control_view') || EAD('share_control_release') ) && url2 == 'enter keywords')
		url2 = '';

		var theurl = '';
		if ($('method') && typeof($('method').value) != 'undefined' && $('method').value=='within'){
			theurl= '/SwishSearch?Keywords=' + q_id + '&ex_keys=' + url2;
		} else {
			theurl= '/SwishSearch?Keywords=' + url2 ;
		}


		if($('displaypanel'))
		{


			if(typeof(suspendWithPeople) == 'undefined' && $('displaypanel').people)
			{	
				if ($('displaypanel').people[1].checked == true){
					theurl += '+haspeople';
				}
				if ($('displaypanel').people[2].checked == true){
					theurl += '+nobody';
				}
				if ($('displaypanel').people[3] && $('displaypanel').people[3].checked == true){
					theurl += '+hascrowd';
				}
			}

//custom a gen purpose that relies on value of form elem
//outline
			if ($('displaypanel').custom)
			{
				$A($('displaypanel').custom).each(function(itm) {
					theurl += '+'+itm.value;
				});
			}

			if ($('displaypanel').outline)
			{
				if ($('displaypanel').outline[0].checked == true) {
					theurl += '+outlinable';
				}
				else if ($('displaypanel').outline[1].checked == true) {
					theurl += '+not+outlinable';
				}
			}

			if(typeof(suspendYesNoRestrictons) == 'undefined' && $('displaypanel').restrictions)
			{
				if ($('displaypanel').restrictions[1].checked == true){
					theurl += '+NOT+imagehasrestrictions';
				}
			}


			if ($('displaypanel').xtrasql && $('displaypanel').xtrasql[1].checked == true){
				theurl += '&xtrasql=(releasedmodel+or+releasedproperty+or+releasednotapplicable+or+releasedmodelandproperty)';
			}
		
			var obypas = 1; //if all orient boxes are checked, include none of them...
			$A($('displaypanel').orient).each(function(itm) {
				if (! itm.checked ) { obypas = 0; }
			});
	

			if (! obypas)
			{
				if ($('displaypanel').orient[0].checked == true){
					theurl += '&orient=horizontal';
				}
				if ($('displaypanel').orient[1].checked == true){
					theurl += '&orient=vertical';
				}
				if ($('displaypanel').orient[2].checked == true){
					theurl += '&orient=panoramic';
				}
				if ($('displaypanel').orient[3].checked == true){
					theurl += '&orient=square';
				}
			}
	
			if($('displaypanel').rmrftype)
			{
				if ($('displaypanel').rmrftype[0].checked == true && $('displaypanel').rmrftype[1].checked == false){
					theurl += '&searchinclude=RM';
				}
				if ($('displaypanel').rmrftype[1].checked == true && $('displaypanel').rmrftype[0].checked == false){
					theurl += '&searchinclude=RF';
				}
			}

			if ( $('displaypanel').color )	
			{
			     if ($('displaypanel').color[1].checked == true){
				theurl += '&color=color';
			    }
			    if ($('displaypanel').color[2].checked == true){
				theurl += '&color=gray';
			    }
			}

			// conditional for Illustation agencies
                        if (typeof(showIllusPhotog) != 'undefined'){
                                if ($('displaypanel').searchinclude[0].checked == true && $('displaypanel').searchinclude[1].checked == false){
                                        theurl += '&searchinclude=illustration';
                                }
                                if ($('displaypanel').searchinclude[1].checked == true && $('displaypanel').searchinclude[0].checked == false){
                                        theurl += '&searchinclude=photography';
                                }
                        }

		}
		if($('spec_idx'))
		{
			if ($('spec_idx').selectedIndex==1){
				theurl += '&spec_idx=ed';
			}
			if ($('spec_idx').selectedIndex==2){
				theurl += '&spec_idx=ne';
			}
		}

		/* ! share control extra fields from filter header on left ! */
		if (EAD('share_control_sphotog'))
			theurl += '&site='+$F('share_control_sphotog');	
		if (EAD('share_control_status'))
			theurl += '&status_view='+$F('share_control_status');
	        if (EAD('share_control_view'))
        	        theurl += '&view='+$F('share_control_view');
                if (EAD('share_control_release'))
                        theurl += '&release_view='+$F('share_control_release');


		
		if (uname && uname != '')
			theurl += '&Username='+encodeURI(uname);


		gsetCookie("gwhichstartpage","", "", "/", gGetCookieDom());

		if (url2 != 'enter keywords') {
			coveroff();
			hidedisplaypanel(1);
			MM_setTextOfLayer('Layer1','','<TABLE width=100% height=100%><TR width=100% height=100%><TD valign=middle align=center width=100% height=100%><B><FONT class=header>Searching for ' + url2 + ' <blink>.</blink></font></B></TD></TR></TABLE>');
			self.location=theurl;

		} else {
			alert('You must first type in keywords to search for.');
			document.isn.Keywords.focus();
		}
	}
};

function gwhichindex(tset) {	
	gsetCookie("gwhichindex",tset, '', '/', gGetCookieDom());
};

function fsearchprefs(val,mode) {
	var gsearchprefs = ggetCookie('gsearchprefs');
	if(gsearchprefs){
	} else {
		gsearchprefs= new String(" ");
	}
	var buildpref = new String("");
		if(val == 'released' && mode == 'remove'){

		} else {
			if((gsearchprefs.indexOf('a')>=0) || (val == 'released' && mode == 'add')){
				buildpref+='a';
			}			
		}
		if(val == 'norestrictions' && mode == 'remove'){	
		} else {
			if((gsearchprefs.indexOf('b')>=0) || (val == 'norestrictions' && mode == 'add')){
				buildpref+='b';
			}
		}
		if(val == 'people' && mode == 'remove'){
		} else {

			if(((gsearchprefs.indexOf('c')>=0) && (val != 'withpeople') && (val != 'withcrowd'))  || (val == 'nobody' && mode == 'add')){
				buildpref+='c';
			} else if (((gsearchprefs.indexOf('d')>=0) && (val != 'withcrowd') ) || (val == 'withpeople' && mode == 'add')){
				buildpref+='d';
			} else if ((gsearchprefs.indexOf('e')>=0) || (val == 'withcrowd' && mode == 'add')){
				buildpref+='e';
			}
		}

		if (document.displaypanel.orient)
		{
		    if (document.displaypanel.orient[0] && document.displaypanel.orient[0].checked == true){
			buildpref+='f';
		    }
		    if (document.displaypanel.orient[1] && document.displaypanel.orient[1].checked == true){
			buildpref+='g';
		    }
		    if (document.displaypanel.orient[2] && document.displaypanel.orient[2].checked == true){
			buildpref+='h';
		    }
		    if (document.displaypanel.orient[3] && document.displaypanel.orient[3].checked == true){
			buildpref+='i';
		    }
		}

		if(typeof(rmonly) == 'undefined' && document.displaypanel.rmrftype)
		{
			if (document.displaypanel.rmrftype[0] && document.displaypanel.rmrftype[0].checked == true){
				buildpref+='j';
			}
			if (document.displaypanel.rmrftype[1] && document.displaypanel.rmrftype[1].checked == true){
				buildpref+='k';
			}
		}

		if (document.displaypanel.color)
		{
		    if (document.displaypanel.color[0].checked == true){
			buildpref+='m';
		    }
		    if (document.displaypanel.color[1].checked == true){
			buildpref+='n';
		    }
		    if (document.displaypanel.color[2].checked == true){
			buildpref+='o';
		    }
		}

                if (typeof(showIllusPhotog) != 'undefined'){ //if adding Illustration / Photography selector checkboxes
                        if(document.displaypanel.searchinclude[0].checked == true){
                                buildpref+='0';
                        }
                        if(document.displaypanel.searchinclude[1].checked == true){
                                buildpref+='1';
                        }
                }

		gsetCookie("gsearchprefs",buildpref, '', '/', gGetCookieDom());
};

function greleasedselect(tsetval) {
	gsetCookie("greleasestatus",tsetval, '', '/', gGetCookieDom());
};


////////////search functions only////////////

function htmlit(showid){

	// build html for each image depending on viewing mode
	
	var html='';
	switchpage = false;
	if (id[showid]){
		
		var myrmrftype = rm[showid];
		myid = id[showid];
		mysimilarto=st[showid];
		if (typeof(scp) != 'undefined' && (viewmode == 'list' || viewmode == 'editing') ) {myshortcaption=unescape(scp[showid]);} else {myshortcaption = "n/a";}
		var temp = true;
		var tempshortcaption='';
		var myreleased = '';

		if (! relcon[showid])
			myreleased = rel[showid];

		if (typeof(relcon) != 'undefined' && relcon[showid] && mysimilarto.length < 13) {  //share control style..
			var shortrel = myreleased; ///( $('gRelease'+showid) && $('gRelease'+showid).value ) ? $('gRelease'+showid).value : myreleased;
			shortrel = shortrel.substring(0,16) + (myreleased.length > 16 ? '...' : '');


			myreleased = '<div id="shortrel'+showid+'">Release: '+shortrel+'</div> <div>  <form id="releasecontrol'+showid+'" > ' + relcon[showid] + ' <input type="hidden" name="shdex" value="'+showid+'"/></form> <a href="" onclick="sor('+showid+'); return false;" >Save Release</a></div>';
		} 
		else if(showrelease){
			if(! ( myreleased == "MODEL RELEASED" || myreleased == "MODEL AND PROPERTY RELEASED" || myreleased == "PROPERTY RELEASED") ){
				myreleased = "Release: " + myreleased;
			}
			if (typeof(relcon) != 'undefined' && relcon[showid] && mysimilarto.length < 13)
				myreleased ='<br/>'+myreleased;

		} else { myreleased="";}
		//shorten long captions
		if(myshortcaption.length > 90){
			for(z=0; z < 130; z++){
				var c = myshortcaption.charAt(z);
				if(temp == true){
					if((z > 90) && (c == ".")){
						temp = false;
						tempshortcaption+=c + " ...";
					} else if((z > 110) && (c == " ")){
						temp = false;
						tempshortcaption+=" ...";
					} else {
						tempshortcaption+= c;
					}
				}
        		}
        		myshortcaption = tempshortcaption;
    		}
    		var thishassimilars = "yes";
		myphotographer=pho[showid];
		myrglobaldynf = rm[showid];
		myfilesize=fs[showid];
		var myhrdlink = hrdl[showid];

		var mysharestatuses = html_share_con_opts(showid);
		var mysiteweight = html_weight_con_opts(showid);
		var mycombinedcon = html_combined_con_opts(showid);

                var thisisacoverimage_feature = '';
                if(rfcd[showid].match(myid)) //myid is in the info for the link, hence this is the cover image
                {
                        var pm = unescape(rfcd[showid]).match(/SwishSearch\?n\=1\&fn\=(.*)\&supst\=cd/);
                        if(pm != null)
                                thisisacoverimage_feature = pm[1];
                }

		adminheight=0;
		if(myhrdlink){
                        if (viewmode != 'editing')
                                adminheight=11;
		} 
		if(myfilesize < 5){myfilesize='Scan on Demand';} //else {myfilesize+=" Mb";}
		if(myid.length > 9){
			if ( o[showid] ){displayid=o[showid];} else {displayid=myid;}	
                        if(viewmode == "editing"){
                                var theight = 160 + adminheight;

                                var sharesync = unescape(shsync[showid]);
                                sharesync=sharesync.split('|');
                                //so 0 is type, 1 is if it matchess
                                var shbg = 'white';
                                if (sharesync[0] == 'shared') {
                                        shbg = '#77BB33';
                                } else if (sharesync[0].toString().match(/notshared|rejected/)) {
                                        shbg = '#DF0000';
                                }
                                var shbdr = 'white';
                                if ( parseInt(sharesync[1]) )
                                {
                                        shbdr = 'orange';
                                }
                                if ( mysimilarto.length < 13){

                                        html += '<span id="cellwrapper'+myid+'" valign=bottom style="float:left;background-color:'+shbdr+'; padding:0 6px; 0 6px">';

                                        html += '<div id="d'+myid+'" align=center valign=bottom style=" background-color:'+shbg+'; width:288px; height:' + theight + 'px;">';
                                        html += '<TABLE width=298 cellspacing=2 cellpadding=0 border=0><TR><TD valign=top><div style="position:relative;height:160px;"><a href="javasc' + 'ript:enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\');"><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' +myid + '.JPG" border=0 class=pimg vspace=2 hspace=3';
                                        html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";html += '" onmouseout="hp();" id=' + myid + '>';

                                        html += '</a>';
					html += mycombinedcon + mysharestatuses;




                                        html += '</div></TD><TD valign="top"><font class=xsmall>ID:' + myid;
                                        if(typeof(suppressrmrftype) == 'undefined'){
                                                html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
                                        }
                                        html += '<DIV class=icons>';

                                        if ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) )
                                        {
                                                html+='<A href="javascript:lightbox_delete_image_enl(\'' + myid + '\');" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
                                        }

                                        html += '</DIV>';

                                        myphotographer = unescape(myphotographer);
                                        if (myphotographer.length > 18)
                                                myphotographer = myphotographer.substring(0,18) + '...';

                                        if(showphotographer == 1){html +='&copy; '+currentYear+' ' + myphotographer;}
                                        html += '  <nobr>';
                                        if(showfilesize){html += myfilesize;}

                                        html += '</nobr><br/>CAPTION: ' + myshortcaption+'<div>'+myreleased+'</div></font>';

                                        html += mysiteweight;

                                        if(myhrdlink)
                                                html += '<br/><NOBR><a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a></NOBR>';
                                        html += '<br/><a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';

                                        html += '</TD></TR></TABLE></DIV></span></SPAN>';
                                } else {

                                        html += '<span id="cellwrapper'+myid+'" valign=bottom style="float:left;background-color:'+shbdr+'; padding:0 6px; 0 6px;">';
                                        html += '<div id="d' + myid + '" align=center valign=bottom style=" background-color:'+shbg+'; width:288px; height:' + theight + 'px;">';
                                        html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','editing', myhrdlink, myreleased);
                                        html += '</DIV></span></SPAN>';
                                }

                        }
                        else if(viewmode == "list"){
				var theight = 172 + adminheight;
				if ( mysimilarto.length < 13){	
					
					html += '<span id="cellwrapper'+showid+'" valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:305px; height:' + theight + 'px;">';
					html += '<TABLE width=298 cellspacing=2 cellpadding=0 border0><TR><TD valign=top>';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" >';
                                        else
						html += '<a href="" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;">';

					html += '<img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + myid + '.JPG" border=0 class=pimg vspace=2 hspace=3';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";html += '" onmouseout="hp();" id=' + myid + '>';
					html += '</a><BR>';
					if(myhrdlink)
						html += '<center><a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a></center>';
					html += '</TD><TD valign="top"><font class=xsmall>ID:' + displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html += '<DIV class=icons>';

					if (  ! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )	
					{
						html+='<A href="" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature )
						html += '<a href="" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class=iconlink title="Enlarge image and more info"><font class=eye>i</font></a>';

					html += '</DIV>';
					
					if(showphotographer == 1){html +='<BR>&copy; '+currentYear+' ' + myphotographer;}
					html += '  <nobr>';
					if(showfilesize){html += myfilesize;}
					html += '</nobr><br/>CAPTION: ' + myshortcaption + '<div>'+myreleased+'</div></font>';


					html += '</TD></TR></TABLE></DIV></SPAN>';
				} else {	
			
	
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:305px; height:' + theight + 'px;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','list', myhrdlink, myreleased);
                                        //html += myhrdlink + '<br/>' + myreleased + mysharestatuses;

					html += '</DIV></SPAN>';
				}
				
			
			} else if (viewmode == "tiny"){
				//adminheight += 8;
				var theight = 100 + adminheight;
				if ( mysimilarto.length < 13){	
					
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:95px; height:' + theight + 'px; overflow: hidden;">';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"';

					if(document.page.previews.selectedIndex == 1){html +=' TITLE="ID:' + displayid;
						if(showphotographer == 1){html += '\r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: '+ myfilesize ;}
						html +=  ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src=http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + myid + '.JPG border=0 class=pimg vspace=1 hspace=1 height=55';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "', '" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
					
					//sp('','" + myid + "','" + myrglobaldynf + "','" + myphotographer + "','" + myid + "','" + showid + "')
					html += '</a><BR>';
					html += '<DIV class=icons>';

					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )
					{
						html+='<A href="" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="iconlinktiny" TITLE="Remove this image from the lightbox">X</A>';
					}


					html += '<a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlinktiny" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlinktiny" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlinktiny" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlinktiny" title="Enlarge image and more info"><font class=eye>i</font></a>';

					/*  if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}  */

					html += '</DIV>';
					html += '<DIV class=imidxxsmall>' + displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV>';

					if (myhrdlink)
						html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';
					html += '</DIV></SPAN>';

				} else {				
	
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:95px; height:' + theight + 'px; overflow:hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','tiny',myhrdlink,myreleased);		
					html += '</DIV></SPAN>';
				}
			
			
			} else if (viewmode == "med"){
				//adminheight += 4; // tweaking adminheight...
				var theight = 130 + adminheight;
				if ( mysimilarto.length < 13){	
				
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:140px; height:' + theight + 'px; overflow: hidden;">';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"';


					if(document.page.previews.selectedIndex == 1){html += ' TITLE="ID:' + displayid;
						if(showphotographer == 1){html += '  \r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: ' + myfilesize ;}
						html += ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src=http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + myid + '.JPG border=0 vspace=1 class=pimg hspace=1 height=80';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "', '" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
						//sp('','" + myid + "','" + myrglobaldynf + "','" + myphotographer + "','" + myid + "','" + showid + "')
					html += '</a><BR>';
					html += '<DIV class=icons>';

					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )
					{
						html+='<A href="" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font></a>';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}
					html += '</DIV>';
					html += '<DIV class=imidxxsmall>' + displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV>';
					if (myhrdlink)
						html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';
					
					

					html += '</DIV></SPAN>';

				} else {				
	
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:140px; height:' + theight + 'px;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','med',myhrdlink,myreleased);		
					html += '</DIV></SPAN>';
				}
			} else if (viewmode == "ss"){			
				html = '  ';
			} else if (viewmode == "huge"){		
				var theight = 220 + adminheight;
				if ( mysimilarto.length < 13){	
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:330px; height:' + theight + 'px; overflow: hidden;">';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" TITLE="ID:' + displayid;

					if(showphotographer == 1){html += '\r&copy; ' + myphotographer;}
					if(showfilesize){html +=   '\rSIZE: ' + myfilesize ;}
					html += ' \r' + 'CAPTION: ' + myshortcaption + '"><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/420/60/' + myid + '.JPG" border="0" vspace="1" hspace="3" alt="loading..." height="192"></a><BR>';
					html += '<DIV class=icons>';

					if ( ! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )
					{
						html+='<A href="" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LIGHTBOX+</a>';
					if(gsession){html += '<a href="" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font> ENLARGE</a> ';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}
					html += displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font> ';
					}
	                                html += '</DIV>  ';

					if (myhrdlink)
						html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';

					html += '</DIV></SPAN>';
					
				} else {
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:330px; height:' + theight + 'px; overflow: hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','huge', myhrdlink, myreleased);

					html += '</DIV></SPAN>';
				}				
			} else if (viewmode == "large"){
				var theight = 199 + adminheight;
				if ( mysimilarto.length < 13){		
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:187px; height:' + theight + 'px; overflow:hidden;">';
                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"'

					if(document.page.previews.selectedIndex == 1){html += ' TITLE="ID:' + displayid;
						if(showphotographer == 1){html +=  '\r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: ' + myfilesize ;}
						html += ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/170/85/' + myid + '.JPG" class=pimg border="0" vspace="0" hspace="3"';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
					
					html += '</a><BR>';
					html += '<DIV class=icons>';

					
					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )						{
						html+='<A href="" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="iconlink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}
					html += '<a href="" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature )
						html += '<a href="" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font></a>&nbsp;';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}

					html += '</div><div><font class=imid>' + displayid + '</font>';
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV>';

					if (myhrdlink)
	                                        html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';

					html += '</DIV></SPAN>';
		
			
				} else {			
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:187px; height:' + theight + 'px; overflow: hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','large', myhrdlink, myreleased);

					html += '</DIV></SPAN>';
				}
			} else {
				var theight = 176 + adminheight;
				if ( mysimilarto.length < 13){		
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:152px; height:' + theight + 'px; overflow:hidden;">';
                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"'


					if(document.page.previews.selectedIndex == 1){html += ' TITLE="ID:' + displayid;
						if(showphotographer == 1){html +=  '\r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: ' + myfilesize ;}
						html += ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + myid + '.JPG" class=pimg border="0" vspace="0" hspace="3"';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
					
					html += '</a><BR>';
					html += '<DIV class=icons>';

					
					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )						{
						html+='<A href="" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="iconlink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}
					html += '<a href="" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font></a>&nbsp;';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}
					 
					html += '</div><div><font class=imid>' + displayid + '</font>';
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV>';

					if (myhrdlink)
	                                        html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';


					html += '</DIV></SPAN>';
		
			
				} else {			
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:152px; height:' + theight + 'px; overflow: hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','normal', myhrdlink, myreleased);

					html += '</DIV></SPAN>';
				}

			}
		}
	} 
	return html;
};

// -> function so we only have to do this once.. option box is static...
function html_share_con_opts(dex) {
        //return 'Status:&nbsp;&nbsp;<select class="editformelem" id="sharecontrol'+dex+'" name="sharecontrol'+dex+'" onchange="sos('+dex+',\'share\')" >'+ unescape(shcon[dex]) + '</select>';

        if(typeof(shcon) == 'object' && shcon[dex] && shcon[dex] != '')
		return '<form id="shf'+id[dex]+'"><span style="font-size:7pt"><NOBR>'+unescape(shcon[dex])+'</NOBR></span><input type="hidden" name="dexer" value="'+dex+'"/></form>';
        else
                return '';
};

function html_weight_con_opts(dex) {
	if(typeof(swcon) == 'object' && swcon[dex] && swcon[dex] != '')
                return 'Weight:&nbsp;<select class="editformelem" id="weightcontrol'+dex+'" name="weightcontrol'+dex+'" onchange="sos('+dex+',\'weight\')">'+ unescape(swcon[dex]) + '</select>';
        else
                return '';
};

function html_combined_con_opts(dex) {
        if(typeof(cocon) == 'object' && cocon[dex] && cocon[dex] != '')
	{
		return '<form id="shf'+id[dex]+'"><span style="font-size:7pt"><NOBR>'+unescape(cocon[dex])+'</NOBR></span><input type="hidden" name="dexer" value="'+dex+'"/></form>';
	}
	else
		return '';
};


function switch_share_control(type) { //this turns your share control cookie on or off, which trips swishsearch
        var shmode = ggetCookie(gusername+'sc_on');
        if(!shmode || type ){ //turn on
                viewmode='editing';
		shmode = 1;
		
        }
	else //off
	{
		viewmode='';
		shmode = '';
	}

        gsetCookie('gviewmode',viewmode, '', '/', gGetCookieDom());
        gsetCookie(gusername+'sc_on',shmode, '', '/', gGetCookieDom());
	
	if (! type)
	{
		var s = self.location.href;
		self.location.href = s.replace(/\&sc_boot\=1/g, '');
	}

};

function EAD(idstring) { //function to check if an id Exists And is Defined as a form value
        if ($(idstring) && $F(idstring) && ! $F(idstring).match(/^\-\- .* \-\-$/))
                return true;
        else
                return false;
};

function sos(dex,which) { //SAVE OUR SHARES

        if (! which || which == 'share')
        {
                var share = $F('sharecontrol'+dex);
                ajax_JSON('/AjaxHandlers/ShareSetShare/'+make_share_control_string(id[dex], share)+'.json', getpost, '');
        }

        if (! which || which == 'weight')
        {
                var weight = $F('weightcontrol'+dex);
                ajax_JSON('/AjaxHandlers/ShareSetWeight/'+make_share_control_string(id[dex], weight)+'.json', getpost, '');
        }

        if( $('cellwrapper'+dex) )
                $('cellwrapper'+dex).style.backgroundColor = 'orange';
};


function sor(dex) { //SAVE RELEASE CONTROL..

	//get release
	var release = $A();
	var relstring = unescape(relcon[dex]).toString().replace(/checked="?checked"?/gi,''); 
	/// $('releasecontrol'+dex).innerHTML.toString().replace(/checked="checked"/gi,'');
	$A($('releasecontrol'+dex)).each( function(itm) {
		if (itm.checked)
		{
			release.push(itm.value);
			var relrex = new RegExp('value="'+itm.value+'"');
			relstring = relstring.replace(relrex, 'value="'+itm.value+'" checked="checked"');
		}
	});
	relcon[dex] = escape(relstring);

	release = release.join('|');
	ajax_JSON('/AjaxHandlers/ShareSetRelease/'+make_share_control_string(id[dex], release)+'.json', getpost, '');

	if( $('cellwrapper'+dex) )
		$('cellwrapper'+dex).style.backgroundColor = 'orange';
};

function validaterad(thar) {
        //radios are self limiting, no need for dex..
        if (! $(thar) && ! $F(thar))
                return;

        //gotta parse the id from name
        var nama = thar.name;
        nama = nama.replace(/(cocon|shcon)/, '');
        var pix = $F(thar);
        //more colors
//        stat            notshared       pending         shared
//        DF0000          red             white           green   77BB33

        var dex = $F($(thar).form.dexer);

        var brd = 'white';
	var status = 'pending';
        if (pix == 'n' || pix == 'r' || pix.match(/^(notshared|rejected)/) )
	{
		if (pix == 'n' || pix == 'notshared')
			status = 'notshared';
		else
			status = 'rejected';

                brd = '#DF0000';
	}
        else if (! isNaN(pix) || pix == 'a' || pix.match(/^shared/) )
	{
		status = 'shared';
                brd = '#77BB33';
	}
	else if ( pix.match(/^hold/) )
	{
		status = 'hold';
	}

        if ($('d'+nama))
                $('d'+nama).style.background = brd;

        var sharesync = unescape(shsync[dex]);
        sharesync=sharesync.split('|');
        shsync[dex] = escape( status + '|' + sharesync[1]);

	var save_str = '';
	if (thar.name.match(/shcon/))
		save_str = 'ShareSetShare';
	else
		save_str = 'ShareSetCombined';
	
        ajax_JSON('/AjaxHandlers/'+save_str+'/'+make_share_control_string(nama, pix)+'.json', getpost, '');

};

function init_share_radios(){ //runs with htmlit -- need to use shsync to remember radio values in javascript..
        for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
        {
                var sharesync = unescape(shsync[cnt]);
                sharesync=sharesync.split('|');
		var full_status = sharesync[0] + $F('share_control_view') + $F("share_control_home_sphotog");
		//combined control uses some combo of n,h,r,p,a,1,2,3,4 and are always allnet view, so less scope info needed
		// shsync codes are notshared,hold,rejected,pending,shared

		var comb_status,comb_weight;
		if ( typeof(cocon) == 'object' && cocon[0] )
		{
			comb_weight = sharesync[2];
			comb_status = sharesync[0].toString().substring(0,1);
		}
                var sForm = $('shf'+id[cnt]);
		if (sForm)
                    $A(sForm.elements).each( function(rad) {
                        if ( rad.value == full_status )  //full status goes first
                                rad.checked = true;
			else if ( comb_status && ( rad.value == comb_status || ( comb_status == 's' && rad.value == comb_weight ) ) )
				rad.checked = true;
                        else
                                rad.checked = false;
                    });

        }
};

function share_set_page(status) { //batch actions a page at a time only for separate share_control style 
//startnumber endnumber
	if (status == '')
		return;

	var shownIds = $A();
	var full_status = status + $F('share_control_view') + $F("share_control_home_sphotog");
        var comb_status = '';
        if ( typeof(cocon) == 'object' && cocon[0] )
        {
                comb_status = status.toString().substring(0,1);
        }


	for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
	{
	    if ( id[cnt] )
	    {
		shownIds.push(id[cnt]);
		if (status.match(/pending|hold/))
		{
			$('d'+id[cnt]).style.background = 'white';
		}
		else if (status.match(/notshared|rejected/) )
			$('d'+id[cnt]).style.background = '#DF0000';
		else if (status.match(/^shared/))
			$('d'+id[cnt]).style.background = '#77BB33';

		var sForm = $('shf'+id[cnt]);
                if (sForm)
		    $A(sForm.elements).each( function(rad) {
        		if ( rad.value == full_status )
				rad.checked = true;
                        else if ( comb_status && ( rad.value == comb_status || ( comb_status == 's' && rad.value.match(/^[a1-4]$/ )  ) ) )
                                rad.checked = true;
			else
				rad.checked = false;
		    }); 

                var sharesync = unescape(shsync[cnt]);
                sharesync=sharesync.split('|');
		shsync[cnt] = escape(status + '|' + sharesync[1]);
	    }
		
	}
	ajax_JSON('/AjaxHandlers/ShareSetShare/'+make_share_control_string(shownIds, full_status)+'.json', getpost, '');
	return false;
};

function save_all_releases() {  //just save all releases currently on the page..
	for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
		sor(cnt);

	return false;	
};

function release_set_page(release) { //batch actions a page at a time only for separate share_control style
	//MODEL RELEASED
	//NOT APPLICABLE
	//NOT RECOGNIZABLE
	//NOT RELEASED
	//PROPERTY RELEASED
	//MODEL AND PROPERTY RELEASED
//startnumber endnumber
        if (release == '')
                return;

        var shownIds = $A();

        for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
        {
            if ( id[cnt] )
            {
                shownIds.push(id[cnt]);

                var sForm = $('releasecontrol'+cnt);

                if (sForm)
                    $A(sForm.elements).each( function(chx) {
			var val = chx.value;
			if ( val && chx.type == "checkbox")
			{
			    if(val == release || ( release == 'MODEL AND PROPERTY RELEASED' && ( val == 'MODEL RELEASED' || val == 'PROPERTY RELEASED' ) ) )
				chx.checked = true;
  			    else
				chx.checked = false;
			}
                    });

        	if ($('shortrel'+cnt)) {
               		var shortrel = release;
                	shortrel = shortrel.substring(0,16) + (release.length > 16 ? '...' : '');
                	$('shortrel'+cnt).innerHTML = 'Release: '+shortrel;
        	}

		sor(cnt); //this spawns a lot of concurrent ajax requests, so set release call has to be reasonably fast... (currently it is)
            }

        }
        return false;
};



function validatechx(thar) {
	//so we're only checking certain things..
	// MODEL & PROP REL (OK)
	// ^NOT (uncheck all others)
	var cc = 0;
	var grel = '';
	$A(thar.form.elements).each( function(chx) {
		if (chx.checked)
		{
			cc++;
			grel = chx.value;//so if only 1 is checked, we get it prepopulated.. otherwise it gets set later..
		}
	});


	if (cc > 1) {  //more than one checked.. have to check for contradiction
		var keepon = new Object;

		/*if( thar.form.elements['NOT RELEASED'].checked ) { keepon['NOT RELEASED'] = 1; grel = 'NOT RELEASED'; }
		else if (thar.form.elements['NOT RECOGNIZABLE'].checked ) { keepon['NOT RECOGNIZABLE'] = 1; grel = 'NOT RECOGNIZABLE'; }
		else if (thar.form.elements['NOT APPLICABLE'].checked ) { keepon['NOT APPLICABLE'] = 1; grel = 'NOT APPLICABLE'; }
		else if (thar.form.elements['ERROR'].checked ) { keepon['ERROR'] = 1; grel = 'ERROR'; }
		else */
		
		if ( thar.form.elements['MODEL RELEASED'].checked && thar.form.elements['PROPERTY RELEASED'].checked 
			&& thar.name.toString().match(/(MODEL|PROPERTY) RELEASED/) )
		{
			keepon['MODEL RELEASED'] = 1;
			keepon['PROPERTY RELEASED'] = 1;
			grel = 'MODEL AND PROPERTY RELEASED';
		}
		else
		{
			keepon[thar.name] = 1;
			grel = thar.name;
		}

		$A(thar.form.elements).each( function(chx) {
                	if (chx.checked && keepon[chx.value] != 1 )
                        	chx.checked = false;
        	});


	}

	if ($('shortrel'+thar.form.shdex.value))
	{
                var shortrel = grel;
                shortrel = shortrel.substring(0,16) + (grel.length > 16 ? '...' : '');
		$('shortrel'+thar.form.shdex.value).innerHTML = 'Release: '+shortrel;
	}
	
};



function enlarge2 (enid,encount,featuredimage,nocache) { //ajax calls to data for detail/enlarged view of image
		var section = $H({ ssid:enid, ssdex:encount, fimg:featuredimage, nc:nocache, showstart:'ss', snum:firstpictureonpage, viewmode:'ss' }).toJSON();
                try { YAHOO.util.History.navigate("nav", section); } catch (e) { dispatchAll(section); }
};

function dispatchEnlarge2 ( args ) {
	if ( typeof(args) != 'object' )
		return;

	var enid = args['ssid'];
	var encount = args['ssdex'];
	var featuredimage = args['fimg'];
	var nocache = args['nc'];
	

	var previousMode = document.currentLayer1Mode;
	document.currentLayer1Mode = 'enlarge';
	var url = '/AjaxHandlers/ImageInfo/'+ 
		( featuredimage ? featuredimage : enid )+
		'.json';
	var drk = '';
	if (nocache)
        	drk = '&drk='+Math.random(10);

	ajax_JSON( url, getpost, "callback=enlarge2_act('"+enid+"','"+encount+"','"+(featuredimage?featuredimage:'')+"','"+previousMode+"')"+drk ); 
	setuppagesize();
	$('Layer1').style.height = truevertHeight + 'px';
        //have to anticipate the header going away when we enlarge..
        var headermod = 0;
        if ( $('cdheader') && $('cdheader').style.display == 'block' )
                headermod = 146;
        $('Layer1').style.height = truevertHeight + headermod + 'px';
};



function enlarge2_act__generateTierRows(myratetiers_data,myrmrftype,enid,encount) {
	var myratetiers = '';
        if ( myrmrftype == 'RF' )
        {
                var tieredimgpricing__rfslug_row = '';
                $A(myratetiers_data.tierinfo).each(function(rowi){
                                        Object.extend(rowi,  {
                                                enlargetid: myratetiers_data.image_id,
                                                usage: rowi.subof,
						img_id: enid,
						encount: ( encount ? encount : "''" )
                                        });
                                        tieredimgpricing__rfslug_row += Templates.tieredimgpricing__rfslug_row.evaluate(rowi);
                        });
                myratetiers = Templates.tieredimgpricing__rfslug.evaluate({ 'rows' : tieredimgpricing__rfslug_row });
        }
        else if ( myrmrftype == 'RR' )
        {
                var tieredimgpricing__rrslug_row = '';
                $A(myratetiers_data.tierinfo).each(function(rowi){
                                        Object.extend(rowi, {
                                                enlargetid: myratetiers_data.image_id,
                                                usage: rowi.subof,
						img_id: enid,
						encount: ( encount ? encount : "''" )
                                        });
                                        //if image is priced out, then include remove button..
                                        if (rowi.opt_selected == 1)
                                                rowi.removebutton = Templates.tieredimgpricing__rrslug_row_removebutton.evaluate(rowi);

                                        tieredimgpricing__rrslug_row += Templates.tieredimgpricing__rrslug_row.evaluate(rowi);
                        });
                myratetiers = Templates.tieredimgpricing__rrslug.evaluate({ 'rows' : tieredimgpricing__rrslug_row });
        }
	return myratetiers;
}

//CALLBACK ACTion for enlarge2
function enlarge2_act(enid,encount,featuredimage,preMem) {
	featuredimage = ( featuredimage == 'undefined' ? '' : featuredimage );
	hp();//ensure closure the preview window
        var useInPage = 0;
        if ( id[encount] == document.JSONobj.getImgDat('id') )
                useInPage = 1;

	if (useInPage || ( document.ajaxLoaded && (enid.match( document.JSONobj.getImgDat('id') )) ) )//made it
	{
		//wipe viewmode cookie:
		if(typeof(viewmode) != 'undefined' && viewmode == 'ss')
			gsetCookie("gcurrentview",'', '', '/', gGetCookieDom());


//		if( featuredimage || preMem == 'cartview' || ( useInPage && id[encount] )
//		{
                        if($('cdheader'))
                        	$('cdheader').style.display = 'none';


			//init
			if ( (! document.thisIsFeatureView && useInPage && st[encount] && st[encount].length > 13) || overflowtype == 'hidden' )
				suspendtrap=1;
			gSetBackpage();		
			if(firstpictureonpage)
				gsetCookie("gwhichstartpage",firstpictureonpage, '', '/', gGetCookieDom());
	
			//set metatdata variables
			var myshortcaption;
			var testshortcaption = document.JSONobj.getImgDat('short_caption');
			testshortcaption = (	testshortcaption	?  testshortcaption : "n/a");
			var testlongcaption = document.JSONobj.getImgDat('long_caption');
			testlongcaption = (	testlongcaption	?  testlongcaption : "n/a");
			if ( typeof(uselongcaption) != 'undefined' && testlongcaption != "n/a" )
			{
				if ( uselongcaption == 'useboth' )
				{
					if ( testshortcaption == "n/a" ) //then just use long
					{
						myshortcaption = testshortcaption;
					}
					else //build switcher
					{
						myshortcaption = '<span id="enlarge_short_caption">'+testshortcaption+
							' <a href="" onclick="$(\'enlarge_short_caption\').style.display=\'none\'; $(\'enlarge_long_caption\').style.display=\'inline\'; return false;">more&nbsp;&gt;&gt;</a></span><span style="display:none" id="enlarge_long_caption">'+testlongcaption+'  <a href="" onclick="$(\'enlarge_long_caption\').style.display=\'none\'; $(\'enlarge_short_caption\').style.display=\'inline\'; return false;">&lt;&lt;&nbsp;less</a></span>'
					}
				}
				else
				{
					myshortcaption = testlongcaption;
				}

			}
			else
			{
				myshortcaption = testshortcaption;
			}


			var myrmrftype = document.JSONobj.getImgDat('rmrftype');
			var myratetiers = document.JSONobj.getImgDat('rfcdimgpricing'); //this is currently preformatted list from templates, could
								//be extended in ajaxhandlers to return a data obj if we need 
								//more granular data

			var myphotographer	= document.JSONobj.getImgDat('photographer') +
					((document.JSONobj.getImgDat('agent_name') && document.JSONobj.getImgDat('agent_name') != '') ? '&nbsp;/&nbsp;'+document.JSONobj.getImgDat('agent_name') : '' );
			var myfilesize = (	document.JSONobj.getImgDat('file_size') < 5 ?
					'Scan on Demand'
						:
					document.JSONobj.getImgDat('file_size') + ' Mb');	
			var myreleased = document.JSONobj.getImgDat('released');
			var myrestrictions = document.JSONobj.getImgDat('image_restrictions');
			var mycompallow = document.JSONobj.getImgDat('comp_allow');
                        var mydimensions = ( typeof(showdimensions) != 'undefined' ? document.JSONobj.getImgDat('dimensions') : '');
                        if (mydimensions) //comes as <XVAL>x<YVAL>
                        {
                                var dimr = mydimensions.match(/^(\d+)x(\d+)$/);
                                if (typeof(dimr) == 'object')
                                        mydimensions = '<br/><b>Original Dimensions:</b>&nbsp;'+dimr[1]+'px&nbsp;x&nbsp;'+dimr[2]+'px';
                        }
	
			var nextimage = parseInt(encount) + 1;
			var nextimageid = id[nextimage];
			var previmage = parseInt(encount) - 1;
			var previmageid = id[previmage];
			
			//this ifblock becomes template var: themediainsert
			var themediainsert = '';
			if((! document.thisIsFeatureView) && useInPage && v[encount] && (v[encount] == 'H')){
				var temph= + enid.substring(0,2) + '/' + enid.substring(0,5) + '/' + enid;
				themediainsert += '<EMBED SRC="http://tools.cgibackgrounds.com/qtvideo/' + temph + '.MOV" WIDTH=420 HEIGHT=280></EMBED>';

			} else {
				var tarid = '0000000000';
				if(featuredimage){tarid = featuredimage;} else {tarid= enid;}
				themediainsert += '<A HREF="" onclick="currentpage(); return false;">'
					+'<img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/'+
					( (typeof(localwatermark) != 'undefined' && ! pngsupport) ? 'wm' : '420' )
					+'/60/'+tarid+'.JPG" border=1 style="display:inline; clear:none;" id="'+tarid+'">'
					+( (typeof(localwatermark) != 'undefined' && pngsupport) ?
						'<img style="z-index: 300; position:absolute; left:0px; bottom:0px;" src="'+localwatermark+'" border="0" onload="fitMeTo(\''+tarid+'\', this)"/>'
						:
						'');
				themediainsert += '</A>';
			}
			
			//similarscolumn
			var similarscolumn = '';
			if(! document.thisIsFeatureView && useInPage && st[encount] && st[encount].length > 13){
				var simlist =st[encount];
				var simarray=simlist.split(" ");
				var temparray = simarray[1].split(",");
				if(temparray.length > 1){temparray=simarray[0] + ' ' + temparray.join(' ');simarray=temparray.split(' ');}
				var simcount =simarray.length;
				if(simcount>40){simheight=(70 - simcount/2)} else {simheight=70 - simcount;}

				var simcolinfo = '';				
				for(var i=0;i< simcount;i++){
					simcolinfo += '<span valign=bottom style="float:left;">'
								+'<a href="javasc' + 'ript:enlarge2(\'' + enid + '\'' + ',' + '\'' + encount + '\',\'' + simarray[i] + '\');" TITLE="ID:' + simarray[i];
					if(showphotographer == 1)
						simcolinfo += '  \r&copy; ' + myphotographer;
						
					simcolinfo += ' click image to view similar"><img src=http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + simarray[i] + '.JPG border=0 vspace=2 hspace=2 height=' + simheight + ' align=left></a></span>';
				}
				similarscolumn = Templates.enlarge2_act__similars.evaluate({simcolinfo: simcolinfo});
			}
			
			


			//this ifblock becomes var navbacklink
			//will become navenlargedlinks
			var navenlargedlinks = '';
			var navbacklink = '';
			    if (preMem == 'cartview')
			    {
				navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'cartview\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom());currentpage(); return false;"><FONT style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO CART</A><BR><BR>';
			    }
			    else if (document.thisIsFeatureView)
			    {
				navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'searchresults\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom()); self.location = self.location; return false;"><FONT style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO REQUEST RESULTS</A><BR><BR>';
			    }
			    else
			    {
				navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'searchresults\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom()); currentpage(); return false; "><FONT style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO SEARCH RESULTS</A><BR><BR>';
			    }

			if ( useInPage )
			{
			    if(preMem != 'cartview')
			    {
				if((snum + encount) > 0){ navenlargedlinks+= '                                  <A HREF="" onclick="enlarge2(\'' + previmageid + '\',\'' + previmage + '\'); return false;" TITLE="GO TO THE PREVIOUS IMAGE"><FONT style="font-size:9pt; font-family: Arial;">&#8592;</FONT> PREV IMAGE </A>&nbsp;&nbsp;';}
				if((Number(snum) + Number(encount) + 1) < Number(total)){ navenlargedlinks+= '                                  <A HREF="" onclick="enlarge2(\'' + nextimageid + '\',\'' + nextimage + '\'); return false;" TITLE="GO TO THE NEXT IMAGE">NEXT IMAGE <FONT style="font-size:9pt; font-family: Arial;">&#8594;</FONT></A><BR>';}
			    }
			}

			var enlargetid = '';
			if(featuredimage){ enlargetid = featuredimage;} else { 	enlargetid = enid;}
			
			//will become downloadcomplink
			var downloadcomplink = '';
			if(preMem != 'cartview')
			{
				if(gsession && gusername && mycompallow == 'Y') { 
					downloadcomplink = '<a href="Javascr' + 'ipt:displayWindow(\'/comp_view.shtml?' + gusername + '/' + cs[encount] + '/' +
					enlargetid
					+ '.JPG\',\'600\',\'640\');"><img src="/graphics/icon_comp.gif" width=21 height=15 alt="" border="0"> DOWNLOAD COMP</a><BR><BR>';
				} else {
				if(gsession) {
					downloadcomplink = '<a href="Javascr' + 'ipt:displayWindow(\'/comp_view.shtml?guest/' + cs[encount] + '/' +
					enlargetid			
					+ '.JPG\',\'600\',\'640\');"><img src="/graphics/icon_comp.gif" width=21 height=15 alt="" border="0"> DOWNLOAD COMP</a><BR><BR>';
					}
				}
			}
	
			// META DATA FOR ENLARGED TARGET IMG:
	
			//will become: ratetierinfo
			var ratetierinfo = ( myratetiers ? '<BR/><div class="enlargeratetiers">' + myratetiers + '</div>' : '' );
			
			//becomes releaseinfo
			var releaseinfo = ( showrelease ? '<b>Release:</b> ' + myreleased + '<br>' : '' );
			
			//becomes photographerinfo
			var linked_photog = myphotographer;
			if(myphotographer.indexOf('/') > 0)
				linked_photog = linked_photog.substring(0, linked_photog.indexOf('/'));
			var photographerinfo = ( (myphotographer && showphotographer) ? '<b>Photographer:</b> <A href="/SwishSearch?Keywords=' + linked_photog + '&spec_idx=ne&method=photographer">' + myphotographer + '</a><br>' : '');
	
			//becomes filesizeinfo
			var filesizeinfo = ( (! featuredimage && showfilesize) ? '<b>File Size:</b> ' + myfilesize : '');
			
			//becomes restrictionsinfo
			var restrictionsinfo = (myrestrictions ? '<BR/><span style="color:#990000">'+myrestrictions+'</span>' : '');
			
			//becomes keywordinfo
			var keywordinfo = '';
			document.JSONobj.getKeywords().each(function (kwd){
				var relink = q_args;
				//e.g. Keywords=shot%20put+haspeople+NOT+imagehasrestrictions
				if(relink.match(/Keywords=[^\+\&]+\+/))
				{
					relink = relink.replace(/Keywords=[^\+]+\+/, 'Keywords='+kwd+'+');
				}
				else if (relink.match(/Keywords=[^\+\&]+\&/))
				{
					relink = relink.replace(/Keywords=[^\+\&]+\&/, 'Keywords='+kwd+'&');
				}
				else if (relink.match(/Keywords=[^\+\&]+$/))
				{
					relink = relink.replace(/Keywords=[^\+\&]+$/, 'Keywords='+kwd);
				}
				else //might be lightbox or request, but so no actual keywords, so append it directly
				{
					relink = relink.replace(/((rid|\&rid)|(vmo|\&vmo)|(lb_view|\&lb_view)|(cartview|\&cartview))=[^\&]+/, '');
					relink = 'Keywords='+kwd+'&'+relink;
					relink = relink.replace(/\&+/, '&');
				}
				relink = relink.replace('&spec_idx=ne', '');
				keywordinfo += '<a href="/SwishSearch?' + relink +'&spec_idx=ne">' + kwd + '</a>, ';
			});

			var displayenlargetid;
			if ( o[encount] ){displayenlargetid=o[encount];} else {displayenlargetid=enlargetid;}

			var dateshot = document.JSONobj.getImgDat('date_shot');
			var rfcdlinkslug = document.JSONobj.getImgDat('rfcdlink');
						
			var tdata = $H({enlargetid: enlargetid,
					rfcdlinkslug: rfcdlinkslug,
					dateshot: dateshot,
					keywordinfo: keywordinfo,
					displayenlargetid: displayenlargetid,
					restrictionsinfo: restrictionsinfo,
     					filesizeinfo: filesizeinfo,
	  				photographerinfo: photographerinfo,
       					releaseinfo: releaseinfo,
	    				ratetierinfo: ratetierinfo,
	 				downloadcomplink: downloadcomplink,
      					navenlargedlinks: navenlargedlinks,
	   				navbacklinks: navbacklink,
					similarscolumn: similarscolumn,
     					themediainsert: themediainsert,
	  				rmrftype: myrmrftype,
					myshortcaption: myshortcaption,
					dimensions: mydimensions
				});
			//write html for enlarge page
			$('Layer1').style.overflow = 'auto';
			MM_setTextOfLayer('Layer1','', Templates.enlarge2_act__body.evaluate(tdata));
			MM_preloadImages('http://gdynx.ipnstock.com/'+dynimagesname+'/420/60/' + nextimageid + '.JPG');
		} 
		else {
			//alert("This is the last image of the search results.");
			gsetCookie('gviewmode','ss', '', '/', gGetCookieDom());

			self.location= nextlink + 'snum=' + (Number(firstpictureonpage) + Number(snum)); //figure out which should be first picture on next page	
		}//end if id[enid]	
/*	}
	else if ( tryCtr < 10 ) 
	{
		tryCtr++;
		setTimeout("enlarge2_act('"+enid+"','"+encount+"','"+featuredimage+"', '"+tryCtr+"', 0, '"+preMem+"')", (500 + (10 * (tryCtr - 1))));
	}
	else // nothing loaded, pop the page w/ missing data..
	{
		enlarge2_act(enid,encount,featuredimage,tryCtr,1,preMem);
	}
*/	
};

function fitMeTo(targetid, thar) {
	if (! targetid || ! thar || ! $(targetid))
	return;

	var dems = Element.getDimensions(targetid);

	if (thar.style)
	{
		thar.style.width = (dems['width']+8) + 'px';	
 		thar.style.height = (dems['height']+8) + 'px';
	}
	return 1;
};

function writesearch(){
	if (typeof(writesearch_custom) == 'function')
		writesearch_custom();
	else
		writesearch_standard();
};

function writesearch_standard() {
	panelheight=340;
	if (typeof(showIllusPhotog) != 'undefined'){ //if adding Illustration / Photography selector checkboxes
		panelheight += parseInt(showIllusPhotog);
	}
	
	gsearchprefs=ggetCookie('gsearchprefs');
	var temph=' checked';
	var tempv=temph;
	var temps=tempv;
	var tempp=tempv;
	var temprno='';
	var temprany=tempv;
	var temppeopany=tempv;
	var temppeopwith='';
	var temppeopwithout='';
	var temppeopcrowd='';
	var temprelany=tempv;
	var temprelonly='';
	var tempcolany=tempv;
	var tempcolcol='';
	var tempcolbw='';
	var rmc="checked";var rfc=rmc;

        var tempillustration=' checked';
        var tempphotography= tempillustration;

	var tempsearchnew = ' selected';
	var tempsearchwithin = '';


	if(gsearchprefs){
		if(gsearchprefs.indexOf("f")>=0 || gsearchprefs.indexOf("g")>=0 || gsearchprefs.indexOf("h")>=0 || gsearchprefs.indexOf("i")>=0){
			if(gsearchprefs.indexOf("f")>=0){ } else {
				temph=' ';
			}
			if(gsearchprefs.indexOf("g")>=0){ } else {
				tempv=' ';
			}
			if(gsearchprefs.indexOf("h")>=0){ } else {
				tempp=' ';
			}
			if(gsearchprefs.indexOf("i")>=0){ } else {
				temps=' ';
			}
		}

                if (typeof(showIllusPhotog) != 'undefined'){ //if adding Illustration / Photography selector checkboxes
			if(gsearchprefs.indexOf("1")<0 && gsearchprefs.indexOf("0")<0){ }
			else
			{
				if(gsearchprefs.indexOf("1")<0){ tempphotography=' '; } 
				if(gsearchprefs.indexOf("0")<0){ tempillustration=' '; } 
			}
                }

		if (typeof(showSearchWithin) != 'undefined'){
			if ( $('method') && $F('method') == 'within')
			{
				tempsearchnew = '';
				tempsearchwithin = 'selected';
			}
			else
			{
				tempsearchnew = 'selected';
				tempsearchwithin = '';
			}
		}

		if(gsearchprefs.indexOf("j")<0 || gsearchprefs.indexOf("k")<0){
			if(gsearchprefs.indexOf("k")<=0 && gsearchprefs.indexOf("j")<=0 ){ }
			else
			{
				if(gsearchprefs.indexOf("k")<=0){// && ! gsearchprefs.indexOf("k")>=0){
					rfc = "";
				}
				if(gsearchprefs.indexOf("j")<=0){// && ! gsearchprefs.indexOf("j")>=0){
					rmc = "";
				}
			}
		}
		if(gsearchprefs.indexOf("b")>=0){ //restrictions
			temprany='';
			temprno='checked';
		}
		if(gsearchprefs.indexOf("c")>=0 || gsearchprefs.indexOf("d")>=0 || gsearchprefs.indexOf("e")>=0)
		{
			if(gsearchprefs.indexOf("c")>=0) //without people
			{
				temppeopany = '';
				temppeopwith = '';
				temppeopwithout = 'checked';
				temppeopcrowd = '';
			}
			if(gsearchprefs.indexOf("d")>=0) //with people
			{
				temppeopany = '';
				temppeopwith = 'checked';
				temppeopwithout = '';
				temppeopcrowd = '';
			}
			if(gsearchprefs.indexOf("e")>=0) //with crowd
			{
				temppeopany = '';
				temppeopwith = '';
				temppeopwithout = '';
				temppeopcrowd = 'checked';
			}
		}
		if(gsearchprefs.indexOf("a")>=0){
			temprelonly = 'checked';
			temprelany = '';
		}
		if(gsearchprefs.indexOf("m")>=0 || gsearchprefs.indexOf("n")>=0 || gsearchprefs.indexOf("o")>=0)
		{
			if(gsearchprefs.indexOf("m")>=0) //any
			{
				tempcolany='checked';
				tempcolcol='';
				tempcolbw='';
			}
			if(gsearchprefs.indexOf("n")>=0) //
			{
				tempcolany='';
				tempcolcol='checked';
				tempcolbw='';
			}
			if(gsearchprefs.indexOf("o")>=0) //
			{
				tempcolany='';
				tempcolcol='';
				tempcolbw='checked';
			}
		}
	}
	var thehtml = '<form action="javasc' + 'ript:g(); return false;" method=get name=displaypanel id=displaypanel>';
	thehtml += '<table cellspacing=0 cellpadding=10 border=0 width=100% height=' + panelheight + '>';
	thehtml += '<tr><td valign=top align=left class="light1">';
	thehtml += '<b>ORIENTATION:</b><br>';
	thehtml += '<table cellspacing=3 cellpadding=0 border=0><tr>';
	thehtml += '<td><nobr><input type=checkbox name=orient value=horizontal onclick=javasc' + 'ript:fsearchprefs("f","add"); ' + temph + '> Horizontal</nobr></td></tr>';
	thehtml += '<tr><td><input type=checkbox name=orient value=vertical onclick=javasc' + 'ript:fsearchprefs("g","add"); ' + tempv + '> Vertical</td></tr>';
	thehtml += '<tr><td><input type=checkbox name=orient value=panoramic onclick=javascr' + 'ipt:fsearchprefs("h","add"); ' + tempp + '> Panororamic</td></tr>';
	thehtml += '<tr><td><input type=checkbox name=orient value=square onclick=javasc' + 'ript:fsearchprefs("i","add"); ' + temps + '> Square</td></tr>';
	thehtml += '</table><br>';
	thehtml += '<b>COLOR:</b><br>';
	thehtml += '<table cellspacing=3 cellpadding=0 border=0>';
	thehtml += '<tr><td><nobr><input '+tempcolany+' type=radio name=color value="" onclick=javascr' + 'ipt:fsearchprefs("color","add");> ANY</td></tr>';
	thehtml += '<tr><td><nobr><input '+tempcolcol+' type=radio name=color value=color onclick=javascr' + 'ipt:fsearchprefs("color","add");> COLOR</td></tr>';
	thehtml += '<tr><td><input '+tempcolbw+' type=radio name=color value=gray onclick=javascr' + 'ipt:fsearchprefs("color","add");> B/W</td></tr>';
	thehtml += '</table>';

        if (typeof(rmonly) == 'undefined'){
                thehtml += '<BR><b>TYPE:</b><br>';
                thehtml += '<table cellspacing="0" cellpadding="3" border="0"><tr><td><font class="black2"><nobr><input type="checkbox" name="rmrftype" value="RM" ' + rmc + ' onclick=javascr' + 'ipt:fsearchprefs("RM","add");> Rights Managed</nobr></font></td>';
                thehtml += '</tr><tr><td><font class="black2"><input type="checkbox" name="rmrftype" value="RF" ' + rfc + ' onclick=javascr' + 'ipt:fsearchprefs("RF","add");> Royalty Free</font></td></tr></table>';
        }


	thehtml += '</td><td valign=top align=left class="light1">';

	if (typeof(showIllusPhotog) != 'undefined'){ 
		thehtml += '<b>MEDIA:</b><br>';
        thehtml += '<input type="checkbox" name="searchinclude" value="illustration"' + tempillustration + ' onclick=javascr' + 'ipt:fsearchprefs("1","add"); />Illustration<br/>';
        thehtml += '<input type="checkbox" name="searchinclude" value="photography"' + tempphotography + ' onclick=javascr' + 'ipt:fsearchprefs("0","add"); />Photography<br/>';
        thehtml += '<br/>';
	}

	if (typeof(suspendYesNoRestrictons) == 'undefined'){
		thehtml += '<b>RESTRICTIONS:</b><br>';
		thehtml += '<input '+temprany+' type=radio name=restrictions value="" onclick=javascr' + 'ipt:fsearchprefs("norestrictions","remove");> ANY<br>';
		thehtml += '<input '+temprno+' type=radio name=restrictions value=not+imagehasrestrictions  onclick=javascr' + 'ipt:fsearchprefs("norestrictions","add");> NO RESTRICTIONS<br>';
		thehtml += '<br>';
	}

	if (typeof(suspendWithPeople) == 'undefined'){
		thehtml += '<b>PEOPLE:</b><br>';
		thehtml += '<input '+temppeopany+' type=radio name=people value="" onclick=javasc' + 'ript:fsearchprefs("people","remove");> ANY<br>';
		thehtml += '<input '+temppeopwith+' type=radio name=people value=withpeople onclick=javasc' + 'ript:fsearchprefs("withpeople","add");> WITH PEOPLE<br>';
		thehtml += '<input '+temppeopwithout+' type=radio name=people value=nobody onclick=javascr' + 'ipt:fsearchprefs("nobody","add");> WITHOUT PEOPLE<br>';
		thehtml += '<input '+temppeopcrowd+' type=radio name=people value=withcrowd onclick=javascr' + 'ipt:fsearchprefs("withcrowd","add");> CROWD<br>';
	}

	thehtml += '<br><b>RELEASES:</b><br>';
	thehtml += '<font class=small>';
	thehtml += '<input '+temprelany+' type=radio name=xtrasql value="" onclick=javascr' + 'ipt:fsearchprefs("released","remove");> Any release status<br>';
	thehtml += '<input '+temprelonly+' type=radio name=xtrasql value=released onclick=javascr' + 'ipt:fsearchprefs("released","add");> Only show released images<br>';

// conditional to insert 'search within' box in dropdown:
	if (typeof(showSearchWithin) != 'undefined'){
		thehtml += '<br/><b>METHOD:</b><br/>';
		thehtml += '<nobr>&nbsp;<select id="method" name="method" class="smallmenu" style="height:16px;"><option value="new" '+tempsearchnew+'>as a new search</option><option value="within" '+tempsearchwithin+'>within current results</option></select></nobr><br/>';
	}

	thehtml += '<BR><a href="" onclick="g(); return false;"><img src="/graphics/button_go.gif" alt="search" border="0"></a><BR><BR><A href="" onclick="hidedisplaypanel(1); return false;">[x] close search options panel</A>';
	thehtml += '</td></tr></table>';
	var temp=Position.cumulativeOffset($('tablerow2'));
	center_panel(340,panelheight,thehtml,temp[1]);
	Event.observe(document, 'mousemove', getMouseXY);
};

function getMouseXY(e) {
  if(browser != 'Internet Explorer'){
    msX = e.pageX
    msY = e.pageY
  } else {
    msX = event.clientX + document.body.scrollLeft
    msY = event.clientY + document.body.scrollTop
  }  
	if( msX < panelx || msY > (panely+panelheight)){
		document.isn.Keywords.blur();
                hidedisplaypanel(1);
        }

};

function createDisplayPanel() {  //so functions requiring the display panel can call 1 func to generate it as needed
	if ( $('displaypanellayer') )
		return;
	var dp = document.createElement('div');
	dp.setAttribute('id', 'displaypanellayer');
	document.body.appendChild(dp);
};

function createCoverLayer() {  //so functions requiring the display panel can call 1 func to generate it as needed
	if ( $('coverlayer') )
		return;
	var dp = document.createElement('div');
	dp.setAttribute('id', 'coverlayer');
	document.body.appendChild(dp);
};

function displaypanelshow(){
	createDisplayPanel();

	$('displaypanellayer').style.zIndex = '9991001';
	$('displaypanellayer').style.visibility="visible";
	//new Effect.Opacity('displaypanellayer',{duration: 0.01, from: 0.07, to: 1 });
	new Effect.Appear('displaypanellayer', {duration: 0.5})

	setTimeout("divshim(1);", 200);
};

function divshim (twid) { //simply to have it set-timeoutable..
	if(typeof($) == 'function' && $('DivShim'))//site that has the popup fix for IE6 and below (it can't render form elements behind dom objects)
	{
		if (twid) //on
		{
			createDisplayPanel();
			$('DivShim').style.width = $('displaypanellayer').style.width;
			$('DivShim').style.height = $('displaypanellayer').style.height;
			$('DivShim').style.top = $('displaypanellayer').style.top;
			$('DivShim').style.left = $('displaypanellayer').style.left;
			$('DivShim').style.zIndex = $('displaypanellayer').style.zIndex - 1;
			$('DivShim').style.display = "block";
		}
		else
		{
			$('DivShim').style.display = "none";
		}
	}
};

function hidedisplaypanel(mode){
	createCoverLayer();
	divshim(0);
	createDisplayPanel();
	if($('displaypanellayer').style && $('displaypanellayer').style.visibility == 'visible'){
		if(mode==1){
			new Effect.Fade('displaypanellayer', {duration: 0.01})			
		} else {
			new Effect.Fade('displaypanellayer', {duration: 0.3})
		}
	}
	if($('coverlayer').style && $('coverlayer').style.visibility == 'visible'){
		new Effect.Fade('coverlayer', {delay: 0.22, duration: 0.3, from: 0.7, to: 0});
		setTimeout("coveroff();",0.31);
	}
	setTimeout("$('displaypanellayer').style.visibility='hidden';", 0.31);
	
	Event.stopObserving(document, 'mousemove', getMouseXY);
};

function coveroff(){
	createCoverLayer();
	$('coverlayer').style.visibility="hidden";
};

function buildpages(startnumber,endnumber,snum){
        suspendtrap=1;

        //builds pulldown menu for page numbers depending on pixperpage and total pagenumbers
        var thehtml= '<table width="100%"><tr><td valign="top">';

	thehtml+= '<NOBR><FONT class=page>';

	//pagenumbers
	var showstartnumber = parseInt(startnumber) + parseInt(snum) + 1;
	var showendnumber = parseInt(endnumber) + parseInt(snum);

        //conditional previous page
        if(Number(currentpagenum) > 0){
                thehtml+='<A href="" onclick="document.currentLayer1Mode=\'searchresults\';prevpage(); return false;"><FONT style=\"font-size:9pt;font-family: Arial;\">&#8592;</FONT> PREV PAGE</A>&nbsp;';
        } else if (showstartnumber <= total){
                thehtml+='<FONT style=\"font-family: Arial;color:#AAAAAA;\"><FONT style="9pt;">&#8592;</FONT> PREV PAGE</FONT>&nbsp;';
	}

	if ( showstartnumber <= total )
	{
		thehtml+='Go&nbsp;to&nbsp;Page:&nbsp;<SELECT name="pageurl" align="absmiddle"  onChange="document.currentLayer1Mode=\'searchresults\'; self.location=this.options[this.selectedIndex].value; return false;" class="smallmenu" style="width:5.5em;">';
	
		totalpages=(  Math.ceil((snum)/( parseInt( $F('pixperpage') ))) +  Math.ceil( (total - snum) / ( parseInt( $F('pixperpage') )  ))) ;
		if(Number(currentpagenum) > 52){psn = (Number(currentpagenum) - 50);} else { psn = 1;}
	
		if((Number(totalpages) - Number(currentpagenum)) > 50){ pen = (Number(currentpagenum) + 50);} else {pen = totalpages;}
		if(psn >1 && currentpagenum != 0){
			thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((psn - 2) * (parseInt(gpixperpagev))) + '">&lt; ' + (Number(psn) - 1) + '</option>';
		}
	
		for(i=psn;i <= pen;i++){
			if(i == (Number(currentpagenum) + 1)){
				thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((i-1) * (parseInt(gpixperpagev))) + '" SELECTED>' + i + '</option>';
			} else {
				thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((i-1) * (parseInt(gpixperpagev))) + '">' + i + '</option>';
			}
		}
	
		if(pen != totalpages){
			thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((Number(pen)) * (parseInt(gpixperpagev))) + '">&gt; ' + (Number(pen) + 1) + '</option>';
		}

	
		thehtml+='</select>';
		if(grange != "outofrange"){
			thehtml+='&nbsp;<A HREF="" onclick="document.currentLayer1Mode=\'searchresults\';nextpage(); return false;">NEXT PAGE&nbsp;<FONT style="font-size:9pt;font-family: Arial;">&#8594;</FONT></A></font>';
		}

		
		thehtml += '&nbsp;&nbsp;[' + showstartnumber + '-';
		if (showendnumber > parseInt(total)){
			thehtml +=  total + ']&nbsp;of&nbsp;' + total;
		} else {
			thehtml += showendnumber + ']&nbsp;of&nbsp;' + total;
		}
		thehtml += '</NOBR>';

		thehtml += '</td><td align="right">';

		//linkback to feature:
		if (document.thisIsFeatureView)
		{
			thehtml += '<a href="/R?'+feat_requestview+'" style="color:#c00; font-size:10px"><nobr>View images from</nobr> <br/><nobr><b>All IPN Members</b></nobr></a>';
		}

	        if (typeof(shsync) == 'object' && shsync[0] && shsync[0] != '')
		{
			var lochtml = '<a onclick="return save_all_releases();" href="">Save All Releases</a> &nbsp;&nbsp; [ Set All: <a href="" onclick="return share_set_page(\'shared\'); ">Accepted</a> | <a href="" onclick="return share_set_page(\'rejected\'); ">Rejected</a> | <a href="" onclick="return share_set_page(\'pending\'); ">Pending</a>  &nbsp;|&nbsp;  <a onclick="return release_set_page(\'NOT RELEASED\');" href="" title="NOT RELEASED">NR</a> | <a onclick="return release_set_page(\'NOT APPLICABLE\');" href="" title="NOT APPLICABLE">NA</a> | <a onclick="return release_set_page(\'NOT RECOGNIZABLE\');" href="" title="NOT RECOGNIZABLE">NR</a> | <a onclick="return release_set_page(\'MODEL AND PROPERTY RELEASED\');" href="" title="MODEL AND PROPERTY RELEASED">MaPR</a> ]';
			$('Layerpreviews').innerHTML = lochtml;
		}
	}

	thehtml += '</td></tr></table>';

	$('Layerpages').style.overflow = 'visible';
        MM_setTextOfLayer('Layerpages','',thehtml);

};

function buildimages(startnumber,mode,resized){
	if(typeof(cartview) != 'undefined' && cartview)
		return;

	if(typeof(id) == 'undefined')
		return;

        var showstartnumber = parseInt(startnumber) + parseInt(snum) + 1;
        var section = $H({ showstart:showstartnumber, snum:startnumber, viewmode:viewmode, buildmode:mode, resized:resized }).toJSON();
        try { YAHOO.util.History.navigate("nav", section); } catch (e) { dispatchAll(section); }
};

function dispatchBuildimages(args) {
	var startnumber = args['snum'];
	var mode = args['buildmode'];
	var resized = args['resized'];
	viewmode = args['viewmode'];
	$('Layer1').style.height = winH +'px';
	$('Layer1').style.overflow = 'hidden';

	if ( $("nav_total_images") )
		$("nav_total_images").innerHTML = id.length;

        if($('cdheader')){
		(typeof(dsplkys) != 'undefined' ? ( ( dsplkys.substring(0,6)=='BLDVCD' || dsplkys.match(/ZRFCD$/) ) ? $('cdheader').style.display = 'block' : $('cdheader').style.display = 'none')             : $('cdheader').style.display = 'block' );
	}

	document.currentLayer1Mode='searchresults';
	createCoverLayer();
	if(!MACIE5){var tshown = Element.getOpacity('coverlayer');}
	
	if(tshown > 0.2){
		hidedisplaypanel();
	}
        suspendcheck=1;
        //calculate how many images can be held on the page depending on mode being used
        if(startnumber > 1 || resized==1){setuppagesize();}

        //  build the page
	showstartnumber_trap = parseInt(startnumber);  //save for later
        var thehtml=optimize(); // + '<FORM name=activedisplay action=#>';
        grange="legal";
        MM_setTextOfLayer('Layer1','','<CENTER> <BR><BR><BR><BR><BR><BR><BR><BR>loading ...</CENTER>');
        var cnt=startnumber;
        //figureout current range of images to show
        firstpictureonpage=startnumber;
        endnumber = parseInt(gpixperpagev) + parseInt(startnumber);

        if (viewmode != "ss"){
                //loop through images in the array and build html
				if(pagetype=='lb' && (typeof(pre_q_args) != 'undefined' && ! ( pre_q_args.match(/lb_view=1/) || pre_q_args.match(/fn=/) || pre_q_args.match(/vmo=/) ) ) )
					thehtml += '&nbsp;&nbsp;<A href="" onclick="viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom()); self.location=\'/SwishSearch'+pre_q_args+'\'; return false;"><FONT style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO SEARCH RESULTS</A><BR/><BR/>';

		while(cnt < endnumber) {
			if( id[cnt] ){
				if ( typeof(htmlit_custom) == 'function' )  {
					thehtml += htmlit_custom(cnt);
				} else {
					 thehtml += htmlit(cnt);
				}
			} else if((snum + cnt)>=total){
                                if (grange != "outofrange"){
                                        thehtml+='<span valign=bottom style="float:left;"><div align=center valign=bottom style="width:130; height:50px; overflow: hidden;">';

                                        if(pagetype=='lb'){
						thehtml+='<BR><nobr>&nbsp;[ end of lightbox images ]&nbsp;</nobr></DIV></SPAN> ';
                                        } else {
						thehtml+='<BR><nobr>&nbsp;[ end of search results ]&nbsp;</nobr></DIV></SPAN> ';
					}
                                }

                                grange="outofrange";

                        } else {
                                grange="illegalpage";   //check to see if page numbers are out of the legal range of images
                        }
                        cnt++;
               } 

		if (snum + cnt == total)
			grange = 'outofrange';  //basically we have exactly enough images, 
						//so we want to skip adding the nextlink and the [ end of results ] cell

               //conditions below are for going ahead or behind available imagenumber ranges
                if (grange == "illegalpage"){
                        if (mode == "next"){
				var next_snum = ( Number(snum) + Number(startnumber) );
        			var section = $H({ showstart:1, snum:0, viewmode:viewmode, resized:resized }).toJSON();

                                self.location= nextlink + 'snum=' + next_snum + '#nav='+section; //figure out which should be first picture on next page
                                 MM_setTextOfLayer('Layer1','','<CENTER> <BR><BR><BR><BR><BR><BR><BR><BR>loading next set of images...</CENTER>');
                        } else {

                                // two ways to go with this code
                                // method a is one screen at a time
                                //prevtogoto = snum + startnumber;

                                // method b is two screens at a time
                                prevtogoto=Number(snum) + Number(startnumber) - parseInt($F('pixperpage')); // go back two pages from start page
                                //gsetCookie("gwhichstartpage",parseInt($F('pixperpage')), '', '/', gGetCookieDom());
                                // ensure no negative numbers
                                if(prevtogoto < 0 ){ prevtogoto=0;}
        			var section = $H({ showstart:1, snum:0, viewmode:viewmode, resized:resized }).toJSON();
                                self.location=nextlink + 'snum=' + prevtogoto + '#nav='+section;

                        }

                } else {

                        //normal page ranges - add lower right next page link
			//thehtml+='</FORM>';
                        MM_setTextOfLayer('Layer1','',thehtml);

			if (shsync[0])
				setTimeout('init_share_radios()', 1);

                        var bottomthehtml= "<table style=\"position:absolute; z-index:999; top:-16px; right:4px; \" width=98% height=17 cellpadding=0 cellspacing=0 border=0><TR><TD align=left width=40%>";
                        if ((typeof(snum) != 'undefined' && Number(snum) > 1) || ( typeof(startnumber) != 'undefined' && Number(startnumber) > 1)){
                                bottomthehtml+= "<nobr>&nbsp;&nbsp;<A HREF=javasc" + "ript:prevpage();><FONT style=\"font-size:9pt;font-family: Arial;\">&#8592;</FONT> PREV PAGE</A></nobr>";
                        } else {
                                bottomthehtml+= "&nbsp;";
                        }

                        bottomthehtml+= "</TD><TD align=\"middle\"  width=10%><center><nobr>" + footer() + "</nobr></center></TD><TD width=40% align=right>";

                        if (grange != "outofrange"){
                                bottomthehtml+= "<nobr><A HREF='' onclick='nextpage(); return false;' name=bottomnext>NEXT PAGE <FONT style=\"font-size:9pt;font-family: Arial;\">&#8594;</FONT></A>&nbsp;&nbsp;</nobr></DIV>";
                                //reset the page numbersw

                        } 
                        bottomthehtml+= "</TD></TR></table>";
			$('pagingrow').innerHTML =  bottomthehtml;


                        // preload next page worth of images
                        lastimage=cnt;
                      	if($('pixperpage')){
				prestart = endnumber - 1;
				preend=(lastimage + parseInt($F('pixperpage')));
                       		if(startnumber==0){
					var delay=6000 + parseInt($F('pixperpage') * 30);
                       		         self.setTimeout("preloadnextpage()",delay);
                       		} else {
					var delay=1000;//delay just a bit to make several next page load requests have time to catch up
                       		         self.setTimeout("preloadnextpage()",delay);
                        	}
			}
                }
        } else {
                //ss mode
                enlarge2(id[0],0); // new page and slideshow mode
        }


        currentpagenum = Math.ceil(         (      Number(snum) + Number(startnumber)         ) /      parseInt($F('pixperpage'))            );
        buildpages(startnumber,endnumber,snum);
	iconstatus();
};

 function iconstatus(){
 	if(viewmode && typeof(iconbackground) != 'undefined'){
 		//clear them
 		if($('iconlist')){$('iconlist').style.background='none';}
 		if($('iconbig')){$('iconbig').style.background='none';}
 		if($('icontiny')){$('icontiny').style.background='none';}
 		if($('iconmed')){$('iconmed').style.background='none';}
 		if($('iconhuge')){$('iconhuge').style.background='none';}
 		if($('iconlarge')){$('iconlarge').style.background='none';}
                 //set it
 		if(viewmode == 'table'){
 			if($('iconbig')){$('iconbig').style.background=iconbackground;}
                 } else  if(viewmode == 'list'){
 			if($('iconlist')){$('iconlist').style.background=iconbackground;}
                 } else  if (viewmode == 'tiny'){
 			if($('icontiny')){$('icontiny').style.background=iconbackground;}
                 } else if (viewmode == 'med'){
 			if($('iconmed')){$('iconmed').style.background=iconbackground;}
                 } else if (viewmode == 'huge'){
 			if($('iconhuge')){$('iconhuge').style.background=iconbackground;}
                 } else if (viewmode == 'large'){
 			if($('iconlarge')){$('iconlarge').style.background=iconbackground;}
                 }
         }
 };

//END


function writesimilar(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased) { 
	if (typeof(writesimilar_custom) == 'function')
		return writesimilar_custom(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased);
	else
		return writesimilar_standard(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased);

}

function writesimilar_standard(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased) { 
	myhrdlink = ( myhrdlink || '' );
	myreleased = ( myreleased || '' );
        var simlist =st[showid];
        var simarray=simlist.split(" ");
 	var temparray = simarray[1].split(",");
 	if(temparray.length > 1){temparray=simarray[0] + ' ' + temparray.join(' ');simarray=temparray.split(' ');}
 	var simcount =simarray.length;
 	if(mode =='normal' || mode=='huge'){
         	if(parseInt(simcount) < 5 ){simindicator=simcount;} else {simindicator=4;}
 	} else {
         	if(parseInt(simcount) < 4 ){simindicator=simcount;} else {simindicator=3;}
 	}

         var thehtml='';
         var wmyid = myid;
     var setid = myid;
     var iconheight=15;var iconwidth=15;
 
         if (action == 'next'){
 
                 var n=sw[showid];
                 n++;
                 sw[showid] = n;
                 if(sw[showid] >= simcount) { sw[showid]=0;n=0;}
                 wmyid = simarray[n];
 
         } else if (action == 'prev'){
                 var n=sw[showid];
                 n--;
                 sw[showid] = n;
                 if(sw[showid] < 0) { sw[showid]=simcount - 1;n=simcount - 1;}
                 wmyid = simarray[n];
         }
 	//empty array fix for a single image returned which is a similar
 	if ( isNaN((sw[showid] + 1)) )
 		sw[showid] = 0;
 		var theight = 172 + adminheight;
         if (mode == 'list' || mode == 'editing'){
                 thehtml += '<TABLE width=298 cellspacing=2 cellpadding=0 border0 height=' + theight + '><TR><TD valign=top width=149 align=center>';
         }
         // similar graphics zzz
         thehtml += '<table cellpadding=0 cellspacing=0 border=0><TR><TD colspan=2 align=right valign=bottom bgcolor=#c9c9c9 width=18 height=18>';
         thehtml += '<a href="javasc' + 'ript:enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\', \''+wmyid+'\');" TITLE="ID:' + wmyid;
         if(showphotographer == 1){'  \r&copy; ' + myphotographer;}
         if(showfilesize){thehtml += '  \rSIZE: '+ myfilesize;}
         thehtml += '  \r' + 'CAPTION: ' + myshortcaption;
         if (mode == 'huge'){
                 thehtml += '"><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/420/60/' + wmyid + '.JPG" border="0" alt="loading..." height="190"></a></TD>';
         } else if( mode == 'med'){
                 iconheight=10;iconwidth=14;
                 thehtml += '"><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + wmyid + '.JPG" border="0" vspace="0" hspace="0" alt="loading..." height=72></a></TD>';
         } else if( mode == 'tiny'){
                 iconheight=8;iconwidth=12;
                 thehtml += '"><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + wmyid + '.JPG" border="0" vspace="0" hspace="0" alt="loading..." height=45></a></TD>';
 
         } else {
 				iconheight=12;iconwidth=16;
                 thehtml += '"><img src="http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + wmyid + '.JPG" border="0" vspace="0" hspace="0" alt="loading..."></a></TD>';
         }
         //simindicator="";
 
         thehtml += '<TD background=/graphics/similars_rc' + simindicator + '.gif valign=top width=9><IMG SRC=/graphics/similars_ru' + simindicator + '.gif width=12 height=9></TD></TR><TR height=8>';
         if(mode == 'normal' || mode=='huge' || mode=='large'){
 		thehtml += '<TD background=/graphics/similars_ll' + simindicator + '.gif height=8 width=12></TD><TD background=/graphics/similars_lc' + simindicator + '.gif height=8><div style="width: 18px;height:8px;padding:0;margin:0;"></DIV></TD>';
 	} else {
 		thehtml+='<TD colspan=2 background=/graphics/similars_lc' + simindicator + '.gif height=8></TD>';
 	}
 	thehtml += '<TD width=12 height=8 background=/graphics/similars_lr' + simindicator + '.gif></TD></TR></TABLE>';
 
         if(mode == 'normal' || mode =='med' || mode == 'tiny' || mode=='large'){
                 thehtml += '<Table cellpadding=0 cellspacing=0 border=0><TR><TD valign=top align=center>';
         }
         if(mode != 'editing')
         {
        		thehtml += '<DIV class=icons><a href="" onclick="lightbox_addto(\'' + wmyid + '\'); return false;" class=iconlink title="Add to your current lightbox">LB+</a>';
         	thehtml += '<a href="" onclick="return price_image(\'' + wmyid + '\',\''+rm[wmyid]+'\');" class=iconlink Title="Price Image">$</a>';
         	thehtml += '<a href="javasc' + 'ript:enlarge2(\'' + wmyid + '\'' + ',' + '\'' + showid + '\');" class=iconlink title="Enlarge image and more info"><font class=eye>i</font></a>';
         	if(mode == 'huge'){
                 	//thehtml += '<font class=xsmall>' + wmyid + '</font>&nbsp;&nbsp;' + (myhrdlink ? '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>' : '')+'&nbsp;&nbsp;';
 		} else if (mode == 'list') {
 			thehtml += '&nbsp;&nbsp;'+ (myhrdlink ? '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>' : '')+'</DIV>';
         	} else {
         		thehtml += '</DIV>';
 		}
 	}
 
         /* if(mode == 'normal' || mode =='med' || mode == 'tiny' || mode =='large'){
            thehtml += '<BR>';
         } */
 
         if(mode =='med' || mode == 'tiny'){
                 thehtml += '<font class=xsmall>' + wmyid + '</font>';
                 thehtml += '</TD><TD valign=top align=center width=40><nobr>';
         }
         if (mode == 'list' || mode == 'normal' || mode=='large' || mode == 'editing'){
                 thehtml += '</TD><TD valign="top">';
         }

         thehtml += '<A HREF="" onclick="writesimilar(\'' + setid + '\',\'' + showid + '\',\'';
         thehtml += myphotographer + '\',\'';
         thehtml += myshortcaption + '\',\'prev\',\'' + mode + '\', \'' + myhrdlink + '\',\'' + myreleased + '\'); return false;" TITLE="show similars">';
         thehtml += '<IMG SRC="/graphics/similars_prev.gif" border="0" hspace="1" height="' + iconheight + '" width="' + iconwidth + '" align="absmiddle"></A>';

         if (mode == 'list' || mode == 'huge' || mode == 'normal' || mode=='large' || mode == 'editing'){
                 thehtml += '<font class=xsmall>' + (sw[showid] + 1) + ' of ' + simcount + '</font>';
         }
 
         thehtml += '<A HREF="" onclick="writesimilar(\'' + setid + '\',\'' + showid + '\',\'';
         thehtml += myphotographer + '\',\'';
         thehtml += myshortcaption + '\',\'next\',\'' + mode + '\', \'' + myhrdlink + '\',\'' + myreleased + '\'); return false;" TITLE="show similars">';
         thehtml += '<IMG src="/graphics/similars_next.gif" border="0" hspace="1" height="' + iconheight + '" width="' + iconwidth + '" align="absmiddle"></A></nobr><BR>';


         if (mode =='med' || mode == 'tiny'){
                 thehtml += '<font class=xsmall>' + (sw[showid] + 1) + ' of ' + simcount + '</font>';
         }
 
         if (mode == 'list' || mode == 'editing'){
                 thehtml += '<font class=xsmall>ID:' + wmyid;
                 if(showphotographer == 1){thehtml +='  <BR>&copy; '+currentYear+' ' + myphotographer;}
                 if(showfilesize){thehtml += '<nobr>' + myfilesize + '</nobr>';}
                 thehtml += myreleased + '<BR>CAPTION: ' + myshortcaption + '</font><BR>';
 
                 if (mode == 'editing') {
                 	thehtml += '<br/><a href="" onclick="launchwin(\'/SwishSearch?show_all=1&similar_to='+wmyid+'\', \'edit sims\', 600, 800, 100, 100); return false;" title="Edit Similar Images">Edit&nbsp;Similar&nbsp;Images</a>';
                 }
 
         }
 	if (mode== 'huge'){
 		thehtml += '</DIV>';
 	}
         thehtml += '</td></TR></TABLE>';
        
	if( myhrdlink ) 
	thehtml += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';
 
         if (action == 'start'){
                 return thehtml;
         }
         if (action == 'prev'){
                 MM_setTextOfLayer( 'd' + setid,'',thehtml);
         }
         if (action == 'next'){
                 MM_setTextOfLayer( 'd' + setid,'',thehtml);
         }
 };
 

//END2

 function currentpage(){
         if($('cdheader'))
              $('cdheader').style.display = 'block';

	setuppagesize(); 	
	if (document.currentLayer1Mode == 'searchresults')
	{
            	var section = $H({ snum:( firstpictureonpage ? firstpictureonpage : 0 ), viewmode:viewmode, buildmode:'', resized:'' });
            	//we don't want to register a backpage event on resize, so call the worker directly.
            	dispatchBuildimages(section);
	}

	else if (document.currentLayer1Mode == 'cartview')
	{
		
		cart_display();
	}



	createCoverLayer();
	$('coverlayer').style.width = winW + 'px';
	if($('Layer1')){
		if (document.currentLayer1Mode != 'cartview' && document.currentLayer1Mode != 'enlarge' )
			$('Layer1').style.overflow = 'hidden';
		$('Layer1').style.width = '100%';
		$('Layer1').style.height = ( document.currentLayer1Mode == 'cartview' || document.currentLayer1Mode == 'enlarge' ? truevertHeight : winH ) + 'px';

		if($('lbbuttons'))
		{
			$('coverlayer').style.height = 	(Element.getHeight("Layer1") + Element.getHeight("row2") + Element.getHeight("cdheader") ) + ( (covertopadjust) ? covertopadjust : 0) + ( (coverbottomadjust) ? coverbottomadjust : 0) + 'px';
		}
		else
		{
			$('coverlayer').style.height = (winH + 30) + 'px';
		}
		if($('cdheader')){
			if(Position.cumulativeOffset($('cdheader'))[1] > 0){
			//qq('cdheader top' + Position.cumulativeOffset($('cdheader'))[1]);
			$('coverlayer').style.height = 	(Element.getHeight("Layer1") + Element.getHeight("row2") + Element.getHeight("cdheader") ) + ( (covertopadjust) ? covertopadjust : 0) + ( (coverbottomadjust) ? coverbottomadjust : 0) + 'px';
			}
		}
		$('coverlayer').style.width = Element.getWidth("Layer1");
		var co = [];
                if ( $('row2') ){
                        co = Position.cumulativeOffset($('row2'));
		}
		
		if($('cdheader') && Position.cumulativeOffset($('cdheader'))[1]>0){
			co=Position.cumulativeOffset($('cdheader'));
		}
                else if ( $('navContainer') )
                {
                        co = Position.cumulativeOffset($('navContainer'));
                        co[1] += $('navContainer').getHeight();
                }

		$('coverlayer').style.top = (co[1] - ( (covertopadjust) ? covertopadjust : 0)) + (Position.cumulativeOffset($('cdheader'))[1] < 1 ? ( (typeof(covertopadjust) != 'undefined') ? covertopadjust : 0) : 0) + 'px';
		$('coverlayer').style.left = co[0]  + 'px';
		var temptop = (trueh - Element.getHeight("LBdiv") -1);	
	}
};

function setuppagesize(){
	adminheight = 0;
	if( typeof(hrdl) != 'undefined' && hrdl[0] && hrdl[0] !=''){
                if (typeof(viewmode) != 'undefined' && viewmode == 'editing')
                        adminheight=0;
                else
			if(typeof(adminheight_custom) != 'undefined'){adminheight=adminheight_custom} else {adminheight=11;}
	} 

	if(typeof(shcon) == 'object' && shcon[0] && shcon[0] !='') {
		adminheight+=11;
	}

	if ( $('Layer1') )
	{
		winW = Element.getWidth('Layer1');
	}
	else
	{

	    if(self.innerWidth ){
		winW = self.innerWidth;
	    } else {
		winW = document.body.offsetWidth - 0;
	    }

	}

	if  (self.innerHeight){
		trueh = self.innerHeight;
	}
	else {
		trueh = document.body.offsetHeight - 0;
	}

            if (document.documentElement.clientHeight && document.documentElement.clientHeight > trueh && (typeof(viewmode) != 'undefined' && (viewmode != 'med' || yourBrowse == 'IE' ) ))
            {
                trueh = document.documentElement.clientHeight - 0;
            }

	
	truew = winW;
	safetyspace = 16;
	menuheight = 20;
	winH = parseInt(trueh) - ( $('row2') ? (parseInt(Element.getHeight("row2")) + Position.cumulativeOffset($('row2'))[1]) : 20 );

	if(document.currentLayer1Mode == 'enlarge')
	{
		winH = winH - safetyspace;
	}
	else
	{
	 	winH = winH - safetyspace - menuheight;
	}

	//tweakheight -- if you just can't get it right:
	if (typeof(tweakheight) != 'undefined' && tweakheight != 0)
		winH = winH - tweakheight;

	if(gsession){//logged in
//switched to fixed lb height, 
		if(document.getElementById('LBdiv')){//lightbox is present measure height
			var lbh = parseInt(Element.getHeight("LBdiv"));
			if(lbh < 140 && ! ( lbdisplaymode == 1 && viewmode == 'editing') ){//be safe and leave room unless we're hiding the LB
				winH = winH - 140;
			} else {
				winH = winH - lbh;
			}
		} 
	}
	if (typeof(setuppagesize_cellsizes_custom) == 'function')
	{
		setuppagesize_cellsizes_custom(); //this function must init the same globals as in the base case below:
	}
	else
	{

	    imagerows=Math.floor(winH/(176 + adminheight));
	    imagespaceheight=imagerows * (176 + adminheight);
	    area=imagerows * Math.floor(winW/152);
	    if(! viewmode && imagerows == 1)
	    { 
		viewmode='med';
		gsetCookie('gviewmode','med', '', '/', gGetCookieDom());
	    }

	    if(viewmode){
		if(viewmode == 'table'){
			imagerows=Math.floor(winH/(176 + adminheight));
			if(imagerows == 0)
				imagerows=1;
			imagespaceheight=imagerows * (176 + adminheight);
			area=imagerows * Math.floor(winW/152);
		} else  if(viewmode == 'editing'){
                        imagerows=Math.floor(winH/(160 + adminheight));
                        if(imagerows == 0)
                                imagerows=1;
                        imagespaceheight=imagerows * (160 + adminheight);
                        area=imagerows * Math.floor(winW/300.00);
                } else 	if(viewmode == 'list'){
			imagerows=Math.floor(winH/(172.00 + adminheight));
			if(imagerows == 0)
				imagerows=1;
			imagespaceheight=imagerows * (172 + adminheight);
			area=imagerows * Math.floor(winW/300.00);
		} else 	if (viewmode == 'tiny'){
			imagerows=Math.floor(winH/(106.00 + adminheight));
			if(imagerows == 0)
				imagerows=1;
			imagespaceheight=imagerows * (106 + adminheight);
			area=imagerows * Math.floor(winW/96.00);
		} else if (viewmode == 'med'){
			imagerows=Math.floor(winH/(130.00 + adminheight));
			if(imagerows == 0)
				imagerows=1;
			imagespaceheight=imagerows * (130 + adminheight);
			area=imagerows * Math.floor(winW/140.00);
		} else if (viewmode == 'huge'){
			imagerows=Math.floor(winH/(220.00 + adminheight));
			if(imagerows == 0)
				imagerows=1;
			imagespaceheight=imagerows * (220 + adminheight);
			area=imagerows * Math.floor(winW/330.00);
		} else if (viewmode == 'large'){
			imagerows=Math.floor(winH/(199.00 + adminheight));
			if(imagerows == 0)
				imagerows=1;
			imagespaceheight=imagerows * (199 + adminheight);
			area=imagerows * Math.floor(winW/187.00);
		}
			
	    }
	}


/*	if(document.currentLayer1Mode == 'enlarge'){
			imagespaceheight=winH - menuheight;
		} */
	truevertHeight = winH;
	//winH=imagespaceheight + menuheight; // restore it to accomodate narrowbar and footer // it's already limited.. this crop is too close..
	if(winH<450){
		smallscreen=1;
	}
	if(area > 0){
		totalimagesthatcanfit=area;
		gpixperpagev=totalimagesthatcanfit;
		$('pixperpage').value = gpixperpagev;
	} else {
		// load images per page into field
		gpixperpagev = ggetCookie('gpixperpage');
		if(! gpixperpagev)
			gpixperpagev=12;
	}


	//set up coverlayer
        createCoverLayer();
        $('coverlayer').style.width = winW + 'px';

                if($('lbbuttons'))
                {
                        $('coverlayer').style.height =
                        ( Position.cumulativeOffset($('lbbuttons'))[1] - Position.cumulativeOffset($('row2'))[1]  + Element.getHeight("lbbuttons") ) + 'px';// + 'px';//$('Layer1').style.height;
                }
                else
                {
                        $('coverlayer').style.height = (winH + 30) + 'px';
                }

                var co = [];
                if ( $('row2') )
                        co = Position.cumulativeOffset($('row2'));
                else
                {
                        co = Position.cumulativeOffset($('navContainer'));
                        co[1] += $('navContainer').getHeight();
                }


                $('coverlayer').style.top = co[1] + 'px';
                $('coverlayer').style.left = co[0]  + 'px';


};

function preloadnextpage(){
        preloadcurrent=prestart;
        preloadnextimg();
};

function preloadnextimg(){
        preloadcurrent++;
        // preload till the next page's images are loaded and stop preloading if next page is clicked
        if(preloadcurrent < preend && endnumber < preend){
                objImage = new Image();
		Event.observe(objImage, 'load', function() { setTimeout("preloadnextimg();",10) });
                objImage.src='http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/' + id[preloadcurrent] + '.JPG';
        }
};

function nextpage(){
        buildimages(lastimage,"next");
};

function prevpage(){
        backpagestart=lastimage - ( 2 * parseInt($F('pixperpage')));
        if((backpagestart) < 0){ // past this set of images
                if((backpagestart + snum) < 0){
                        prevtogoto=0;
                } else {
                        prevtogoto=Number(snum) + Number(backpagestart); // go back two pages from start page
                        gsetCookie('gwhichstartpage','0', '', '/', gGetCookieDom());
                        if(prevtogoto < 0 ){ prevtogoto=0;}
                }
                var section = $H({ showstart:1, snum:0, viewmode:viewmode }).toJSON();
                self.location=nextlink + 'snum=' + prevtogoto + '#nav='+section;

        } else { //within this set of images
                buildimages(backpagestart,"prev");
        }
};

function footer(){
	if (typeof(customfooter) != 'undefined')
		return customfooter;
	else
		return Templates.footer__body.evaluate({currentyear: currentYear});
};

function tellme(){
        setuppagesize();
        alert($F('pixperpage') + " browser is " + browser + " and os is " + OS + 
				" width=" + document.body.offsetWidth + "," + self.innerWidth + "," + winW +
				" winH="+winH+", truevertHeight="+truevertHeight
				);
};

//////preview functions////zpp///

function previewset(){
	tset = document.page.previews.options[document.page.previews.selectedIndex].value;
        var date = new Date();
        date.setTime(date.getTime()+(60*24*60*60*1000));
        gsetCookie('gpreviews',tset,date, '/', gGetCookieDom());
};

function prloadimg(prid,crop){
	if (! $("pimid"))
		document.body.appendChild( Builder.node('div',{id:'pimid',style:'position:absolute; top:-500px'}) );
	
	var theImgAttrs = $H({
		id:'previewimg_' + prid, src:'/graphics/loading.png', border:0, alt:'Loading...', lowsrc:'/graphics/spacer.gif'
	});	
	if(winH < 450){
		smallscreen=1;
		if(typeof(crop)!= 'undefined'){//smallscreen using orientation to decide limiter
			if(crop=='panoramic'){
				theImgAttrs['width'] = 420;
			} else if(crop=='vertical'){
				theImgAttrs['height'] = ((winH - 100) < 180) ? 180 : (winH - 100);
			} else {
				theImgAttrs['height'] = ((winH - 142) < 160) ? 160 : (winH - 142);
			}
		} else {
			theImgAttrs['height'] = 135;
		}
	} else {
		smallscreen=0;
	}
	$("pimid").innerHTML = '';
	
	$('pimid').style.visibility="hidden";
	var theNode = 
	Builder.node('div', {id:'previewpaneshadow2'},[
 		Builder.node('div',{id:'previewpaneshadow1'},[
 			Builder.node('div',{id:'previewpane'},[
		 		Builder.node('div', {style:'padding: 2px 2px 2px 2px;', align:'center'},
     					[ Builder.node('img', theImgAttrs) ]
				),
     				Builder.node('div',{id:'previewpane_metdat_'+prid},'')
		     	]),
			Builder.node('img', {src:'http://globaldyn.ipnstock.com/'+dynimagesname+'/420/60/' + prid + '.JPG', style:'display:none', onload:"if($('previewimg_"+prid+"')) $('previewimg_"+prid+"').src = this.src"})
		])
	]);
	$("pimid").appendChild(theNode);
};

function sp(oObj, imageid, imagenum, mode) { //was wrapper func to make asynch call before rendering, now just calls sp_act as all info is stored within the page
	if (oObj.id)
		currMousedOverObj = oObj.id;

	if ( currMousedOverObj != id[imagenum] ) //not in page
		ajax_JSON( '/AjaxHandlers/ImageInfo/'+imageid+'.json', getpost, null ); //even if it's off make the call anyway to cache

 	sp_act(oObj.id, imageid, mode, imagenum, 0);
};


function mouseSnap(e) { 
	if (typeof(event) == 'undefined')
	{
		document.mouseLocSnapX = Event.pointerX(e);
		document.mouseLocSnapY = Event.pointerY(e);
	}
	else
	{
		document.mouseLocSnapX = Event.pointerX(event);
		document.mouseLocSnapY = Event.pointerY(event);
	}
};

function sp_act(oObjId, imageid, mode, dex, tryCtr){  //imagename, imagenum, license, photographer, 
	//pshown=1;

	if( (! $('previewsSel').selectedIndex || $('previewsSel').selectedIndex != 1) && suspendpreviews==0)
	if(mode == 'on')
	{
		//grab current mouse pos quick
		Event.observe(document, 'mousemove', mouseSnap);
		setTimeout("Event.stopObserving(document, 'mousemove', mouseSnap)", 200);


		Event.observe(document, 'mousemove', pfindmouse);
		if (	(oObjId == currMousedOverObj ) &&
			( ( document.ajaxLoaded && imageid == document.JSONobj.getImgDat('id') ) || imageid == id[dex] )	) {

			var temp = true;
			
			gloCrop = ( imageid == id[dex] ? crp[dex] : document.JSONobj.getImgDat('crop') );
			gloCrop = ( gloCrop ? gloCrop : 'horizontal' );
			var crop = gloCrop;
			//SMALL SCREEN HACK
			if(smallscreen=='1' && (crop=='panoramic' || crop=='vertical')){
				prloadimg(imageid,crop);
			}
			
			var file_size = ( imageid == id[dex] ? fs[dex] : document.JSONobj.getImgDat('file_size') );
			if (file_size < 5){file_size='';} else if (! file_size.toString().match(/[A-Za-z]/)){file_size += 'Mb';} //something wrong do not show or it already has size info

			var dimensions = ( typeof(showdimensions) != 'undefined' ? ( imageid == id[dex] ? dim[dex] : document.JSONobj.getImgDat('dimensions') ) : '');
			if (dimensions) //comes as <XVAL>x<YVAL>
			{
				var dimr = dimensions.match(/^(\d+)x(\d+)$/);
				if (dimr != null && dimr.length > 1)
					dimensions = '[&nbsp;'+dimr[1]+'px&nbsp;x&nbsp;'+dimr[2]+'px&nbsp;]';	
			}
			
			var tempshortcaption = ( imageid == id[dex] ? unescape(scp[dex]) : document.JSONobj.getImgDat('short_caption') );	//=spcap;
			if(tempshortcaption && tempshortcaption.length > 130)
			{
				var tsc='';
				for(z=0; z < 170; z++)
				{
					var c = tempshortcaption.charAt(z);
					if(temp == true)
					{
						if((z > 130) && (c == ".")){
							temp = false;
							tsc+=c + " ...";
						} else if((z > 150) && (c == " ")){
							temp = false;
							tsc+=" ...";
						} else {
							tsc+= c;
						}
					}
				}
				tempshortcaption = tsc;
			}
		
			var displayimageid = '';	
			if ( typeof(o) == 'object' && typeof(o[dex]) != 'undefined'){
				displayimageid= ( imageid == id[dex] ? o[dex] : document.JSONobj.getImgDat('orig_id') );
			} 
			else {displayimageid=imageid;}
			
			var rmrftype = ( imageid == id[dex] ? rm[dex] : document.JSONobj.getImgDat('rmrftype') );
			var photographer = ( imageid == id[dex] ? unescape(pho[dex]) : document.JSONobj.getImgDat('photographer') );
			var image_restrictions = ( imageid == id[dex] ? imr[dex] : document.JSONobj.getImgDat('image_restrictions') );
			image_restrictions = ( image_restrictions ? ' :: <span style="color:#990000"> This image has restrictions. Click to View </span>' : '' );
			//oObjId == currMousedOverObj
			var tdata = {
				imageid: imageid,
				displayimageid: displayimageid,
    				rmrftype: rmrftype,
				filesize: file_size,
    				shortcaption: tempshortcaption,
				dimensions: dimensions,
				photographer: photographer,
    				imagerestrictions: image_restrictions
			};
			
			//RENDER!
			$('previewpane_metdat_'+imageid).innerHTML = Templates.sp_act__metadata.evaluate(tdata);
					
			$('pimid').style.visibility="visible";
			//pshown=2;
			new Effect.Appear($('pimid'), {duration:0.1});
			
		}
		else if (tryCtr < 10) // effectively, try 10 times to get ajax data... waiting a max of 10 * 250 ms
		{
			tryCtr++;
			setTimeout("sp_act('"+oObjId+"', '"+imageid+"', '"+mode+"', '"+dex+"', '"+tryCtr+"')", 250);
		}
	}
};

function hpoff(){	
	if(currMousedOverObj == '' || ! currMousedOverObj){
		if(typeof(mouseX)!='undefined' && mouseX > parseInt(portSize()[0]/2))
			$('pimid').style.left = '-500px';
		else
			$('pimid').style.top = '-750px';
	}
	else // user action has moved to a new location during timeout..
	{
		new Effect.Appear('pimid', {duration:0.1, from:Element.getOpacity($('pimid'))});
	}
};

function hp(){
	currMousedOverObj = '';
	Event.stopObserving(document, 'mousemove', pfindmouse);
	if (!$('pimid'))
		return;
	new Effect.Fade('pimid', {duration: 0.3, from:Element.getOpacity($('pimid'))})
	setTimeout("hpoff()",300);
};


function portSize() {
	var retY = parseInt(document.body.offsetHeight - 20);
	var retX = parseInt(document.body.offsetWidth - 20);

	var iX = window.innerWidth;
	var iY = window.innerHeight;

	retX = ( iX < retX ? iX : retX);
	retY = ( iY < retY ? iY : retY); //we want smaller of 2 anyway, also pseud-crossbrowser as a result...

	return [retX, retY]; //X x Y
};

function pfindmouse(e, sX, sY){
	if($('pimid')) { //pshown!=0 && 
 		var xcoord=pmousedelta[0];
 		var ycoord=pmousedelta[1];

		mouseX = (sX || 0); 
		mouseY = (sY || 0);
		var theTar;
		if (typeof(event) == 'undefined')
		{
			//mouseX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
			//mouseY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
			mouseX = Event.pointerX(e);
			mouseY = Event.pointerY(e);

			theTar = e.target;
		}
		else //IE
		{
			//mouseX = event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
			//mouseY = event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
			mouseX = Event.pointerX(event);
			mouseY = Event.pointerY(event);
			theTar = event.target;
		}

		//check to see if we need to bail out...
		if (Math.abs(mouseX - document.mouseLocSnapX) > 150 || Math.abs(mouseY - document.mouseLocSnapY) > 150)
		{
			hp();
		}
		else
		{

			//keep it in the viewport...

 			var primHt = 60;
 			if(theTar && theTar.nodeName == 'IMG')
 				primHt = Element.getDimensions(theTar)['height'];
		
			if ((mouseX + Element.getDimensions($('pimid'))['width']) > winW)
			{	xcoord = (mouseX - Element.getDimensions($('pimid'))['width'] - pmousedelta[0] - 45);	}
			else
			{	xcoord += mouseX;	}
			if(xcoord < 0 ){xcoord = pmousedelta[0];}

			if ((mouseY - Math.min(primHt, 420) + pmousedelta[1] - 20) < document.body.scrollTop)
			{	ycoord = document.body.scrollTop - pmousedelta[1];			
				
				if ((ycoord + 40) > winH)
				{	ycoord = (ycoord - Math.min(primHt, 420)+ pmousedelta[1]);
					if ( ((ycoord + Math.max(primHt, 420) - document.body.scrollTop) - winH) > 0)
					{
						ycoord = ycoord - (typeof(event) == 'undefined' ? Math.min((primHt+160), 420) : (gloCrop == 'panoramic' || (gloCrop != '' && gloCrop !='vertical') ? 190 : 380));	 //ie can't find heights properly.. so rely on crop..
					}
				}
			
			}
			else if ((mouseY + Math.max(primHt, 420)) > winH)
			{	ycoord = (mouseY - Math.min(primHt, 420)+ pmousedelta[1]);

				if ( ((ycoord + Math.max(primHt, 420) - document.body.scrollTop) - winH) > 0)
				{
					ycoord = ycoord - (typeof(event) == 'undefined' ? Math.min((primHt+160), 420) : (gloCrop == 'panoramic' || (gloCrop != '' && gloCrop !='vertical') ? 190 : 380));	 //ie can't find heights properly.. so rely on crop..
				}

				if (ycoord < document.body.scrollTop)
				{	ycoord = document.body.scrollTop - pmousedelta[1];	}
			 }
			else
			{	ycoord += mouseY;	
				if ((ycoord + 40) > winH)
				{	ycoord = (ycoord - Math.min(primHt, 420)+ pmousedelta[1]);
					if ( ((ycoord + Math.max(primHt, 420) - document.body.scrollTop) - winH) > 0)
					{
						ycoord = ycoord - (typeof(event) == 'undefined' ? Math.min((primHt+160), 420) : (gloCrop == 'panoramic' || (gloCrop != '' && gloCrop !='vertical') ? 190 : 380));	 //ie can't find heights properly.. so rely on crop..
					}
				}
			}


 	 		$('pimid').style.left = parseInt(xcoord) + "px";
  			$('pimid').style.top  = parseInt(ycoord) + "px";
		}
	}
};

/////////////////////
function dispatchAll(oContent,init){
        var oC = (typeof(oContent) == 'object' ? oContent : oContent.evalJSON() ); 
	var fpop = ( typeof(firstpictureonpage) != 'undefined' ? firstpictureonpage : 0 );

        if(oC.viewmode == 'ss' ) {
		dispatchEnlarge2(oC);
	} else if ( oC.viewmode == 'cartview' || cartview ) {
                document.currentLbdivMode = 'cart';
                document.currentLayer1Mode = 'cartview';
		viewmode = 'cartview';
                currMousedOverObj = 'shop_cart';
		dispatchCart_display(oC);
        } else if ( oC.snum < fpop ) {
		document.currentLayer1Mode = oC.viewmode;
		viewmode = oC.viewmode;
                //buildimages(oC.snum, 'prev');
		oC['buildmode'] = oC['buildmode'] || 'prev';
		dispatchBuildimages(oC);
        } else if ( oC.snum > fpop ) {
		document.currentLayer1Mode = oC.viewmode;
		viewmode = oC.viewmode;
                //buildimages(oC.snum, 'next');
		oC['buildmode'] = oC['buildmode'] || 'next';
		dispatchBuildimages(oC);
        } else if ( oC.snum == fpop ) {
		document.currentLayer1Mode = oC.viewmode;
		viewmode = oC.viewmode;
		//buildimages(oC.snum,'current');
		oC['buildmode'] = oC['buildmode'] || 'current';
		dispatchBuildimages(oC);
	}


};

function reDispatch() {
	dispatchAll(YAHOO.util.History.getCurrentState());
};

function MM_setTextOfLayer(objName,x,newText) { //v4.01
  var obj = $(objName)
  if (obj != null) 
  {
	//also clear sister 'pagingrow'
	if($('pagingrow') && document.currentLayer1Mode != 'searchresults')
		$('pagingrow').innerHTML = '';

	if (document.layers) {document.write(unescape(newText)); document.close();}
	else { obj.innerHTML = unescape(newText); }
  }
};

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
};

function toplightboxrefresh() {
	if(gsession){
		self.location="/SwishSearch?n=1&lb_view=1";
	} else {
		self.location = '/bin/Cklb?ref=/SwishSearch?lb_view=1';
	}
};

function topcartrefresh() {
	if(gsession){
		self.location="/SwishSearch?n=1&cartview=1";
	} else {
		self.location="/bin/Cklb?ref=/SwishSearch?cartview=1";
	}
};

/////////admin functions //////////////////////////
function displayWindow(url, width, height) {
	if (navigator.appName == 'Netscape'){
		height = parseInt(height) + 16;
	}
	var Win = window.open(url,"displayWindow",'width=' + width + ',height=' + height + ',resizable=1,scrollbars=yes,menubar=no,status=no' );
	Win.focus();
};

function displayWindow2(url, width, height) {        
	var Win2 = window.open(url,"displayWindow2",'width=' + width + ',height=' + height + ',resizable=0,scrollbars=yes,menubar=no,status=no' );
	Win2.focus();
};

///////////////js functions for search //////////////////////////
function optimize() {
        var searchthreshhold = 60;
        var thehtml='';
        if (optimizemenu == 1 && pagetype=='search'){
			if (searchthreshhold < total){
							thehtml+='<TABLE cellspacing=0 cellpadding=1 border=0>';
							thehtml+='<FORM name="optimizer" action="#">';
							thehtml+='<TR><TD>';
							thehtml+='<SELECT NAME="narrow" ONCHANGE="narrowit(this.form.narrow.options[this.form.narrow.selectedIndex].value);" class="smallmenu">';
							thehtml+='<OPTION VALUE="#">Narrow your search results';
							thehtml+='<OPTION VALUE="colorgray">Remove black and white images';
							thehtml+='<OPTION VALUE="colorrgb">Remove color images';
							thehtml+='<OPTION VALUE="imagehasrestrictions">Remove restricted images';
							thehtml+='<OPTION VALUE="orientationvertical">Remove verticals';
							thehtml+='<OPTION VALUE="(orientationhorizontal+OR+orientationpanoramic)">Remove horizontals';
	
							if(spec_idx != 'ed'){
									thehtml+='<OPTION VALUE="lowres">Remove small scans (< 30 Mb)';
							}
							thehtml+='<OPTION VALUE="agefiveyears">Only show recent images (<5 yrs)';
							thehtml+='<OPTION VALUE="agetenyears">Remove very old images (>10 yrs)';
							thehtml+='</SELECT></td></tr></form></table>';
							thehtml+='';
	
			} else {
	
							thehtml+='';
							thehtml+='<FORM name="optimizer" action="#"><SELECT NAME="narrow" ONCHANGE="expandit(this.form.narrow.options[this.form.narrow.selectedIndex].value);" class="smallmenu">';
							thehtml+='<OPTION VALUE="#">Expand your search results';
							thehtml+='<OPTION VALUE="deep">Have IPN members perform a deep search';
							if(spec_idx != 'ne'){
									thehtml+='<OPTION VALUE="expand">Show me the broadest set of images';
							}
							thehtml+='</SELECT></form>';
							thehtml+='';
	
			}
        }
        return(thehtml);
};

function narrowit(url) {
        if(url == "#"){
                alert('please select an item from the list');
        } else {
                var url1 = '/SwishSearch?spec_idx=' + spec_idx + '&Keywords=' + ukeys + '+NOT+' + url;
                self.location=url1;
        }
};

function expandit(url) {
        if(url == "#"){
                alert('please select an item from the list');
        } else if (url == "deep" ) {
                var url1 = '/deepsearch.shtml';
                self.location=url1;
        } else {
                var url1 = '/SwishSearch?synsearch=true&spec_idx=ne&Keywords=' + ukeys;
                self.location=url1;
        }
};

function checkIt(string){
        place = detect.indexOf(string) + 1;
        thestring = string;
        return place;
};


function popkeys2(oId, oLbj) {
	var topop = $(oId);
	if (topop)
	{
		if (topop.style.display == 'none')
		{
			topop.style.display = 'block';
			//top of lbbuttons - top of keyword div
			var toppos;
			if ($('lbbuttons'))
				toppos = Position.cumulativeOffset($('lbbuttons'))[1];
			else
				toppos = winH;
			
			var kwdht = toppos - Position.cumulativeOffset(topop)[1] + 'px'; 
			topop.style.maxHeight = kwdht;
			topop.style.overflowY = 'auto';
		}
		else
			topop.style.display = 'none';
	}

	if (oLbj)
	{
		if (oLbj.innerHTML == 'Show keywords')
			oLbj.innerHTML = 'Hide keywords';
		else if (oLbj.innerHTML == 'Hide keywords')
			oLbj.innerHTML = 'Show keywords';
	}
};

function gsetCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
};

function ggetCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
};

function gdeleteCookie(name, path, domain) {
  if (ggetCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

function gsetCookie2(name2,value2) {
	gsetCookie(name2, value2, '', '/', gGetCookieDom());
};

function gGetCookieDom(){
	var thisdomain = document.domain;
	var domainparts = thisdomain.split(".");
	var end = domainparts.length - 1;
	var start = domainparts.length - 2;
	var domainend = domainparts[end];
	var domainstart = domainparts[start];
	var setdom = "." + domainstart + "." + domainend;
	return setdom;
};

function gSetBackpage() {
	var thispage = '';
	if (location.href)
		thispage = location.href;
	gsetCookie('backpage', thispage, '', '/', gGetCookieDom());
};

function checkpageresize(e){
	if(self.innerWidth){
                newW = self.innerWidth - 0;
	} else if (document.body){
		newW = document.body.offsetWidth - 0;
	}

	if (newW != tempW){
		if(self.innerWidth){
			tempW = self.innerWidth - 0;
		} else {
			tempW= document.body.offsetWidth - 0;
		}

		try {
			if (currentLbdivMode == 'lightbox')
				setTimeout("lightbox_build(document.currentlbstash);",1000);
			else if (currentLbdivMode == 'cart')
				setTimeout("cart_build();",1000);
		} catch (e) {}

		setTimeout("currentpage();",1000);
	}
};

function nada(){};

function launchwin(url, tle, ht, wd, px, py){ // for popups etc (primarily used on cart page)...
	if (!tle)
		tle = "newwindow";
	if (!ht)
		ht = 590;
	if (!wd)
		wd = 550;
	if (!px)
		px = 40;
	if (!py)
		py = 40;

	var newwin = window.open( url, tle, 'height=' + ht + ',width=' + wd + ',alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=' + px + ",top=" + py);
	if (!newwin.opener) newwin.opener=( typeof(parent) != 'undefined' ? parent : self );
	if (newwin.focus) newwin.focus();
};

function hovercopyright(){
    if($('copyright')){				
		if (typeof(customhovermessage) != 'undefined' && customhovermessage != '')
			$('copyright').innerHTML = customhovermessage;
		else
		 	$('copyright').innerHTML = Templates.hovercopyright__text.evaluate({
				currentyear: currentYear,
				baseurl: baseurl
			});
    }
};

//for CHECK USAGE RATES
function license(id) {
	launchwin('/bin/Rates?calc_only=1&usage=1&ln='+id);
};

function twidle_price_img(selId, type, price) {
	setTimeout("twidle_price_img_delay("+selId+", '"+type+"', '"+price+"')", 10);
	return false;
};

//call this onload, will create a global object named urlParams.. so you access by urlParams.foo ...
function getVars() {
	if (! document.location.href.split('?')[1])
		return;

	var varArray = document.location.href.split('?')[1].split('&');

	urlParams = new Object;

	for(var x=0; x<varArray.length; x++)
	{
		var tmp = varArray[x].split('=');
		if (tmp[0])
			urlParams[unescape(tmp[0])] =  unescape(tmp[1]) ;
	}
};

function twidle_price_img_delay(selId, type, price) {
        var docold = 'lic'+selId;

	if (document[docold].loaded == 'true')
		return;
        if(type == 'RF'){
		var thyimg = new Image();
		thyimg.src = '/graphics/specify_filesize.gif';
                document[docold].src=thyimg.src;
        }

        if(price == '$ 0.00'){
        } else {
		var thyimg = new Image();
		thyimg.src = '/graphics/ready_to_license.gif';
                document[docold].src=thyimg.src;
        }
	document[docold].loaded = 'true';
	return true;
};


