// many of global vars are set in ajaxhandlers/ajax_searchpage.html

var area, fmstartnumber, grange, optimizemenu, overflowtype, pixperpage, resized, showcaptionview, showphotographer, showfilesize, showrelease, viewmode, winH;        // must be here for backward-compaibility.
var Builder, color, date, MACIE5, method, orient, pagetype, q_args, q_id, scriptname, searchinclude, sort, spec_idx, ucats, vcdbrowse, feat_requestview, mobject_id, similar_to, ukeys, dsplkys;

var global = new Object();

var afInitObj = new afInit();
var afDateObj = new afDate();   // needed for globally accessible functions backwards compatible.
var afCookieObj = new afCookie();  // needed for globally accessible functions backwards compatible.
var afCartObj = new afCart();
var afLightboxObj = new afLightbox();
var afImageObj = new afImage();
var afHTMLObj = new afHTML();
var afURLObj = new afURL();
var afMouseObj = new afMouse();
var afPreviewObj = new afPreview();
var afSearchObj = new afSearch();
var afSystemObj = new afSystem();
var afLegalObj = new afLegal();
var afInfoObj = new afInfo();
var afWindowObj = new afWindow();
var afDispatchObj = new afDispatch();
var afPageObj = new afPage();
var afReleaseObj = new afRelease();
var afShareObj = new afShare();
//-- [ globally accessible functions ] ---

gfixDate = afDateObj.fixDate; 
setCurrentTime = afDateObj.setCurrentTime;  // not sure this is needed, but added it to be safe.

_handleNonSearch = afURLObj.createNextLink;

make_share_control_string = afShareObj.makeShareControlString;
switch_share_control = afShareObj.toggleShareControlCookie;
share_set_page = afShareObj.shareSetPage;
EAD = afShareObj.checkID;
sos = afShareObj.saveShares;
sor = afShareObj.saveReleaseControl;
validaterad = afShareObj.validateRadioButtons;

gsetCookie = afCookieObj.setCookie;
gsetCookie2 = afCookieObj.setCookie2;
ggetCookie = afCookieObj.getCookie;
gGetCookieDom = afCookieObj.getCookieDomain;
gdeleteCookie = afCookieObj.deleteCookie;
gwhichindex = afCookieObj.setCookieGwhichindex;
greleasedselect = afCookieObj.setCookieGreleasedselect;

cart_addto = afCartObj.addToCart;
cart_build = afCartObj.buildCart;
cart_build_act = afCartObj.cart_build_act;
cart_check_act = afCartObj.cart_check_act;
cart_delete_license = afCartObj.deleteLicenseFromCart;
cart_delete_image = afCartObj.deleteImageFromCart;
cart_display = afCartObj.displayCart;
cart_mod_act = afCartObj.cart_mod_act;
cart_reprice = afCartObj.repriceImagesInCart;
cart_away = afCartObj.awayCart;
cart_check = afCartObj.checkCart;
dispatchCart_display = afCartObj.displayDispatchedCart;
topcartrefresh = afCartObj.refreshTopCart;

lightbox_add2cart = afLightboxObj.addLightboxToCart;
lightbox_addto = afLightboxObj.addImageToLightbox;
lightbox_build = afLightboxObj.buildLightbox;
lightbox_new = afLightboxObj.newLightbox;
lightbox_new_send = afLightboxObj.registerLightbox;
lightbox_email = afLightboxObj.emailConfirmation;
lightbox_email_send = afLightboxObj.emailLightbox;
lightbox_mod_act = afLightboxObj.lightbox_mod_act;

lightbox_delete = afLightboxObj.deleteLightbox;
lightbox_delete_image_enl = afLightboxObj.deleteLightboxFromEnlargeView;
lightbox_delete_image = afLightboxObj.deleteImageFromLightbox;
lightbox_rename = afLightboxObj.renameLightbox;
lightbox_rename_send = afLightboxObj.registerLightboxRename;
lightbox_change = afLightboxObj.changeLightbox;
make_lightbox_string = afLightboxObj.makeLightboxString;
polllb = afLightboxObj.saveLightbox;
showhideLB = afLightboxObj.toggleLightbox;
simplemessage = afLightboxObj.simpleMessage;
test_valid_name = afLightboxObj.validateLightboxName;
toplightboxrefresh = afLightboxObj.refreshTopLightbox;

buildimages = afImageObj.buildImages;
fitMeTo = afImageObj.sizeImageToContainer;
preloadnextimg = afImageObj.preloadNextImage;
price_image_act = afImageObj.price_image_act;
price_image = afImageObj.priceImage;
prloadimg = afImageObj.preLoadImage;
twidle_price_img = afImageObj.twidleImagePrice;
twidle_price_img_delay = afImageObj.twidlePriceImagedelay;

buildpages = afHTMLObj.buildPagination;
center_panel = afHTMLObj.centerPanel;
coveroff = afHTMLObj.hideCoverLayer;
createCoverLayer = afHTMLObj.createCoverLayer;
createDisplayPanel = afHTMLObj.createDisplayPanel;
dispatchBuildimages = afHTMLObj.dispatchBuildImages;
divshim = afHTMLObj.divShim;
hidedisplaypanel = afHTMLObj.hideDisplayPanel;
html_share_con_opts = afHTMLObj.html_share_con_opts;
html_weight_con_opts = afHTMLObj.html_weight_con_opts;
html_combined_con_opts = afHTMLObj.html_combined_con_opts;

htmlit = afHTMLObj.imageProfile;
init_share_radios = afHTMLObj.initShareRadios;
displaypanelshow = afHTMLObj.showDisplayPanel;
footer = afHTMLObj.getFooter;

mouseSnap = afMouseObj.mouseSnap;
pfindmouse = afMouseObj.findMouse;
getMouseXY = afMouseObj.getMouseCoordinates;

hp = afPreviewObj.hp;
hpoff = afPreviewObj.hpoff;
portSize = afPreviewObj.portSize;
previewset = afPreviewObj.previewSet; // variable has s in lowercase for backword capatibility
sp = afPreviewObj.sp;
sp_act = afPreviewObj.sp_act;

checkIt = afSearchObj.checkIt;
expandit = afSearchObj.expandIt; // variable has i in lowercase for backward compatibility
g = afSearchObj.searchType;
g_standard = afSearchObj.standardSearch;
fsearchprefs = afSearchObj.searchPreferences;
narrowit = afSearchObj.narrowIt;  // variable has i in lowercase for backward compatibility
optimize = afSearchObj.optimizeSearch;
popkeys2 = afSearchObj.popKeywords;
writesearch = afSearchObj.writeSearch;                    // this might be more appropriately be put in afHTML
writesimilar = afSearchObj.writeSimilar;                  // this might be more appropriately be put in afHTML
writesearch_standard = afSearchObj.writeStandardSearch;   // this might be more appropriately be put in afHTML
writesimilar_standard = afSearchObj.writeStandardSimilar; // this might be more appropriately be put in afHTML

hovercopyright = afLegalObj.copyrightNotice;
license = afLegalObj.licenseCostWindow;

enlarge2 = afInfoObj.enlarge2;
dispatchEnlarge2 = afInfoObj.dispatchEnlarge2;
enlarge2_act__generateTierRows = afInfoObj.enlarge2_act__generateTierRows;
enlarge2_act = afInfoObj.enlarge2_act;
MM_preloadImages = afInfoObj.preloadImages;
MM_setTextOfLayer = afInfoObj.setTextOfLayer;

launchwin = afWindowObj.popUp;
displayWindow = afWindowObj.displayWindow;
displayWindow2 = afWindowObj.displayWindow2;
maxscreen = afWindowObj.maximizeScreen;

dispatchAll = afDispatchObj.dispatchAll;
reDispatch = afDispatchObj.reDispatch;

checkpageresize = afPageObj.checkPageResize;
currentpage = afPageObj.currentPage;  //variable has p in lowercase for backward compatibility
gSetBackpage = afPageObj.setBackPage;
setuppagesize = afPageObj.setupPageSize;  //variable has p in lowercase for backward compatibility
nextpage = afPageObj.nextPage;
prevpage = afPageObj.previousPage;
preloadnextpage = afPageObj.preloadNextPage;

save_all_releases = afReleaseObj.saveAllReleases;
release_set_page = afReleaseObj.releaseSetPage;
validatechx = afReleaseObj.validateCheckboxes;
iconstatus = afReleaseObj.iconStatus;

debug = afSystemObj.debug;
getVars = afSystemObj.getVars;
nada = afSystemObj.empty;
tellme = afSystemObj.screenInfo;

//---

afInitObj.init();            // this calls the init function that initializes all the global variables
                             // and further manipulates them. The end result is then re-assigned to  
                             // the old global variables for backwards compatibility. Eventually these
                             // variables below will gradually get extinct.

//alert('Going to re-assign globals...');
// we need to explicitly globalize some vars for backwards compatibility.
// again, these will eventually need to be phased out.

var MACIE5 = global.macIE5;                                    // MACIE5 used in dispatchBuildimages(); default value = 'false'
var q_args = global.qArgs;                                     // q_args used in init()
var searchinclude = global.searchInclude;                      // searchinclude used in _handleNonSearch()
var color = global.color;                                      // color used in _handleNonSearch()
var method = global.method;                                    // method used in _handleNonSearch()
var orient = global.orient;                                    // orient used in _handleNonSearch()
var sort = global.sort;                                        // sort used in _handleNonSearch()
var todaysDate = global.currentDate;                                 // date used in _handleNonSearch()
                                                           //   Note : all other instances of 'date' are localized in functions
var vcdbrowse = global.VCDBrowse;                              // VCDBrowse used in _handleNonSearch()
var spec_idx = global.specIdx;                                 // spec_idx used in: _handleNonSearch()
                                                           //                   optimize()
                                                           //                   narrowit()
var q_id = global.qID;                                         // q_id used in _handleNonSearch()
                                                           //              g_standard()
var scriptname = global.scriptName;                            // scriptname used in _handleNonSearch()

var nextlink;                                              // nextlink defined in _handleNonSearch()
                                                           //          used in: _handleNonSearch()
                                                           //                   enlarge2_act()
                                                           //                   buildpages()
                                                           //                   dispatchBuildimages()
                                                           //                   prevpage()
var narrowurl;                                             // narrowurl defined in _handleNonSearch()
                                                           //           used globally

ucats = global.uCats;
mobject_id = global.mobjectID;
similar_to = global.similarTo;
dsplkys = global.lightboxSphotog;

// end of backward compatibility

var firstpictureonpage = global.firstPicOnPage;
var snum = global.sNum;
var tset = global.tSet;
var showstartnumber_trap = global.showStartNumberTrap;
var currentlbname = global.currentLbName; 
var currentlblist = global.currentLbList;
var feat_requestview = global.featureRequestView;
var typeoflbaction = global.typeOfLbAction;
var sphotog = global.sPhotog;
var pre_q_args = global.preQArgs;
var winW = global.winW;
var baseurl = global.baseURL;
var carnit = global.carnIt;
var currentLbdivMode = global.currentLbdivMode;

var gloCrop = global.gloCrop;
var currentLayer1Mode = global.currentLayer1Mode;

var cartview = global.cartView;
var enlargeview = global.enlargeView;
var viewmode = global.viewMode;

var lightbox_built = global.lightBoxBuilt;

var currMousedOverObj = global.currentMousedOverObject;
var suspendpreviews = global.suspendPreviews;
var scr = global.scr;

var d = global.currentDate;
var currentYear = global.currentYear;
var now = global.currentTime;
var bad = global.bad;

var agt = global.userAgent;
var yourOS = global.userOS;
var yourBrowse = global.userBrowser;

var ver5 = global.netscapeVersion5;

var dynimagesname	= global.dynamicImagesName;
document.currentlbstash = '';
var lbexpansionspace= global.lbExpansionSpace;

var pmousedelta = global.pMouseDelta;

var loadImg = new Image();
loadImg.src = global.loadImage;

var detect = global.userAgentLowerCase;
var OS = global.userOSName;
var browser = global.userBrowserName;
var version = global.userBrowserVersion;

var total = global.total;
var thestring;

var getpost = global.getPost;

var pngsupport = global.pngSupport;

//checking for login status
var gsession = global.gSession;
var debugmode = global.gDebugMode;
var gusert = global.gUserT;
var gcartimages = global.gCartImages;
var gusername = global.gUserName;
var gcurrency = global.gCurrency;
var gfirstname = global.gFirstName;

//
//	NON SEARCH PAGES 
//

if (global.scriptName != ''){
 pixperpage= global.pixPerPage;

 //initialize some page variables
 grange= global.gRange;
 winH = global.winH;
 area = global.area;
 resized = global.resized;

 c=-1;
 fmstartnumber = global.fmStartNumber;

 overflowtype = global.overflowType;

 //optional configurations for this page varies from site to site
 optimizemenu = global.optimizeMenu;
 showphotographer = global.showPhotographer;
 showrelease = global.showRelease;
 showfilesize = global.showFileSize;
 showcaptionview = global.showCaptionView;

 var output = _handleNonSearch({color : color,
                                date : todaysDate,
                                enlargeview : enlargeview,
                                method : method,
                                orient : orient,
                                preQArgs : global.preQArgs,
                                q_args : global.qArgs,
                                qID : global.qID,
                                scriptName : global.scriptName,
                                searchInclude : global.searchInclude,
                                sort : global.sort,
                                specIdx : global.specIdx,
                                ucats : ucats,
                                VCDBrowse : global.VCDBrowse})
 nextlink = output['nextlink'];
 narrowurl = output['narrowurl'];

};

var tempW = global.winW;

if (global.featureRequestView)
{
 document.thisIsFeatureView = true;
};

var lbdisplaymode = global.lbDisplayMode;

var nodeTree = global.nodeTree;

		
//******************************* INTERNALS ****************************//


 function _globals() {

  var d = afDateObj.getCurrentDate();

  global = {
            firstPicOnPage : ( typeof(firstpictureonpage) != 'undefined' ? firstpictureonpage : 0 ),
            sNum : ( snum ? snum : 0 ),
            tSet : ( tset ? tset : 'on' ),
            showStartNumberTrap : 0,
            currentLbName : undefined,
            currentLbList : undefined,
            featureRequestView : feat_requestview,  // needs to be here because global var pre_q_args is set on ajax search page.
            typeOfLbAction : undefined,
            sPhotog : sphotog,                      // needs to be here because global var pre_q_args is set on ajax search page.
            preQArgs : pre_q_args,                  // needs to be here because global var pre_q_args is set on ajax search page.
            qArgs : typeof(q_args) == 'undefined' ? undefined : q_args,
            baseURL : baseurl,                      // needs to be here because global var pre_q_args is set on ajax search page.
            carnIt : 1,                 //flag to do once on load for cartview
            gloCrop : '',
            currentLayer1Mode : document.currentLayer1Mode ? currentLayer1Mode : 'searchresults',
            currentLbdivMode : undefined,    //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...
            cartView : (cartview ? cartview : ''),  //trip this flag to display cart in main window and draw cart in lightbox
            cartViewLocation : "/bin/Cklb?ref=/SwishSearch?cartview=1",
            enlargeView : (enlargeview ? enlargeview : ''),

            lightBoxBuilt : 0,          //basically this is a check so when polllb comes around, if lightBoxBuilt is 0
                                        //and we're logged in, try and build the box!
            currentMousedOverObject : undefined,
            suspendPreviews : 0,
            scr : '',
            currentDate : d,
            currentTime : d.getTime(),      // Normally it was: setCurrentTime(d),
            currentYear : d.getFullYear(),
            dynamicImagesName : typeof(dynimagesname) == 'undefined' ? 'dyn_images' : 'dyn_images',
            bad : undefined,
            userAgent : navigator.userAgent,
            userAgentLowerCase : navigator.userAgent.toLowerCase(),
            userOS : navigator.userAgent.indexOf("Mac")!=-1 ? 'Mac' : 'PC',
            userOSName : undefined,            //this gets populated by findOS()
            userBrowser : navigator.appName == 'Netscape' ? 'NS' : 'IE',
            userBrowserName : undefined,
            userBrowserVersion : undefined,
            netscapeVersion5 : navigator.appVersion.substr(22,1) >= "5" ? 'Yes' : '',
            lbExpansionSpace : 0,
            pMouseDelta : [20,-30],     //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
            loadImage : '/graphics/loading.png',
            pngSupport : 1,             //this also may get altered by the checkPNGsupport() function according to the browser.
            getPost : 'POST',           //had reports of IE caching ajax calls with a GET and firefox not able to complete fake POSTS, so..
                                        //this also may get altered by the checkPostGet() function according to the browser.
            gSession : ggetCookie("gmpsess"),
            debugMode : ggetCookie("debugmode"),
            gUserT : ggetCookie("usert"),
            gCartImages : ggetCookie("gcartimages"),
            gUserName : ggetCookie("username") || ggetCookie("gwhichuser"),
            gCurrency : ggetCookie("currency"),
            gFirstName : ggetCookie("firstname"),
            scriptName : typeof(scriptname) == 'undefined' ? undefined : scriptname,
            viewMode : (typeof(viewmode)!='undefined') ? viewmode : ((typeof(scriptname) !="undefined") ? ggetCookie('gviewmode') : ''),
            pixPerPage : (typeof(scriptname) !="undefined") ? 12 : pixperpage,
            gRange : (typeof(scriptname) !="undefined") ? "legal" : grange,
            winW : (typeof(scriptname) !="undefined") ? 700 : winW,
            winH : (typeof(scriptname) !="undefined") ? 460 : winH,
            area : (typeof(scriptname) !="undefined") ? 12 : area,
            resized : (typeof(scriptname) !="undefined") ? 0 : resized,
            fmStartNumber : (typeof(scriptname) !="undefined") ? 0 : fmstartnumber,
            overflowType : (typeof(scriptname) !="undefined") ? 'hidden' : overflowtype,
            macIE5 : ((navigator.userAgent.indexOf("Mac")!=-1) && (navigator.appName.indexOf("Microsoft")!=-1)) ? 'true' : 'false',
            optimizeMenu : (typeof(scriptname) !="undefined") ? 0 : optimizemenu,
            showPhotographer : (typeof(scriptname) !="undefined") ? 1 : showphotographer,
            showRelease : (typeof(scriptname) !="undefined") ? 1 : showrelease,
            showFileSize : (typeof(scriptname) !="undefined") ? 1 : showfilesize,
            showCaptionView : (typeof(scriptname) !="undefined") ? 1 : showcaptionview,
            pageType : typeof(pagetype)=='undefined' ? undefined : pagetype,
            lbDisplayMode : ggetCookie('ghidelightbox'),
            cartPic : '/graphics/cart_enabled_02.gif',
            searchInclude : searchinclude,
            builderClass : Builder,
            nodeTree : undefined,
            color : color,
            method : method,
            orient : orient,
            sort : sort,
            qID : q_id,
            specIdx : spec_idx,
            VCDBrowse : vcdbrowse,
            uCats : ucats,
            mobjectID : mobject_id,
            similarTo : similar_to,
            total : total,
            uKeys : ukeys,
            lightboxSphotog : dsplkys
           };
 };

function afCart() {

 this.addToCart = addToCart;
 this.awayCart = awayCart;
 this.buildCart = buildCart;
 this.checkCart = checkCart;
 this.deleteLicenseFromCart = deleteLicenseFromCart;
 this.deleteImageFromCart = deleteImageFromCart;
 this.displayCart = displayCart;
 this.displayDispatchedCart = displayDispatchedCart;
 this.cart_build_act = cart_build_act;
 this.cart_mod_act = cart_mod_act;
 this.cart_check_act = cart_check_act;
 this.refreshTopCart = refreshTopCart;
 this.repriceImagesInCart = repriceImagesInCart;

 function addToCart(id,args){

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

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

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

 function deleteLicenseFromCart (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 deleteImageFromCart(id) {
	simplemessage('Deleting image from Shopping Cart <blink>.</blink>','','LB');
	ajax_JSON('/AjaxHandlers/CartDel/' + id + '.json', 'POST', 'callback=cart_mod_act(0)');
 };

 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 repriceImagesInCart (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 awayCart() { //leave site for universal checkout
        top.location = "/bin/Cart?op=ckout";
 };

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

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

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

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

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

	currMousedOverObj = 'shop_cart';
 };

 function cart_build_act(){

	if(! $('LBdiv'))
		return;
	
	if ( ! isNaN(document.JSONobj.getCartDat('total')) ) 
	{
		hidedisplaypanel(1)	// clears the message that was saying loading lightbox or any other transition messages
		
		var cartRoot = $A([]); //aka LBdiv
		
		var cartTotal = document.JSONobj.getCartDat('total');
				
		cartRoot.push(
		Builder.node('div', {id:'lbbuttons', style:'padding:0px; margin:0px; width:127px; height:16px; overflow:hidden'}, [
			nodeTree.cart_build_act__buttons,
			]),
		Builder.node('div', { className:'lbname', style:'padding:3px 0px 0px 3px; margin:0px;'},[
			Builder.node('b', {}, 'Shopping Cart  '+( cartTotal ? cartTotal : 0 ) + ' images '),
			nodeTree.cart_build_act__actions,
		]));
	
		if(document.JSONobj.getCartDat('total')>0){
			
			var tofit = parseInt((winW*0.65)/document.JSONobj.getCartDat('total'));
			if(winH < 340){vlim=25;} else if(winH < 450){vlim=35;} else {vlim=58;}
			if(tofit> vlim){
				tofit=vlim;
			} else if (tofit<18){
				tofit=18;
			}
			
			var cartimages = $A([]);
			for (cti=0;cti<document.JSONobj.getCartDat('total');cti++)
			{
				ctimid = document.JSONobj.getImgDat('id', cti);
				ctid = document.JSONobj.getCartDat('id',cti);				
				
				cartimages.push( Builder.node('div', { 	align:'center', id:'dct'+cti+'s', name:'dct'+cti+'s', valign:'bottom', style:'float:left; height:' + ( tofit + 18 ) + 'px; overflow:hidden;' },[
					Builder.node('a', {	href:'', onclick:'hp(); return false', id:'dct'+cti+'s_cti'},[
						Builder.node('img', { id:'ctimage_'+ctimid, onmouseover:'prloadimg("'+ctimid+'"); sp(this, "'+ctimid+'", "1", "'+tset+'");', onmouseout:'hp();', src: 'http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/'+ctimid+'.JPG', height: tofit, border: 0, className: 'lbimg', hspace: 2	} )
					]),
					Builder.node('div', { style:'padding:2px'}, [
						Builder.node('a', { href:'', onclick:'cart_delete_image("'+ctid+'"); return false;', className:'ctlink', title:'Remove this image from the cart'}, 'X')
					])
				]) );
				
			}
			
			cartRoot.push(
				Builder.node('div', {id:'LBimgdiv', style:'padding:6px 0 0 3px; height: 100%'}, [ cartimages, Builder.node('br', {style:'clear:both'}) ])
			);

			//set future cookie for remaining images in cart
			var date = new Date();
        		date.setTime(date.getTime()+(60*24*60*60*1000));
			gsetCookie('gcartimages',cti,date,'/',gGetCookieDom());
			
		}

		$('LBdiv').replace('<DIV id="LBdiv"></DIV>');
		cartRoot.each(function(carta){
			$('LBdiv').appendChild(carta);	
		});


		
	}
 };	

 function displayDispatchedCart ( 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 refreshTopCart() {
	if(gsession){
		self.location.replace(  ( typeof(baseurl) != 'undefined' ? baseurl : '' ) + "/SwishSearch?n=1&cartview=1&random=" + Math.random(100)); // added random to make cart refresh itself if called locally
	} else {
		self.location=( typeof(baseurl) != 'undefined' ? baseurl : '' ) + "/bin/Cklb?ref=%2FSwishSearch?cartview=1";
	}
 };


};

function afCookie() {

 this.setCookie = setCookie;
 this.setCookie2 = setCookie2;
 this.getCookie = getCookie;
 this.deleteCookie = deleteCookie;
 this.getCookieDomain = getCookieDomain;
 this.setCookieGwhichindex = setCookieGwhichindex;
 this.setCookieGreleasedselect = setCookieGreleasedselect;

 function setCookie(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 getCookie(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 deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
     ((path) ? "; path=" + path : "/") +
     ((domain) ? "; domain=" + domain : "") +
     "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
 };

 function setCookie2(name2,value2) {
  setCookie(name2, value2, '', '/', getCookieDomain());
 };

 function getCookieDomain(){
  var thisdomain = document.domain;
  thisdomain = thisdomain.replace(/^(www(\d*)|tools)\./i,"");
  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;
  var setdom = domainstart + "." + domainend;
  if(domainstart.match(/^co(m?)$/))
        setdom = thisdomain;

  return setdom;
 };

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

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

};

function afDate() {

 this.getCurrentDate = getCurrentDate;
 this.setCurrentTime = setCurrentTime;
 this.fixDate = fixDate;

 function getCurrentDate() {
  var d = new Date();
  return (d);
 }

 function setCurrentTime(currDate) {

  var currentDate = currDate || this.getCurrentDate();

   var now = currentDate;
   fixDate(currentDate);
   now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);

  return (now);

 };

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

};

function afDispatch() {

 this.dispatchAll = dispatchAll;
 this.reDispatch = reDispatch;

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

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

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

};
function afHTML() {

 this.buildPagination = buildPagination;
 this.imageProfile = imageProfile;
 this.centerPanel = centerPanel;
 this.createCoverLayer = createCoverLayer;
 this.createDisplayPanel = createDisplayPanel;
 this.dispatchBuildImages = dispatchBuildImages;
 this.divShim = divShim;
 this.getFooter = getFooter;
 this.hideCoverLayer = hideCoverLayer;
 this.hideDisplayPanel = hideDisplayPanel;
 this.html_share_con_opts = html_share_con_opts;
 this.html_weight_con_opts = html_weight_con_opts;
 this.html_combined_con_opts = html_combined_con_opts;
 this.initShareRadios = initShareRadios;
 this.showDisplayPanel = showDisplayPanel;

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

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

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


 function imageProfile(showid){

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

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

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


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

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

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

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

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

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

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

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

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




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

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

                                        html += '</DIV>';

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

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

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

                                        html += mysiteweight;

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

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

			}
		}
	} 
	return html;
 };

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

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

        }
 };

 function 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 showDisplayPanel(){
	createDisplayPanel();

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

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

 function buildPagination(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="javascript: return false;" onclick="document.currentLayer1Mode=\'searchresults\';prevpage(); return false;"><FONT style=\"font-size:9pt;font-family: Arial;\">&#8592;</FONT> PREV PAGE</A>&nbsp;';
        } else if (showstartnumber <= results_total){
                thehtml+='<FONT style=\"font-family: Arial;color:#AAAAAA;\"><FONT style="9pt;">&#8592;</FONT> PREV PAGE</FONT>&nbsp;';
	}

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

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

		
		thehtml += '&nbsp;&nbsp;[' + showstartnumber + '-';
		if (showendnumber > parseInt(results_total)){
			thehtml +=  '<span id="lastpgtotal">' + results_total + '</span>' + ']&nbsp;of&nbsp;<span id="imgtotal">' + results_total + '</span>';
		} else {
			thehtml += showendnumber + ']&nbsp;of&nbsp;<span id="imgtotal">' + results_total + '</span>';
		}
		thehtml += '</NOBR>';

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

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

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

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

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

 };

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

 function hideDisplayPanel(mode){

	createCoverLayer();
	divshim(0);
	createDisplayPanel();

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

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

 // -> 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 dispatchBuildImages(args) {

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


//LS20081106 moving this to lightbox_delete_image_enl function 
//to fix issue where search results number did not match Layerspage section
//	if ( $("nav_total_images") )
//		$("nav_total_images").innerHTML = id.length;

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

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

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

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

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

                                        if(pagetype=='lb'){
						thehtml+='<div id="endbox" class="endoflightboximages"><nobr>[ end of lightbox images ]</div></nobr></DIV></SPAN> ';
                                        } else {
						thehtml+='<div id="endbox" class="endofsearchresults"><nobr>[ end of search results ]</div></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 == results_total)
			grange = 'outofrange';  //basically we have exactly enough images, 
						//so we want to skip adding the nextlink and the [ end of results ] cell

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

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

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

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

                        }

                } else {

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

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

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

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

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

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


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


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

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

};
function afImage() {

 this.buildImages = buildImages;
 this.priceImage = priceImage;
 this.sizeImageToContainer = sizeImageToContainer;
 this.preloadNextImage = preloadNextImage;
 this.price_image_act = price_image_act;
 this.preLoadImage = preLoadImage;
 this.twidleImagePrice = twidleImagePrice;
 this.twidlePriceImagedelay = twidlePriceImagedelay;

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

	var dems = Element.getDimensions(targetid);

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

 function priceImage(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 preLoadImage(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 < 150){
		smallscreen=1;
		if(typeof(crop)!= 'undefined'){//smallscreen using orientation to decide limiter
			if(crop=='panoramic'){
				theImgAttrs['width'] = 420;
			} else if(crop=='vertical'){
				theImgAttrs['height'] = ((winH - 100) < 180) ? 180 : (winH - 100);
			} else {
				theImgAttrs['height'] = ((winH - 142) < 160) ? 160 : (winH - 142);
			}
		} else {
			theImgAttrs['height'] = 135;
		}
	} else {
		smallscreen=0;
	}
	$("pimid").innerHTML = '';
	
	$('pimid').style.visibility="hidden";
	var theNode = 
	Builder.node('div', {id:'previewpaneshadow2'},[
 		Builder.node('div',{id:'previewpaneshadow1'},[
 			Builder.node('div',{id:'previewpane'},[
		 		Builder.node('div', {style:'padding: 2px 2px 2px 2px;', align:'center'},
     					[ Builder.node('img', theImgAttrs) ]
				),
     				Builder.node('div',{id:'previewpane_metdat_'+prid},'')
		     	]),
			Builder.node('img', {src:'http://globaldyn.ipnstock.com/'+dynimagesname+'/420/60/' + prid + '.JPG', style:'display:none', onload:"if($('previewimg_"+prid+"')) $('previewimg_"+prid+"').src = this.src"})
		])
	]);
	$("pimid").appendChild(theNode);
 };

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

 function twidlePriceImagedelay(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 buildImages(startnumber,mode,resized){
	if(typeof(cartview) != 'undefined' && cartview)
		return;

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

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


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



};
function afInfo() {

 this.enlarge2 = enlarge2;
 this.dispatchEnlarge2 = dispatchEnlarge2;
 this.enlarge2_act__generateTierRows = enlarge2_act__generateTierRows;
 this.enlarge2_act = enlarge2_act;
 this.preloadImages = preloadImages;
 this.setTextOfLayer = setTextOfLayer;

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

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

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

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

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

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

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

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

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


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


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

			}
			else
			{
				myshortcaption = testshortcaption;
			}


			var myrmrftype = document.JSONobj.getImgDat('rmrftype');
			//var myratetiers = document.JSONobj.getImgDat('rfcdimgpricing'); //this is currently preformatted list from templates, could
								//be extended in ajaxhandlers to return a data obj if we need 
								//more granular data
                        var 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') != '') ? '&nbsp;/&nbsp;'+document.JSONobj.getImgDat('agent_name') : '' );
			var myfilesize = (	document.JSONobj.getImgDat('file_size') < 5 ?
					'Scan on Demand'
						:
					document.JSONobj.getImgDat('file_size') + ' Mb');	
			var myreleased = document.JSONobj.getImgDat('released');
			var myrestrictions = document.JSONobj.getImgDat('image_restrictions');
			var mycompallow = document.JSONobj.getImgDat('comp_allow');
                        var mydimensions = ( typeof(showdimensions) != 'undefined' ? document.JSONobj.getImgDat('dimensions') : '');
                        if (mydimensions) //comes as <XVAL>x<YVAL>
                        {
                                var dimr = mydimensions.match(/^(\d+)x(\d+)$/);
                                if (typeof(dimr) == 'object')
                                        mydimensions = '<br/><b>Original Dimensions:</b>&nbsp;'+dimr[1]+'px&nbsp;x&nbsp;'+dimr[2]+'px';
                        }
	
			var nextimage = parseInt(encount) + 1;
			var nextimageid = id[nextimage];
			var previmage = parseInt(encount) - 1;
			var previmageid = id[previmage];
			
			//this ifblock becomes template var: themediainsert
			var themediainsert = '';
			if((! document.thisIsFeatureView) && useInPage && v[encount] && (v[encount] == 'H')){
				var temph= + enid.substring(0,2) + '/' + enid.substring(0,5) + '/' + enid;
				themediainsert += '<EMBED SRC="http://tools.cgibackgrounds.com/qtvideo/' + temph + '.MOV" WIDTH=420 HEIGHT=280></EMBED>';

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

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


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

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

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

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

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

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

 function 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 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 afInit() {

 this.init = init;

 function init() {

 var output;

 _prototype();                          // checks if it should include/load prototype framework
 _globals();                            // initializes various global variables
 checkStatus();                        // checks some sort of status in Layer1 (need more info?) and alters global variable
 prepareEvents();                      // binds various checks to the window.onload event
 findBrowser();                        // determines user browser
 findOS();                             // determines user OS
 styleSheets();                        // determines proper stylesheets to include based on browser/OS
 checkGetPost();                       // double-checks if browser should be using GET or POST and alters global variable
 checkPNGSupport();                    // double-checks if browser supports PNG format and alters global variable
 handleSession({cartView : global.cartView,                  
                cartViewLocation : global.cartViewLocation,
                gSession : global.gSession,
                pageType : global.pageType,
                pre_q_args : global.preQArgs,
                q_args : global.qArgs
               });                                           // checks if session exists, if not bring to startpage
                                                             // otherwise it will set cookie and continue with script.

 pageTypeEvents({ pageType : global.pageType });             // binds various events based on pagetype
 handleBuilder({ Builder : global.builderClass,
                 cartPic : global.cartPic });                // in case a Builder object exists, handle it (not sure what it does)

 };

 function checkGetPost() {
   if (global.userBrowserName == 'Firefox')
       global.getPost = 'GET';
 };

 function checkPNGSupport() {

  if (global.userBrowserName == 'Explorer' && parseInt(global.userBrowserVersion) < 7)
      global.pngSupport = 0;

 };

 function checkStatus() {

  document.currentLayer1Mode = global.currentLayer1Mode;

  //enlarge shouldn't travel
  if( global.currentLayer1Mode == 'enlarge' ) {
        document.currentLayer1Mode = 'searchresults';
        global.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

 };
/*
 function findData(data) {

  var place = 0;
  var info = '';

  for (x in data)
   {
    place = global.userAgentLowerCase.indexOf(x) + 1;
    if (place > 0)
     {
      info = data[x];
      break;
     };
   };

  return ({
           data : info,
           place : place
          });

 };
*/
function findData(data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	};
function findVersion(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
};

 function findBrowser() {

var browsers = [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	];




  global.userBrowserName = findData(browsers) || "An unknown browser";
  global.userBrowserVersion = findVersion(navigator.userAgent) 
				|| findVersion(navigator.appVersion)
				|| "an unknown version";
 //alert(global.userBrowserName+" "+global.userBrowserVersion);	
//  global.userBrowserVersion = detect.charAt(browserData['place'] + x.length);

 };

 function findOS() {

var os = [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	];


  global.userOSName = findData(os) || "An unknown operating system";
 };

 function handleBuilder(args) {

  var Builder = args['Builder'];
  var cartEnabledPic = args['cartPic'];

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

 function handleSession(args) {
 
  var cartView = args['cartView'];
  var cartViewLocation = args['cartViewLocation'];
  var gsession = args['gSession'];
  var pagetype = args['pageType'];
  var pre_q_args = args['pre_q_args'];
  var q_args = args['q_args'];

  if(typeof(gsession) != 'undefined' && gsession)
   {
   if (cartView)
    {
     document.currentLbdivMode = 'cart';	
     document.currentLayer1Mode = 'cartview';
     global.currentMousedOverObject = 'shop_cart';
    }
	
   if ( (typeof(pagetype) != 'undefined' && pagetype=='lb') || (typeof(pre_q_args) != 'undefined' && ( pre_q_args.match(/lb_view=1/) || pre_q_args.match(/fn=/) )) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/lb_view=1/) )) )
    {
     global.pageType = 'lb';
     gsetCookie('gwhichstartpage', '', '', '/', gGetCookieDom());
    }
  }
  else if (cartView)
  {
   top.location=cartViewLocation;
  };

  return ({currMousedOverObj : global.currentMousedOverObject,
           pagetype : global.pageType
         });

 }

 function pageTypeEvents(args) {

  var pageType = args['pageType'];

  if (typeof(pageType) != "undefined"){
   Event.observe(window, 'load', currentpage);
   Event.observe(window, 'resize', checkpageresize);
   Event.observe(window, 'click', hp);
  };
 
 };

 function prepareEvents() {

  // This is a Prototype framework specific piece of code (e.g. Event.observe)

  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')+'&';

     });
  };

 };

 function _prototype() {
  if (typeof($) != 'function')
	document.write('<script src="/javascripts/prototype.js" type="text/javascript"></script>');
 };

 function styleSheets() {
   var styleList = document.styleSheets;
   var styleSheetLoaded = false;

   for(i=0;i<styleList.length;i++){
        if(styleList[i].href != null && styleList[i].href.endsWith("/css/main2.css")){
                styleSheetLoaded = true;
        }
   }
   if(!styleSheetLoaded)
           document.write('<LINK rel="stylesheet" href="/css/main2.css" type="text/css">');

   if ((global.userBrowser == "IE" || global.userBrowserName == "Explorer") && (parseInt(global.userBrowserVersion) <5))
     document.write('<LINK rel="stylesheet" href="/css/fixed4ie.css" type="text/css">');

 };
};
function afLegal() {

 this.copyrightNotice = copyrightNotice;
 this.licenseCostWindow = licenseCostWindow;

 function copyrightNotice(){
    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 licenseCostWindow(id) {
	launchwin('/bin/Rates?calc_only=1&usage=1&ln='+id);
 };

};
function afLightbox() {

 this.newLightbox = newLightbox;
 this.registerLightbox = registerLightbox;
 this.emailLightbox = emailLightbox;
 this.emailConfirmation = emailConfirmation;
 this.lightbox_mod_act = lightbox_mod_act;
 this.simpleMessage = simpleMessage;
 this.addLightboxToCart = addLightboxToCart;
 this.deleteLightbox = deleteLightbox;
 this.renameLightbox = renameLightbox;
 this.buildLightbox = buildLightbox;
 this.validateLightboxName = validateLightboxName;
 this.registerLightboxRename = registerLightboxRename;
 this.changeLightbox = changeLightbox;
 this.addImageToLightbox = addImageToLightbox;
 this.deleteLightboxFromEnlargeView = deleteLightboxFromEnlargeView;
 this.deleteImageFromLightbox = deleteImageFromLightbox;
 this.toggleLightbox = toggleLightbox;
 this.makeLightboxString = makeLightboxString;
 this.refreshTopLightbox = refreshTopLightbox;
 this.saveLightbox = saveLightbox;

// simplemessage(m,mode,trg)
// test_valid_name(v)
// lightbox_mod_act (cruft)
// lightbox_new_send(v)
// lightbox_email(mode)
// lightbox_build(tlba,lname,secr,lbl)
// lightbox_addto(id)
// lightbox_change(newlb)

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

 function registerLightbox(){ // 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 emailLightbox(){ // URL call to send lightbox by email
	var theurl='/bin/Mail';

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

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

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

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

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

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

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

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

 function emailConfirmation(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 addLightboxToCart(){ 
	simplemessage('Adding lightbox images to Shopping Cart <blink>.</blink>','','LB');
	ajax_JSON('/AjaxHandlers/CartLbAdd/0000000000.json', 'POST', 'callback=cart_mod_act(0)');
 };

 function deleteLightbox(){ 
	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 renameLightbox(){
	var tdata = { currentlbname: currentlbname };
	center_panel(290,200, Templates.lightbox_rename__body.evaluate(tdata));
 };

 function buildLightbox(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 = $('LBdiv') ? Position.cumulativeOffset($('LBdiv')) : [0,0];

	var lbbgH = winH - lbdPos[1] - 18; //18 being height of lbbuttons	

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

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

		}

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

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

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

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

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

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


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

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

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

    }

      global.lightBoxBuilt = 1;
	lightbox_built = global.lightBoxBuilt;  // backward compatibility
	return;
 };

 function validateLightboxName(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 registerLightboxRename(){
	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 changeLightbox(newlb){
	currentLbdivMode="lightbox"; 
	cartview=""; 
	document.currentLbdivMode="lightbox"; 

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

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

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

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

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

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

 };

 //deleting lightbox from exlarge view (as opposed to local lb).
 function deleteLightboxFromEnlargeView(locid,callback) {
	var targetlb;
	var loc_mobj = '';
	var owner = gusername;

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

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

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

						//LS20081104 Changed viewmode from 'lb' to cookie-saved gviewmode.
						//Should fix issue where image size changed to medium when images is deleted from lightbox.
        		var section = $H({ showstart:showstartnumber_trap+1, snum:showstartnumber_trap, viewmode:viewmode, buildmode:'', resized:'' }).toJSON();
        		dispatchAll(section);

		}
	}

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

	//LS20081105 Need to update the lightbox results_total on the fly instead of regenerating fullpage
	if ( $("imgtotal") ) {
		$("imgtotal").innerHTML = id.length;
	}
	if ( $("lastpgtotal") ) {
		$("lastpgtotal").innerHTML = id.length;
	}
	if ( $("nav_total_images") )
		$("nav_total_images").innerHTML = id.length;
	results_total = id.length;

 };

 function deleteImageFromLightbox(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 toggleLightbox () {
        if($('LBimgdiv').hidden == 1) {
                $('LBimgdiv').style.display = 'block';

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

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

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

        currentpage();
 };

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

	newlba = newlba.reverse();

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

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

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

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

 //ALL THIS DOES IS SAVE YOUR CURRENT LIGHTBOX
 function saveLightbox(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 );
 };



};
function afMouse() {

 this.mouseSnap = mouseSnap;
 this.findMouse = findMouse;
 this.getMouseCoordinates = getMouseCoordinates;

 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 findMouse(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 getMouseCoordinates(e) {
  if(browser != 'Explorer'){
    msX = e.pageX
    msY = e.pageY
  } else {
    msX = event.clientX + document.body.scrollLeft
    msY = event.clientY + document.body.scrollTop
  }  
	if( msX < panelx || msY > (panely+panelheight)){
		document.isn.Keywords.blur();
                hidedisplaypanel(1);
        }

 };


};
function afPage() {

 this.checkPageResize = checkPageResize;
 this.currentPage = currentPage;
 this.nextPage = nextPage;
 this.preloadNextPage = preloadNextPage;
 this.previousPage = previousPage;
 this.setBackPage = setBackPage;
 this.setupPageSize = setupPageSize;

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

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

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



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

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

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

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

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

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

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

	}

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

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

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

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

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

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

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

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


/*	if(document.currentLayer1Mode == 'enlarge'){
			imagespaceheight=winH - menuheight;
		} */
	truevertHeight = winH;
	//winH=imagespaceheight + menuheight; // restore it to accomodate narrowbar and footer // it's already limited.. this crop is too close..
	if(winH<150){
		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 nextPage(){
        buildimages(lastimage,"next");
 };

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

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

 function 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 preloadNextPage(){
        preloadcurrent=prestart;
        preloadnextimg();
 };

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


};
function afPreview() {

 this.hp = hp;
 this.hpoff = hpoff;
 this.portSize = portSize;
 this.previewSet = previewSet;
 this.sp = sp;
 this.sp_act = sp_act;

 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 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 sp_act(oObjId, imageid, mode, dex, tryCtr){  //imagename, imagenum, license, photographer, 
	//pshown=1;

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


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

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

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

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

 function hp(){
	currMousedOverObj = '';
	Event.stopObserving(document, 'mousemove', pfindmouse);
	if (!$('pimid'))
		return;
	new Effect.Fade('pimid', {duration: 0.3, from:Element.getOpacity($('pimid'))})
	setTimeout("hpoff()",300);
 };
 function portSize() {
	var retY = parseInt(document.body.offsetHeight - 20);
	var retX = parseInt(document.body.offsetWidth - 20);

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

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

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


};
function afRelease() {

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

	return false;	
 };

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

        var shownIds = $A();

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

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

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

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

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

        }
        return false;
 };

 function validateCheckboxes(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 iconStatus(){
	 if(viewmode && typeof(iconbackground) != 'undefined'){
 		//clear them
 		if($('iconlist')){$('iconlist').style.background='none';}
 		if($('iconbig')){$('iconbig').style.background='none';}
 		if($('icontiny')){$('icontiny').style.background='none';}
 		if($('iconmed')){$('iconmed').style.background='none';}
 		if($('iconhuge')){$('iconhuge').style.background='none';}
 		if($('iconlarge')){$('iconlarge').style.background='none';}
                 //set it
 		if(viewmode == 'table'){
 			if($('iconbig')){$('iconbig').style.background=iconbackground;}
                 } else  if(viewmode == 'list'){
 			if($('iconlist')){$('iconlist').style.background=iconbackground;}
                 } else  if (viewmode == 'tiny'){
 			if($('icontiny')){$('icontiny').style.background=iconbackground;}
                 } else if (viewmode == 'med'){
 			if($('iconmed')){$('iconmed').style.background=iconbackground;}
                 } else if (viewmode == 'huge'){
 			if($('iconhuge')){$('iconhuge').style.background=iconbackground;}
                 } else if (viewmode == 'large'){
 			if($('iconlarge')){$('iconlarge').style.background=iconbackground;}
                 }
         }
 };


};
function afSearch() {

 this.checkIt = checkIt;
 this.expandIt = expandIt;
 this.narrowIt = narrowIt;
 this.optimizeSearch = optimizeSearch;
 this.popKeywords = popKeywords;
 this.searchType = searchType;
 this.standardSearch = standardSearch;
 this.searchPreferences = searchPreferences;
 this.writeSearch = writeSearch;
 this.writeSimilar = writeSimilar;
 this.writeStandardSimilar = writeStandardSimilar;
 this.writeStandardSearch = writeStandardSearch;

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

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

               prev_keys = unescape(prev_keys);
       	}

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

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

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


		if($('displaypanel'))
		{


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

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

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

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


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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

 };

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

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

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

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


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

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



};
function afShare() {

 this.checkID = checkID;
 this.makeShareControlString = makeShareControlString;
 this.saveReleaseControl = saveReleaseControl;
 this.saveShares = saveShares;
 this.shareSetPage = shareSetPage;
 this.toggleShareControlCookie = toggleShareControlCookie;
 this.validateRadioButtons = validateRadioButtons;

 function makeShareControlString(id,value) {

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

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

 function toggleShareControlCookie(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 checkID(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 saveShares(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 saveReleaseControl(dex) { //SAVE RELEASE CONTROL..

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

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

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

 function validateRadioButtons(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 shareSetPage(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 afSystem() {

 this.debug = debug;
 this.empty = empty;
 this.getVars = getVars;
 this.screenInfo = screenInfo;

 function debug(mmm,val){
	if(typeof(debugmode) !='undefined' && debugmode=='yes'){
		alert(mmm + '=' + val);
	}
 };

 function empty(){};

 //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 screenInfo(){
        setuppagesize();
        alert($F('pixperpage') + " browser is " + browser + " and os is " + OS + 
				" width=" + document.body.offsetWidth + "," + self.innerWidth + "," + winW +
				" winH="+winH+", truevertHeight="+truevertHeight
				);
 };


};
function afURL() {

 this.createNextLink = createNextLink;

 function createNextLink (args) {

 var enlargeview = args['enlargeview'];
 var method = args['method'];
 var qArgs = args['q_args'];
 var qID = args['qID'];
 var ucats = args['ucats'];

 var color = args['color'];
 var date = args['date'];
 var orient = args['orient'];
 var preQArgs = args['preQArgs'];
 var scriptName = args['scriptName'];
 var searchInclude = args['searchInclude'];
 var sort = args['sort'];
 var specIdx = args['specIdx'];
 var VCDBrowse = args['VCDBrowse'];
 var nextLink = String(scriptName + "?" +
				(color ? "&color=" + color : '' ) + 
				( orient ? "&orient=" + orient : '' ) + 
				(specIdx ? "&spec_idx=" + specIdx : '' ) + 
				(sort ? "&sort=" + sort : '') + 
				(searchInclude ? "&searchinclude=" + searchInclude : '') + 
				((typeof(VCDBrowse) != 'undefined' && VCDBrowse) ? '&VCDBrowse='+VCDBrowse : '' )
			) ;


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

 var narrowURL = nextLink + "&snum=0";

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

 nextLink +=  "&method=" + method  + "&q_id=" + qID + "&" + ucats;
 if (enlargeview)
   setTimeout("enlarge2('"+enlargeview+"', 0)", 500);

 return ({narrowurl : narrowURL,
          nextlink : nextLink});

 };

};
function afWindow() {

 this.displayWindow = displayWindow;
 this.displayWindow2 = displayWindow2;
 this.maximizeScreen = maximizeScreen;
 this.popUp = popUp;

 function popUp(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 maximizeScreen(){
        window.moveTo(0,0);
        window.resizeTo(screen.availWidth,screen.availHeight);
	if (self.location)
		self.location.href=self.location.href;
 };

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

};

