 function lightbox_list_process() { 
    var images = document.JSONobj.oJSON.images.image_id;
    var originals = document.JSONobj.oJSON.images.orig_id;
    var content = originals.join('\n'); 

     var tdata = {
                  content: content,
                  images: images,
                  origs: originals,
                  currentlbname: 'Lightbox'
                 };

               $('displaypanellayer').style.top =   '100px';
                $('displaypanellayer').style.left = '200px';
                $('displaypanellayer').style.width ='292px';
                $('displaypanellayer').style.height ='349px';
                $('coverlayer').style.visibility="visible";
                $('displaypanellayer').style.visibility="visible";
            $('displaypanellayer').innerHTML = Templates.lightbox_list__body.evaluate(tdata);
	var top = new Effect.ScrollTo('navbar');


 };

 function lightbox_list(args){ // Displays a list of images in a lightbox - Milan Adamovsky

  var mode = args.mode;
  var lb = args.lb;
  var user = args.user;

  if (mode=='close')
   {
    hidedisplaypanel(1);
   } 
  else 
   {
    var d = new Date();  // This overcomes doubleposting constraint in AJAX - Milan Adamovsky 06/28/2009 Mantis # 1157 
    ajax_JSON( '/bin/UserAdmin?lb_list=' + lb + '&user=' + user + '&noise=' + d.getTime() + '&callback=lightbox_list_process()', 'GET');
 }
};


function ImageUrl(isize,iiid,iindex){
	iurl = 'http://gdynx.ipnstock.com/'+dynimagesname+ '/' + isize + '/' + iiid + '.JPG';
	
	// remote url detect
	if(typeof(iindex)=='undefined')
	{                  
		// seek the index of this particular id if it isn't already known
	        for(iii=0;iii<id.length;iii++)
		{
			if(id[iii] == iiid)
	                       iindex =iii;
	        }
	}
	
	/* 
         test for remote size available and that we're not already in a safety mode of not available at remote location
	 imagesafetymode is local "sense there is a problem with remote hosting failover";
	 if url has http it's absolute otherwise use the base path
        */

	//imagesafetymode=0;
	if(typeof(primary_turl) != 'undefined' && typeof(imagesafetymode)=='undefined' && typeof(primary_turl[iindex]) !='undefined' && primary_turl[iindex].indexOf(isize)>=0)
	{
 		iurl = (primary_turl[iindex].indexOf('http') >=0 ? '' :  remotemediaprefix1.split('|')[primary_turl[iindex].split('~')[0]]) + '/' + isize + '/' + iiid.substr(0,2) + '/' + iiid.substr(0,iiid.length-5) + '/' + iiid + '.JPG';
	}
	
	return iurl;
}

function InitSafetyCheck(isize){
        //seek first remote media id for this isize
        if(typeof(testLoadImage)=='undefined')
        {
                this.remoteAssetLoad = function(){
                                        //alert('We are Sorry. We have detected that something is wrong with you being able to view our images.'
                                        //+ this.src + ' We will now switch you to an alternate image location. We are sorry for the delay.');
                                        imagesafetymode=1; // temporarily changes to safety mode and reverts to default hosting location
                                        currentpage();
                                        };

		if(typeof(primary_turl) == 'undefined')
                {
                	        testLoadImage=new Image ();
                        	remoteAssetLoad();
                }
		else
		{

 	               var iii=0;
        	        while( (iii < primary_turl.length) && (primary_turl[iii].indexOf(isize)<1) )
                	{        // seek the first id for this specific size
                        	iii++;
                	}


	                if(iii >= primary_turl.length)
        	        {
                	        testLoadImage=new Image ();
                        	remoteAssetLoad();
                	}
                	else
			{
 	                       testLoadImage=new Image ();
        	                testLoadImage.src= (primary_turl[iii].indexOf('http') >=0 ? '' : remotemediaprefix1.split('|')[primary_turl[[iii]].split('~')[0]] + '/' + isize + '/' + id[iii].substr(0,2) + '/' + id[iii].substr(0,id[iii].length-5) + '/' + id[iii] + '.JPG');

 	                       testLoadImage.onload = function(){
                                                  if(this.height==0 || this.width==0)
                                                  {
                                                        remoteAssetLoad();
                                                  }
                                                };

 	                       testLoadImage.onerror= remoteAssetLoad;
        	                testLoadImage.onabort= remoteAssetLoad;

 	               }
		}
        }
}



//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 : '') + 
				(photoginclude ? '&photoginclude='+photoginclude : '' ) +
				(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 && gusername){

	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=/)) )
	{
		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('div', {id:'lbbuttons' }, [
                    Builder.node('table',{cellspacing:0,cellpadding:0, width:'100%', height:'20'},[
                     Builder.node('tbody', [
                     Builder.node('tr',[
                      Builder.node('td',[
                        Builder.node('a', {href:'', onclick:"lightbox_build('changing'); return false;", title:'SWITCH TO YOUR CART'},[
                                Builder.node('img', {src:'/graphics/cart_enabled_02.gif', border:0, hspace:0, vspace:0})
                        ])
                      ]), //end TD
                      Builder.node('td', { align:'right' }, [
                      Builder.node('div', { 'style':'padding:0 16px 4px 0'  }, [
                        Builder.node('a',{href:'', onclick:"cart_build('changing'); return false;", title:'Switch to your cart'},[
                                Builder.node('img', {border:0, src:'/graphics/tab_vc_off.gif'})
                      	])
                      ])
                      ]) //end TD
                     ]) //end TR
                    ]) //end TBODY
                   ]) //end TABLE
		]),
	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 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();

        	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 co = [6,80];

			if ( $('row2') ){
				co = Position.cumulativeOffset($('row2'));
				if(Position.cumulativeOffset($('cdheader'))[1]>0){
					co=Position.cumulativeOffset($('cdheader'));
				}

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

			panelx = co[0];
 
			panely = co[1] - ( (typeof(covertopadjust) != 'undefined') ? covertopadjust : 0) + (Position.cumulativeOffset($('cdheader'))[1] < 1 ? ( (typeof(covertopadjust) != 'undefined') ? covertopadjust : 0) : 0) ;
			qq('co1' + co[1] + ',panely' + panely + ',' + (Position.cumulativeOffset($('cdheader'))[1]<1) + ',' + ( (typeof(covertopadjust) != 'undefined') ? covertopadjust : 0));
		}
		createDisplayPanel();
		createCoverLayer();
		$('displaypanellayer').style.top = panely + '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){ 
	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 = '128px';
		$('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 && gusername)//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){
	polllb();//make sure and save changes
	currentlbname=newlb;
	simplemessage('Changing to Lightbox: ' + newlb + '<blink>.</blink>','','LB');
	var 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 && gusername)
	{
		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' ) //features already have an ajax-y handler for this
	{
		ajax_TEXT('/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 ) && (typeof(pre_q_args) != 'undefined' && ! ( pre_q_args.match(/vmo=|vmo%3D/))))
		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' },[
		    Builder.node('table',{cellspacing:0,cellpadding:0, width:'100%', height:'20'},[
	 	     Builder.node('tbody', [
		     Builder.node('tr',[
		      Builder.node('td',[
			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, hspace:0, vspace:0})
			])
		      ]), //end TD
		      Builder.node('td', { align:'right' }, [
		      Builder.node('div', { 'style':'padding:0 16px 4px 0'  }, [	
//			Builder.node('a',{href:'/SwishSearch?n=1&lb_view=1',title:'Maximize your lightbox'},[
//				Builder.node('img', {border:0, src:'/graphics/tab_maximize_off.gif'})
//			]),
//			Builder.node('img', {src:'/graphics/tab_div.gif'}),
			Builder.node('a',{href:'', onclick:"cart_build('changing'); return false;", title:'Switch to your cart'},[
				Builder.node('img', {border:0, src:'/graphics/tab_vc_off.gif'})
		      ])
			])
		      ]) //end TD
		     ]) //end TR
		    ]) //end TBODY
		   ]) //end TABLE
		]) //end DIV
		);
		
		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  ')
//			);

			thehtmlLinkList.push(
			Builder.node('b', {}, '')
			);
	
			//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);

			thehtmlLinkList.push(Builder.node('b', {}, '(' + displen + ') ' ) );
		}
	
		var tlb1 = '';
		var tlb2 = '';
		var tlb3 = '';
		var tlb4 = '';
		var tlb5 = '';
		var tlb6 = '';
		var tlb7 = '';
		var tlb8 = '';
		if(1==0){
			tlb1 ='Make 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';
			tlb2 ='View';
			tlb3 ='Email';
			tlb4 ='Add to Cart';
			tlb5 ='Delete';
			tlb6 ='Rename';
			tlb7 ='ADMIN: Make Feature';
			tlb8 ='Copy';
			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:#FFF;height:120px;font-size:11pt;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';
							lbImgLinkArgs.onclick = function () { true; };
						}
                                        } 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',{'id':'siconlbdeletesmall65','style':'padding-left: 1px; padding-right: 1px; padding-bottom:6px;'},[
								Builder.node('a', {'onclick':"lightbox_delete_image('" + lbid + "'); return false;", className:'lblink', 'title':'Remove this image from the lightbox'},[
								]),
//  								Builder.node('a', lbLinkArgs,[
//										Builder.node('img', {'src':'/graphics/lb_plus.gif','height':'13','width':'13','border':'0'})
//									])
		       					])
						:
				       			''
					);


					if(lbid=='1'){lbid='1a';} //hack to get better no images in lb.
					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':ImageUrl('/135/50',lbid), 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://gdynx.ipnstock.com/'+dynimagesname+'/135/50/1a.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-45)+'px;'},[ 
				Builder.node('div', {'id':'LBimgdiv', 'style':'position:absolute; left:0; top:0; padding: 1px 0 0 13px; 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;


/*		
		var temp='dlb_' + (tlba.length - 1) + '';
		lbexpansionspace=0;
		var temp3=$(temp);

		if (temp3)		
		{
			var topoflastimage = Position.cumulativeOffset(temp3);
			var heightoflastimage = parseInt(Element.getHeight(temp3));
			var heightoflbdiv = Element.getHeight('LBdiv');
			var topoflbdiv = Position.cumulativeOffset($('LBdiv'));
			var bottomoflastimage = topoflastimage[1] + heightoflastimage;
	
			if((topoflastimage[1] + heightoflastimage) > trueh){
				lbexpansionspace = (bottomoflastimage - topoflbdiv[1] + 5);
				
				//choke it off to 30% of the screen max
				if(lbexpansionspace > parseInt(trueh * 0.3))
					lbexpansionspace=parseInt(trueh * 0.3);

			}
			
			//Sortable bases it's reordering on the state of the array when it was created..
			//since we also rebuild any time something is added, this is safe..
			document.currentlbstashSnapShot = document.currentlbstash;

        	Sortable.create("LBimgdiv", {
			tag:'DIV',
			overlap:'horizontal',
			constraint: false,
			onChange:function(){
				hp();
				suspendpreviews=1;
			},
			onUpdate:function(){
				var neworder = Sortable.serialize("LBimgdiv");
				rExp = /LBimgdiv/gi;
				results = neworder.replace(rExp, '');
				results = results.replace(/\&/g, '|');
				results = results.replace(/\[\]\=/g, '');
				var newlborder=new Array();
				var newarray=results.split('|'); 
				
				for (var i=0;i< newarray.length;i++){
					newlborder[i]=document.currentlbstashSnapShot[newarray[i]]; 
				}
				document.currentlbstash = newlborder;  //then copy it in
				polllb(); //save it
				setTimeout('suspendpreviews=0;',1000);
			}  
     		});
		}
*/
    }

	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';
                $('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();
	//console.log(newlba);
	var newlb = newlba.join('|');

	if (newlb && newlba.length > 50) //failsafe  50's not a totally arbitrary # .. it's a safe length for a get 
		newlb = '';		//( 50 * 11 is 550 chars + control and url to be less than the 2083 char limit in ie )
					//the # 50 appears elsewhere and changing it here can produce unexpected results

	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();
		}		
	};
/*
	else if (cartTryCtr < 10)
	{
		cartTryCtr++;
		setTimeout("cart_check_act('"+cartTryCtr+"')",  (500 + (50 * (cartTryCtr - 1))) ); //((50 * cartTryCtr - 1) / 2)
	}
	else if (!document.ajaxLoaded )
	{
		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', 'POST', { 'callback':'cart_build_act()' } ); 

	currMousedOverObj = 'shop_cart';
};

function cart_build_act(){
	if(! $('LBdiv'))
		return;

	if ( ! isNaN(document.JSONobj.getCartDat('total')) ) 
	{
		//var stime = jotTime();
		
		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(
		//nodeTree.cart_build_act__buttons,

                Builder.node('div', {id:'lbbuttons' }, [
                    Builder.node('table',{cellspacing:0,cellpadding:0, width:'100%', height:'20'},[
                     Builder.node('tbody', [
                     Builder.node('tr',[
                      Builder.node('td',[
                        Builder.node('a', {href:'', onclick:"lightbox_build('changing'); return false;", title:'SWITCH TO YOUR CART'},[
                                Builder.node('img', {src:'/graphics/cart_enabled_02.gif', border:0, hspace:0, vspace:0})
                        ])
                      ]), //end TD
                      Builder.node('td', { align:'right' }, [
                      Builder.node('div', { 'style':'padding:0 16px 4px 0'  }, [
                        Builder.node('a',{href:'', onclick:"cart_build('changing'); return false;", title:'Switch to your cart'},[
                                Builder.node('img', {border:0, src:'/graphics/tab_vc_off.gif'})
                        ])
                      ])
                      ]) //end TD
                     ]) //end TR
                    ]) //end TBODY
                   ]) //end TABLE
                ]),


		Builder.node('div', {'id':'cartlinks', 'class':'lbname', 'style':'overflow: auto; overflow-y:hidden;'},[
			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=45;} else if(winH < 450){vlim=50;} 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',  '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: ImageUrl('/135/50',ctimid), height: tofit, border: 0, 'className': 'lbimg', hspace: 2	} )
					]),
					Builder.node('div', { 'id':'siconlbdeletesmall65','style':'padding:0px;clear:both'}, [
						Builder.node('a', { href:'', onclick:'cart_delete_image("'+ctid+'"); return false;',  title:'Remove this image from the cart'}, [
						])
					])
				]) );

				
			}

			cartRoot.push(
		                Builder.node('div', {'className':'lbscroll', 'style':'position: relative; overflow: hidden; overflow-y:hidden; height: 82px;' },[
					Builder.node('div', {'id':'LBimgdiv', 'style':'position:absolute; left:0; top:-3px; padding: 0;padding-left: 13px;'}, [ 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>');
		$('LBdiv').innerHTML = '';
                $('LBdiv').style.height = '137px';

		cartRoot.each(function(carta){
			$('LBdiv').appendChild(carta);	
		});


		//var etime = jotTime();
		//$('debugDiv').innerHTML = 'CART BUILD: '+( etime - stime )+' MS <br/>' + $('debugDiv').innerHTML;
		
	}
};	

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

function g() {
	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 = '';
	var photogurladd='';
	if($('displaypanellayer').style && $('displaypanellayer').style.visibility == 'visible'){
		var photocodes = new Array();
		for (var i=0; i < $('displaypanel').photographers.length; i++){
	      		if ( $('displaypanel').photographers.options[i].selected ){
				photocodes.push( $('displaypanel').photographers.options[i].value );
			}
		}
		if(photocodes.length){
				photogurladd += '&photoginclude='+photocodes.join('||');
				if(url2 == 'Keyword or image number(s)'){ url2='BlendImages&sort=orig_iddesc';}
		}
	       	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 (typeof(photogcodes) == 'undefined' && (url2.length<1 || url2 == 'Keyword or image number(s)') && 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 == 'Keyword or image number(s)') && photogurladd.length ==0 )
		{
			url2 = prev_keys;
                	$('Keywords').value = url2;
		}

		if ( (EAD('share_control_sphotog') || EAD('share_control_status') || EAD('share_control_view') || EAD('share_control_release') ) && url2 == 'Keyword or image number(s)')
		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 += 'l'+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(photogurladd.length > 5){theurl += photogurladd;}


			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=square';
				}
			}
	
			if($('displaypanel').rmrftype){
				if ($('displaypanel').rmrftype[0].checked == true && ($('displaypanel').rmrftype[1].checked == false || $('displaypanel').rmrftype[2].checked == false)){
					theurl += '&searchinclude=RF';
				}
				if ($('displaypanel').rmrftype[1].checked == true && ($('displaypanel').rmrftype[0].checked == false  || $('displaypanel').rmrftype[2].checked == false)){
					theurl += '&searchinclude=RM';
				}
				if ($('displaypanel').rmrftype[2].checked == true && ($('displaypanel').rmrftype[0].checked == false || $('displaypanel').rmrftype[1].checked == false)){
					theurl += '&searchinclude=BT';
				}

			}

			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.risn.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';
		    }
			//removed panos
		    if (document.displaypanel.orient[2] && document.displaypanel.orient[2].checked == true){
			buildpref+='i';
		    }
		}

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


		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());
};



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

function htmlit(){}


// -> 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();
	$A($('releasecontrol'+dex)).each( function(itm) {
		if (itm.checked)
			release.push(itm.value);
	});
	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 = '';
		if ( typeof(cocon) == 'object' && cocon[0] )
		{
			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.match(/^[a1-4]$/ )  ) ) )
				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 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 ); 
};



function enlarge2_act__generateTierRows(myratetiers_data,myrmrftype,enid,encount) {
	var myratetiers = '';
        if ( myrmrftype == 'RF' || myrmrftype == 'BT' )
        {
                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
	setuppagesize();
	//console.log( truevertHeight+' '+winH+' '+$('Layer1').style.height );
	$('Layer1').style.height = truevertHeight + 100 + 'px';
	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' || id[encount] )
		///{
                        if($('cdheader'))
                        	$('cdheader').style.display = 'none';

			//var tstart = jotTime();

			//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 : " ");
			var testlongcaption = document.JSONobj.getImgDat('long_caption');
			testlongcaption = (	testlongcaption	?  testlongcaption : " ");
			if ( typeof(uselongcaption) != 'undefined' && testlongcaption != " " )
			{
				if ( uselongcaption == 'useboth' )
				{
					if ( testshortcaption == " " ) //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 myorigid = ( useInPage && o[encount] ? o[encount] : document.JSONobj.getImgDat('orig_id') );
			var mycomplink = ( useInPage && cs[encount] ? cs[encount] : document.JSONobj.getImgDat('comp_link') );
			var myrmrftype = document.JSONobj.getImgDat('rmrftype');
			var myratetiers_data = document.JSONobj.getImgDat('tieredimgpricing'); //myratetiers is a data object now.. so build..
			var myratetiers = enlarge2_act__generateTierRows(myratetiers_data,myrmrftype,enid,encount);

			var myphotographer	= document.JSONobj.getImgDat('photographer') +
					((document.JSONobj.getImgDat('agent_name') && document.JSONobj.getImgDat('agent_name') != '') ? '/'+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 += '<div style="z-index:2;position:absolute;top: 0px; left: 0px;">'
					+ '<img src="' +
					( (typeof(localwatermark) != 'undefined' && ! pngsupport) ? 'http://gdynx.ipnstock.com/'+dynimagesname+'/wm/60/' + tarid + '.JPG' : ImageUrl("420/60",tarid) )
					+'" border=0 style="display:inline; clear:none; border:1px solid grey;" id="'+tarid+'"></a></div>'
					+( (typeof(localwatermark) != 'undefined' && pngsupport) ? '<div style="z-index:3;position:absolute;top: 0px; left: 0px;overflow: hidden;"><IMG src='+localwatermark+' style="margin-top: -20px;" border=0></div>'
						:
						'');
			//	themediainsert += '</div></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="' + ImageUrl("135/50/",simarray[i]) + '" border=0 vspace=2 hspace=2 height=' + simheight + ' align=left></a></span>';
				}
				similarscolumn = Templates.enlarge2_act__similars.evaluate({simcolinfo: simcolinfo});
			}
			
			

			//will become navenlargedlinks
			var navenlargedlinksprev = '';var navenlargedlinksnext='';

			//this ifblock becomes var navbacklink
			var navbacklink = '';

			    if (preMem == 'cartview')
			    {
				navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'cartview\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom());currentpage(); return false;" class="orangelink"><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;" class="orangelink"><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; " class="orangelink">Return to Search Results</A>';
			    } 

			if ( useInPage )
			{
			    if(preMem != 'cartview')
			    {
				if((snum + encount) > 0){ navenlargedlinksprev= '<A HREF="" onclick="enlarge2(\'' + previmageid + '\',\'' + previmage + '\'); return false;" TITLE="GO TO THE PREVIOUS IMAGE"><IMG SRC=/images/arrow_back.gif width=14 height=8 border=0></a>';}
				if((Number(snum) + Number(encount) + 1) < Number(total)){ navenlargedlinksnext = '<A HREF="" onclick="enlarge2(\'' + nextimageid + '\',\'' + nextimage + '\'); return false;" TITLE="GO TO THE NEXT IMAGE"><IMG SRC=/images/arrow_next.gif width=12 height=8 border=0></A>';}
			    }
			}  

			var enlargetid = '';
			if(featuredimage){ enlargetid = featuredimage;} else { 	enlargetid = enid;}
			
			//will become downloadcomplink
			var downloadcomplink = '';
			if(preMem != 'cartview')
			{
				if(gsession && gusername && mycompallow == 'Y') { 
					downloadcomplink = '<tr><td><div id="siconcompsmall65" style="margin-left: 3px;"><a href="/bin/Comp/'+gusername + '/' + mycomplink + '/' +
					enlargetid
					+ '.JPG" TITLE="Download a comp image"></a></div></td><td><div id="iconrighttextlink"><a href="/bin/Comp/'+gusername + '/' + mycomplink + '/' +
					enlargetid
					+ '.JPG">DOWNLOAD COMP</a></div></td></tr>';
				} else if(gsession) {
					downloadcomplink = '<tr><td><div id="siconcompsmall65" style="margin-left: 3px;"><a href="/bin/Comp/'+gusername + '/' + mycomplink + '/' +
					enlargetid
					+ '.JPG" TITLE="Download a comp image"></a></div></td><td><div id="iconrighttextlink"><a href="/bin/Comp/'+gusername + '/' + mycomplink + '/' +
					enlargetid
					+ '.JPG">DOWNLOAD COMP</a></div></td></tr>';

				} else {
					//guest
					downloadcomplink = '<tr><td><div id="siconcompsmall65" style="margin-left: 3px;"><a href="/bin/Comp/guest/' + mycomplink + '/' +
					enlargetid
					+ '.JPG" TITLE="Download a comp image"></a></div></td><td><div id="iconrighttextlink"><a href="/bin/Comp/guest/'+ mycomplink + '/' +
					enlargetid
					+ '.JPG">DOWNLOAD COMP</a></div></td></tr>';
				}
			}
	
			// META DATA FOR ENLARGED TARGET IMG:
	
			//will become: ratetierinfo
			var ratetierinfo = ( myratetiers ? '<BR/><div id="enlargeratetiers" class="enlargeratetiers">' + myratetiers + '</div>' : '' );
			
			//becomes releaseinfo
			var releaseinfo = ( showrelease ? '<b>Release:</b> ' + myreleased + '<br>' : '' );
			
			//becomes RM price link if applicable
			var rmpricelink = ( myrmrftype == 'RM' ? '<tr><td><div id="siconpricesmall65" style="margin-left: 6px;"><a href="#" onclick="license(\'' + enlargetid + '\'); return false;"></div></td><td><div id="iconrighttextlink"><a href="#" onclick="license(\'' + enlargetid + '\'); return false;">CHECK USAGE RATES</a></div></td></tr>' : '');
				
			//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 + '" class="orangelink">' + 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 keywordinfoArr = new Array();
			document.JSONobj.getKeywords().each(function (kwd){
				var relink = decodeURIComponent(q_args);
				//e.g. Keywords=shot%20put+haspeople+NOT+imagehasrestrictions
				if(relink.match(/Keywords=[^\+\&]+\+/))
				{
					relink = relink.replace(/Keywords=[^\+]+\+/, 'Keywords='+kwd+'l');
				}
				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', '');
				keywordinfoArr.push('<a class="keywordinfo" href="/SwishSearch?' + relink +'&spec_idx=ne">' + kwd + '</a>');
			});

			var keywordinfo = keywordinfoArr.join(', ');

			var displayenlargetid = myorigid;

			var dateshot = document.JSONobj.getImgDat('date_shot');
			var rfCDinfo = unescape( document.JSONobj.getImgDat('rfcdObj') + " " );
			var rfcdlinkslug = '';
			if ( rfCDinfo.toString().length > 1 )
			{
				rfCDinfo = rfCDinfo.evalJSON();
				rfcdlinkslug = Templates.rfcd__cdimage_detail.evaluate(rfCDinfo);
			}
						
			var tdata = $H({enlargetid: enlargetid,
					dateshot: dateshot,
					rfcdlinkslug: rfcdlinkslug,
					keywordinfo: keywordinfo,
					displayenlargetid: displayenlargetid,
					restrictionsinfo: restrictionsinfo,
					rmpricelink: rmpricelink,
     					filesizeinfo: filesizeinfo,
	  				photographerinfo: photographerinfo,
       					releaseinfo: releaseinfo,
	    				ratetierinfo: ratetierinfo,
	 				downloadcomplink: downloadcomplink,
      					navenlargedlinksprev: navenlargedlinksprev,
      					navenlargedlinksnext: navenlargedlinksnext,
	   				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(ImageUrl('420/60', nextimageid));
		} 
		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]	
	//}
};

function writesearch(){
	panelheight=430;
	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 btc=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 || gsearchprefs.indexOf("l")<0){

			if(gsearchprefs.indexOf("k")<=0){// && ! gsearchprefs.indexOf("k")>=0){
				rfc = "";
			}
			if(gsearchprefs.indexOf("j")<=0){// && ! gsearchprefs.indexOf("j")>=0){
				rmc = "";
			}
			if(gsearchprefs.indexOf("l")<=0){// && ! gsearchprefs.indexOf("j")>=0){
				btc = "";
			}
			
		}
		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 style="background: #fff; height: 20px;" colspan=2>';
	// conditional to insert 'search within' box in dropdown:
	if (typeof(showSearchWithin) != 'undefined'){
		thehtml += '<nobr>&nbsp;<select id="method" name="method" class="smallmenu" style="height:18px; width: 120px;"><option value="new" '+tempsearchnew+'>New Search</option><option value="within" '+tempsearchwithin+'>Search Within Results</option></select></nobr><br/>';
	}
	thehtml += '</td>';
	thehtml += '</tr><tr><td valign=top align=left class="light1">';
        if (typeof(rmselector) != 'undefined' || typeof(rfselector) != 'undefined' || typeof(rrselector) != 'undefined'){
                thehtml += '<b>SEARCH FILTERS</b><br><table cellspacing="0" cellpadding="3" border="0">';

		if (typeof(rfselector) != 'undefined'){
			thehtml += '<tr><td><nobr><input type="checkbox" name="rmrftype" value="RF" ' + rfc + ' onclick=javascr' + 'ipt:fsearchprefs("RF","add");> Royalty Free</nobr></td></tr>';
		}



		if (typeof(rmselector) != 'undefined'){
			thehtml += '<tr><td><nobr><input type="checkbox" name="rmrftype" value="RM" ' + rmc + ' onclick=javascr' + 'ipt:fsearchprefs("RM","add");> Rights Managed</nobr></td></tr>';
		}

		if (typeof(btselector) != 'undefined'){
			thehtml += '<tr><td><nobr><input type="checkbox" name="rmrftype" value="BT" ' + btc + ' onclick=javascr' + 'ipt:fsearchprefs("BT","add");> Boost</nobr></td></tr>';
		}


		thehtml += '</table><BR>';
        }


	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=square onclick=javasc' + 'ript:fsearchprefs("i","add"); ' + temps + '> Square</td></tr>';
	thehtml += '</table><br>';
	if(typeof(vcdoptions) != 'undefined'){
		thehtml += '<b>BROWSE VCDs</b><BR><Select name=VCDoption onchange="javascript:self.location.href=this.options[this.selectedIndex].value">';
		thehtml += vcdoptions + '</select>';
	}
	if(typeof(tpriorsearchmenu) != 'undefined' && tpriorsearchmenu.length > 50){
		thehtml +=tpriorsearchmenu + '<BR>';
	}
	thehtml += '</td><td valign=top align=left class="light1">';
thehtml +='<b>Filter by contributor&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="" onclick="clearPhotogs(document.risn); return false;"><span style="color:#14aae8">clear</span></a></b><br/><select name="photographers" size="12" multiple class="photographersList" style="color:#000">';
if ( typeof(artistoptions) != 'undefined' )
	thehtml +=artistoptions;
thehtml +='</select></div><p style="margin-top:3px; width:175px; font-size: 7pt;">(To select more than one option, hold down "Ctrl" or "Cmd" on your keyboard)</p>';

	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] hide search options</A>';
	thehtml += '</td></tr></table></form>';
	var temp=$A();
	if ( $('tablerow2') )
		temp=Position.cumulativeOffset($('tablerow2'));
	else
		temp=[0,6];
	center_panel(453,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( document.risn && ( msX < panelx || msY > (panely+panelheight)) ){
	document.risn.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 = '1001';
	$('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 autodropset(){
	autodropmode=0;
	gsearchprefs = ggetCookie('gsearchprefs');
	if(gsearchprefs){
	        if(gsearchprefs.indexOf("f")>=0 && gsearchprefs.indexOf("g")>=0 && gsearchprefs.indexOf("i")>=0 || ! (gsearchprefs.indexOf("f")>=0 || gsearchprefs.indexOf("g")>=0 || gsearchprefs.indexOf("i")>=0)){
	        } else {
	                autodropmode=1;
	        }
	        if(gsearchprefs.indexOf("j")>=0 && gsearchprefs.indexOf("k")>=0 && gsearchprefs.indexOf("1")>=0 || !(gsearchprefs.indexOf("j")>=0 || gsearchprefs.indexOf("k")>=0 || gsearchprefs.indexOf("1")>=0)){
	        } else {
	                autodropmode=1;
	        }
	}
}

function toggleadvanced(adm){
	autodropset();
	 if($('displaypanellayer').style && $('displaypanellayer').style.visibility == 'visible' && !(adm)){
		//$('advancedoptions').src='/graphics/show_advanced_closed.gif';
		hidedisplaypanel();
	} else {
		//$('advancedoptions').src='/graphics/show_advanced_open.gif';
		writesearch();
	}
}
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 buildSubNav(ldt,dsplkys) {

	var totestman = ( pagetype == 'search' ? 'search' : ( ldt.match(/^Request:/) ? 'req' : ( ldt.match(/^Feature:/) ? 'feat' : ( ldt.match(/^Virtual CD Store:/) ? 'vcd' : pagetype ) ) ) );

	var thehtml = '';

	if (totestman == 'req'){
		thehtml += ldt+' Results&nbsp;:&nbsp;'+dsplkys+'';
	} else if (cartview) {
		dsplkys = '<div class="resultstitleBox"><img src="/images/h_myshoppingcart.gif" alt="Shopping Cart" width="202" height="40" style="margin-bottom: -11px;"/>';
		setTimeout("$('previewbox').style.display='none';",1000);
		setTimeout("$('sizeicons').style.display='none';",1000);
		thehtml += ''+dsplkys+'';
		setTimeout("document.getElementById('Layerpages').style.visibility='hidden'",1000);
	} else if (totestman == 'lb') {
		thehtml += '<div class="resultstitleBox"><img src="/graphics/h_mylightboxes.gif" alt="My Lightboxes" width="165" height="27"  align="absmiddle"style="margin-bottom: 4px;"/><div style="display: inline;padding-left: 5px;">'+dsplkys+'&nbsp;:&nbsp;<!total>&nbsp;images</div>';
	} else if (totestman == 'feat') {
		if(dsplkys.substring(0,6)=='BLDVCD'){
			thehtml += '<div class="resultstitleBox"><img src="/images/h_virtualCDStore.gif" alt="Virtual CD STore" width="178" height="40" align="absmiddle" style="margin-top: -19px;margin-bottom: -4px;"/>&nbsp;&nbsp;'+dsplkys+'&nbsp;:&nbsp;<!total>&nbsp;images';
		} else {
			$('cdheader').style.display='none';
			thehtml += '<div class="resultstitleBox"><img src="/images/h_galleryResults.gif" alt="Gallery" width="77" height="24" style="margin-top: 17px;margin-bottom: -4px;"/>&nbsp;&nbsp;'+dsplkys+'&nbsp;:&nbsp;<!total>&nbsp;images';
		}
	} else if (totestman == 'vcd') {
		thehtml += '<div class="resultstitleBox"><img src="/images/h_virtualCDStore.gif" alt="Virtual CD STore" width="178" height="40" align="absmiddle" style="margin-top: -11px;margin-bottom: -4px;"/>&nbsp;&nbsp;'+dsplkys+'&nbsp;:&nbsp;<!total>&nbsp;Virtual CDs';
	} else {
		thehtml += '<div class="resultstitleBox"><img src="/images/h_searchResults.gif" alt="Search results" width="163" height="19" align="absmiddle" style="margin-bottom: 8px;"/><div style="display: inline;padding-left: 5px;"><!display_type>"'+dsplkys+'"&nbsp;found&nbsp;<!total>&nbsp;images</div></div>';
	}

	$('SubNavRow').innerHTML = '';

	MM_setTextOfLayer('SubNavRow','',thehtml);

	return dsplkys;
};
*/
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;"><IMG SRC=/images/arrow_back.gif width=14 height=8 border=0></A>&nbsp;';
        } else if (showstartnumber <= total){
                thehtml+='<IMG SRC=/images/arrow_back.gif width=14 height=8 border=0>';
	}

	if ( showstartnumber <= total )
	{
		thehtml+='Page&nbsp;<SELECT name="pageurl" align="absmiddle"  onChange="document.currentLayer1Mode=\'searchresults\'; self.location=this.options[this.selectedIndex].value; return false;" class="smallmenu" style="width:52px;margin-left: 3px;margin-right: 3px; margin-bottom: 2px;">';
		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="' + encodeURI(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="' +encodeURI(nextlink) + 'snum=' + ((i-1) * (parseInt(gpixperpagev))) + '" SELECTED>' + i + '</option>';
			} else {
				thehtml+='<OPTION VALUE="' + encodeURI(nextlink) + 'snum=' + ((i-1) * (parseInt(gpixperpagev))) + '">' + i + '</option>';
			}
		}
	
		if(pen != totalpages){
			thehtml+='<OPTION VALUE="' + encodeURI(nextlink) + 'snum=' + ((Number(pen)) * (parseInt(gpixperpagev))) + '">&gt; ' + (Number(pen) + 1) + '</option>';
		}

	
		thehtml+='</select> of ' + totalpages;
		if(grange != "outofrange"){
			thehtml+='&nbsp;<A HREF="" onclick="document.currentLayer1Mode=\'searchresults\';nextpage(); return false;"><IMG SRC=/images/arrow_next.gif width=12 height=8 border=0></A></font>';
		}

		thehtml += '</NOBR></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 = ' 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> ';
			$('Layerpreviews').innerHTML = lochtml;
		}
	}

	thehtml += '</td></tr></table>';
	$('Layerpages').style.overflow = 'visible';
	//buildSubNav(pagetype,searchwords);
	$('Layerpages').style.display='block';
	//$('Layerpages').style.visibility='visibile';
        MM_setTextOfLayer('Layerpages','',thehtml);
        //suspendtrap=0;



};

function buildimages(startnumber,mode,resized){
	if(typeof(cartview) != 'undefined' && cartview && mode != 'current')
		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($('cdheader')){
		(typeof(dsplkys) != 'undefined' ? (dsplkys.substring(0,6)=='BLDVCD' ? $('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);

	var checksnum = true;
	
	checksnum=(snum?true:false);
	
        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/>';

		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=/) ) ) || (id.length==1) || (total <=endnumber))
		checksnum = true;	


		while(cnt < endnumber) {
			if( id[cnt] ){
                                thehtml += htmlit_custom(cnt);
			} 
			else if(((snum + cnt)>=total) && checksnum){
                                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></DIV></SPAN> ';
                                        } else {
						thehtml+='<BR><nobr>&nbsp;&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" || mode == 'forcesearch'){
			if (mode == 'forcesearch'){
				self.location='/SwishSearch?Keywords='+searchwords+'&snum='+ (Number(firstpictureonpage) + Number(snum));
				return;
                        } else if (mode == "next"){
                                self.location= nextlink + 'snum=' + (Number(firstpictureonpage) + Number(snum)); //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;}
                                self.location=nextlink + 'snum=' + prevtogoto;

                        }

                } 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:-6px; border: solid #ccc 0px;border-top-width: 1px;\" align=left width=100% height=17 cellpadding=0 cellspacing=0 border=0><TR><TD align=left width=90% style=\"padding-top: 5px;\">" + footer();

                        bottomthehtml+= "</TD><TD align=\"right\"  width=10% style=\"padding-top: 5px;\"><div style=\"padding-right: 20px; height: 12px;\">";
	                        if ((typeof(snum) != 'undefined' && Number(snum) > 1) || ( typeof(startnumber) != 'undefined' && Number(startnumber) > 1)){
                                bottomthehtml+= "<nobr><A HREF=javasc" + "ript:prevpage(); TITLE=\"PREVIOUS PAGE\"><IMG SRC=/graphics/arrow_prev2.gif width=11 height=12 border=0 style=\"margin-right:12px;\"></A>";
                        } else {
                                bottomthehtml+= "<nobr>";
                        }


                        if (grange != "outofrange"){
                                bottomthehtml+= "<A HREF='' onclick='nextpage(); return false;' name=bottomnext TITLE=\"NEXT PAGE\"><IMG SRC=/graphics/arrow_next2.gif width=45 height=12 border=0></A></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){
		//clear them
		if($('sicontiny')){$('sicontiny').className='sizeiconblocks';}
		if($('siconbig')){$('siconbig').className ='sizeiconblocks';}
		if($('siconlarge')){$('siconlarge').className ='sizeiconblocks';}
		if($('siconmed')){$('siconmed').className ='sizeiconblocks';}
		if($('sicontab')){$('sicontab').className ='sizeiconblocks';}
		if($('siconhuge')){$('siconhuge').className ='sizeiconblocks';}
		if($('siconlist')){$('siconlist').className ='sizeiconblocks';}
                //set it
		if(viewmode == 'table'){ //
			if($('sicontab')){$('sicontab').className='sicontabactive';}
                } else  if(viewmode == 'list'){ //
			if($('siconlist')){$('siconlist').className='siconlistactive';}
                } else  if (viewmode == 'tiny'){
			if($('sicontiny')){$('sicontiny').src='/graphics/icon_miniv2_on.gif';}
                } else if (viewmode == 'med'){  //
			if($('siconmed')){$('siconmed').className='siconmedactive';}
                } else if (viewmode == 'huge'){ //
			if($('siconhuge')){$('siconhuge').className='siconhugeactive';}
                } else if (viewmode == 'large'){
			if($('siconhuge')){$('siconhuge').className='siconhugeactive';}
		//	if($('siconlarge')){$('siconlarge').src='/graphics/icon_lrgv2_on.gif';}
                }
        }
};

function writesimilar(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink) {
        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="' + ImageUrl("420/60",wmyid) + '" border="0" alt="loading..." height="190"></a></TD>';
        } else if( mode == 'med'){
                iconheight=10;iconwidth=14;
                thehtml += '"><img src="' + ImageUrl("135/50",wmyid) + '" border="0" vspace="0" hspace="0" alt="loading..." height=72></a></TD>';
        } else if( mode == 'tiny'){
                iconheight=8;iconwidth=12;
                thehtml += '"><img src="' + ImageUrl("135/50",wmyid) + '" border="0" vspace="0" hspace="0" alt="loading..." height=45></a></TD>';

        } else {
				iconheight=12;iconwidth=16;
                thehtml += '"><img src="' + ImageUrl("135/50",wmyid) + '" 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;' + (typeof(myhrdlink) != 'undefined' ? myhrdlink : '')+'&nbsp;&nbsp;';
		} else if (mode == 'list') {
			thehtml += '&nbsp;&nbsp;'+ (typeof(myhrdlink) != 'undefined' ? myhrdlink : '')+'</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 + '\'); 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 + '\'); 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 (action == 'start'){
                return thehtml;
        }
        if (action == 'prev'){
                MM_setTextOfLayer( 'd' + setid,'',thehtml);
        }
        if (action == 'next'){
                MM_setTextOfLayer( 'd' + setid,'',thehtml);
        }
};

function currentpage(){
	setuppagesize(); 	
	if (document.currentLayer1Mode == 'searchresults')
	{
        	qq('running buildimages');
		//buildimages( ( firstpictureonpage ? firstpictureonpage : 0 ),0);
                //var showstartnumber = parseInt(startnumber) + parseInt(snum) + 1;
                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 =  ( Position.cumulativeOffset($('lbbuttons'))[1] - Position.cumulativeOffset($('row2'))[1]  + Element.getHeight("lbbuttons") ) + 'px';// + 'px';//$('Layer1').style.height;
			$('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(Position.cumulativeOffset($('cdheader'))[1]>0){
				co=Position.cumulativeOffset($('cdheader'));
			}

                } else {
                        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);	
	}
	if (enlargeview)
		enlarge2(enlargeview, 0);
};

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;
            }
*/
	if ( $('Layer1') )
	{
		winW = Element.getWidth('Layer1');
	}
	else if (window.innerWidth)
       	{
              	winW = window.innerWidth;
        }
       	else if(document.documentElement && document.documentElement.clientWidth)
        {
        	winW = document.documentElement.clientWidth;
        }
        else if(document.body && document.body.clientWidth)
        {
        	winW = document.body.clientWidth;
        }
        else if(document.body && document.body.offsetWidth)
        {
        	winW = document.body.offsetWidth;
        }




	if (window.innerHeight)
	{
		trueh = window.innerHeight;
	}
	else if(document.documentElement && document.documentElement.clientHeight)
	{
		trueh = document.documentElement.clientHeight;
	}
	else if(document.body && document.body.clientHeight)
	{
		trueh = document.body.clientHeight;
	}
	else if(document.body && document.body.offsetHeight)
	{
		trueh = document.body.offsetHeight;
	}


	
	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  && gusername){//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
	{
		///old function now replaced by allfuncs_template.js
	}


/*	if(document.currentLayer1Mode == 'enlarge'){
			imagespaceheight=winH - menuheight;
		} */
	truevertHeight = winH;
	if (! (gsession  && gusername))
		//	winH=imagespaceheight - menuheight + 30; // restore it to accomodate narrowbar and footer when  not logged in
	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=ImageUrl("135/50",id[preloadcurrent]);
        }
};

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;}
                }

                self.location=nextlink + 'snum=' + prevtogoto;

        } 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=='vertical'){
				theImgAttrs['height'] = (((winH - 100) < 180) ? 180 : (winH - 50));
			} else {
				theImgAttrs['height'] = ((winH - 142) < 160) ? 160 : (winH - 102);
			}
		} else {
			theImgAttrs['height'] = 195;
		}

	} 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:ImageUrl("420/60",prid), 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});
			
			//var tend = jotTime();
			//$('debugDiv').innerHTML = 'SP: '+( tend - tstart )+' MS <br/>' + $('debugDiv').innerHTML;
		}
		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){
        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' ) {
                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_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
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  && gusername){
		self.location="/SwishSearch?n=1&lb_view=1";
	} else {
		self.location = '/bin/Cklb?ref=/SwishSearch?lb_view=1';
	}
};

function topcartrefresh() {
	if(gsession  && gusername){
		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=no,menubar=no,status=no' );
	Win2.focus();
};

///////////////js functions for search //////////////////////////
function optimize() {
};

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?supst=multiuse&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;
};

function jotTime() {
	var d = new Date()
	var tnow = d.getMilliseconds();
	return tnow;
};

function qq(b){
if(ggetCookie("debug")){alert(b);};
}
function qqon(){
	gsetCookie2("debug","1");
}
function qqoff(){
gsetCookie2("debug","");
}

var gpsearches = ggetCookie('psearches');
if(gpsearches){
	priorsearcharray = gpsearches.split('|');
	var tpriorsearchmenu='<br/><select name=psearch class=priorsearchmenu onchange="javascript:self.location.href=this.options[this.selectedIndex].value"><option value=#>Your previous searches</option>';
	for(var i=priorsearcharray.length - 1;i>=0;i--){
		var itemarray=priorsearcharray[i].split('~');
		var ta=itemarray[1];
		if(ta.length>40){ta=itemarray[1].substring(0,39) + '...';}
		tpriorsearchmenu +='<option value=/SwishSearch?' + itemarray[0] + '>' + ta + '</option>';
	}
	tpriorsearchmenu += '</select>';
}

