//Begin: /Scripts/ServiceDescription_CartScriptService.js

/*
* DEFINE SERVICES FOR 
* Checkout/CartScriptService.asmx
* ********************************************/
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.ValidateItems', { submissionTemplate: ["productUids"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.UpdateCartItemPrice', { submissionTemplate: ["productUid"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.AddItemsToCartContainer', { submissionTemplate: ["cartProductUids", "cartContainer"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.DeleteItemsFromCartContainer', { submissionTemplate: ["cartProductUids", "cartContainer"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.MoveItemWithInCart', { submissionTemplate: ["cartProductUids", "cartContainer"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.AddOfferingToCart', { submissionTemplate: ["offeringUid"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.AddProductToCart', { submissionTemplate: ["corbisId", "productUid"] } );
CorbisUI.ServiceManager.defineService('Checkout.CartScriptService.GetPricedPricingDisplay', { submissionTemplate: ["productUid"] });
window.addEvent('domready', function() {
    CorbisUI.NameSpace.register('Corbis.Web.UI.Checkout.CartScriptService', { Alias: CorbisUI.ServiceManager.Checkout.CartScriptService, ForceAlias: true });
});

//End: /Scripts/ServiceDescription_CartScriptService.js
//Begin: /Scripts/ServiceDescription_SubscriptionScriptService.js

/*
* DEFINE SERVICES FOR 
* Picplan/SubscriptionScriptService.asmx
* ********************************************/
CorbisUI.ServiceManager.defineService('Picplan.SubscriptionScriptService.DownloadSubscriptionImages', { submissionTemplate: ["projectName", "fileSize", "remainingCount", "isContinue", "isAdditionalPurchase"] });
CorbisUI.NameSpace.register('CorbisUI.ServiceManager.Subscription', { Alias: CorbisUI.ServiceManager.Picplan });
window.addEvent('domready', function() {
    CorbisUI.NameSpace.register('Corbis.Web.UI.Subscription', { Alias: CorbisUI.ServiceManager.Picplan });
});
//End: /Scripts/ServiceDescription_SubscriptionScriptService.js
//Begin: /Scripts/ServiceDescription_LightboxScriptService.js

/*
* DEFINE SERVICES FOR 
* Lightboxes/LightboxScriptService.asmx
* ********************************************/

// JSON RESPONSES
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.UpdateLightboxProductNote', { submissionTemplate: ["productUid", "notedUid", "noteText"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.GetLightboxCOFFImages', { submissionTemplate: ["lightboxId", "pageNumber", "pageSize"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.GetMoveModifiedDate', { submissionTemplate: ["lightboxId"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.GetLightboxCopyImages', { submissionTemplate: ["lightboxId", "pageNumber", "pageSize"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.CopyLightboxImages', { submissionTemplate: ["fromLightboxId", "toLightboxId", "imageUids", "purgeItems"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.ValidateItemsForCOFF', { submissionTemplate: ["fromLightboxId", "imageUids"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.ContinueToCheckoutCOFFItems', { submissionTemplate: ["fromLightboxId", "coffOrderImages"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.GetLightBoxDropDownListForCopy', { submissionTemplate: ["lightboxTreeSortBy"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.DeleteLightboxProductNote', { submissionTemplate: ["productUid"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.SavePreviewPreference', { submissionTemplate: ["previewState"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.GetLightBoxDropDownListForMove', { submissionTemplate: ["lightboxIdToMove", "lightboxTreeSortBy"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.MoveLightBox', { submissionTemplate: ["lightboxIdToMove", "newParentLightboxId"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.CreateLightbox', { submissionTemplate: ["username", "lighboxName"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.RenameLightbox', { submissionTemplate: ["lightboxId", "newLightboxName"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.UpdateSharedLightbox', { submissionTemplate: ["lightboxId", "lightboxName", "clientName", "noteUid", "noteText"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.GetMemberAssociates');
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.AddMemberAssociate', { submissionTemplate: ["associateUserName"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.CheckoutQuickPicImages', { submissionTemplate: ["images"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.RemoveMemberAssociates', { submissionTemplate: ["associateUserNames"] });
CorbisUI.ServiceManager.defineService('Lightboxes.LightboxScriptService.TransferLightbox', { submissionTemplate: ["lightboxId", "associateUserNames", "removeSource"] });

window.addEvent('load', function() {
    CorbisUI.NameSpace.register('Corbis.Web.UI.Lightboxes', { Alias: CorbisUI.ServiceManager.Lightboxes, ForceAlias: true });
});
//End: /Scripts/ServiceDescription_LightboxScriptService.js
//Begin: /Scripts/CorbisUI.SearchConstructors.js

/****************************
NAMESPACES
****************************/
if (typeof (CorbisUI) == 'undefined') {
    CorbisUI = {};
}

/////////////////////////////////////
// CONSTRUCTORS
// generic templates incorporated
// by other objects with Implement
/////////////////////////////////////
CorbisUI.SearchConstructors = {

    licenseMapping: ['Unknown', 'RM', 'RF', 'RS'],

    /* block constructor for lightbox and quickpic item */
    pinkyBlockConstructor: new Class({

        closeButton: null,
        cartButton: false,
        quickCheckoutButton: false,

        mediaUID: null,
        corbisID: null,
        realProductUID: null,
        lightboxID: 0,
        licenseModel: null,

        isOutline: false,
        isRfcd: false,

        injectWhere: null,

        block: null,

        isInCart: function() {
            return CorbisUI.cartMediaUidList.has(this.mediaUID);
        },

        highlightIcon: function(iconType) {
            if (iconType == 'cart') this.block.addClass('inCart');
        },

        createBlock: function(newItem, caller) {
            var objRef, imageRef, imageClone, title, coords, clickContent, clickLink;
            var coordsBase = {
                marginTop: 90,  //basic dimensions of container
                width: 90,      // minimum width
                height: 90      // minimum height
            };

            objRef = (newItem) ? this.tempObject : CorbisUI.ProductCache.get(this.mediaUID);

            //console.log('TEMPOBJECT');
            //console.log(this.tempObject);
            //debugger
            this.isOutline = (newItem) ? this.tempObject.IsOutLine : CorbisUI.ProductCache.get(this.mediaUID).isOutline;
            this.isRfcd = (newItem) ? this.tempObject.IsRfcd : CorbisUI.ProductCache.get(this.mediaUID).isRfcd;
            //this.isOutline = this.tempObject.IsOutline;
            //console.log('ISOUTLINE: ' + this.isOutline);

            if (!newItem) objRef.setupObject();

            this.injectWhere = (newItem) ? 'bottom' : 'top';

            var objRefLicenseModal = (newItem) ? CorbisUI.SearchConstructors.licenseMapping[objRef.LicenseModel] : objRef.licenseModel;
            this.licenseModel = Corbis.CommonSchema.Contracts.V1.LicenseModel.toLocalizedString(Corbis.CommonSchema.Contracts.V1.LicenseModel[objRefLicenseModal]);
            //this.licenseModel = (newItem) ? CorbisUI.SearchConstructors.licenseMapping[objRef.LicenseModel] : objRef.licenseModel;

            var Wrap = new Element('div', {
                'class': this.constructorType + 'Block',
                'corbisid': this.corbisID
            });

            var closeWrap = new Element('div')
                                .addClass('hoverBtn')
                                .addClass('closeIcon')
                                .inject(Wrap);

            var closeInput = new Element('input').setProperties({
                'class': 'hovable',
                'value': '',
                'title': CorbisUI.GlobalVars.SearchResults.text.deleteBtnAlt,
                'alt': CorbisUI.GlobalVars.SearchResults.text.deleteBtnAlt
            }).addEvent('click', this.deleteButtonEvent.bindWithEvent(this))
                .inject(closeWrap);

            this.closeButton = closeInput;
            //note: if newitem is null, IsRfcd also available?
            if (objRef.IsRfcd == true) {
                clickContent = '/ImageGroup/' + Corbis.Image.Contracts.V1.ImageMediaSetType.RFCD + '/' + objRef.CorbisId;
                clickLink = function() { window.location.href = clickContent; return false; };
            }
            else {

                if (caller == 'quickpic' || caller == 'subcription') {
                    clickContent = '../Enlargement/Enlargement.aspx?id=' + ((newItem) ? objRef.CorbisId : this.corbisID) + '&caller=' + caller;
                }
                else {
                    clickContent = '../Enlargement/Enlargement.aspx?id=' + ((newItem) ? objRef.CorbisId : this.corbisID) + '&puid=' + ((newItem) ? objRef.ProductUid : this.realProductUID) + '&caller=' + caller;
                }

                clickLink = function() { EnlargeImagePopUp(clickContent); return false; };
            }
            var thumbBlock = new Element('div').setProperties({
                'class': 'thumbWrap'
            }).setStyles({
                'cursor': 'pointer',
                'background': '#262626'
            });

            if (clickLink) {
                thumbBlock.addEvent('click', clickLink);
            }
            //            else {
            //                if (Browser.Engine.trident) {
            //                    clickContent = '../Enlargement/Enlargement.aspx?id=' + this.corbisID + '&puid=' + this.realProductUID + '&caller=' + caller;
            //                    clickLink = function() { EnlargeImagePopUp(clickContent); return false; };
            //                    thumbBlock.addEvent('click', clickLink);
            //                }
            //            }
            thumbBlock.inject(Wrap);

            if (!newItem) {
                imageRef = objRef.thumbWrap.getFirst('img');
                imageClone = imageRef.clone();
                coords = CorbisUI.SearchConstructors.helpers.ScaleImage2(objRef.thumbWrap.getFirst('img'), coordsBase);
                imageClone.setStyles(coords);

                // Remove the onclick property since it isn't formatted correctly (and we added a click event above).
                if (imageClone.getProperty('onclick')) imageClone.removeProperty('onclick');

                title = imageRef.getProperty('title');

            } else {

                this.realProductUID = objRef.ProductUid;

                imageClone = new Element('img', { 'src': objRef.Url128 });

                if (objRef.AspectRatio < 1) {
                    coords = {
                        width: 90 * objRef.AspectRatio,
                        height: 90
                    };
                } else {
                    coords = {
                        width: 90,
                        height: 90 / objRef.AspectRatio,
                        marginTop: (90 - (90 / objRef.AspectRatio)) / 2
                    };
                }

                imageClone.setStyles(coords);

                title = objRef.CorbisId + ' - ' + objRef.Title;

            }

            imageClone.setProperties({
                'title': title,
                'alt': title
            });

            imageClone.inject(thumbBlock);

            this.licenseBlock = new Element('div')
                                    .addClass(this.licenseModel + 'color infoBox')
                                    .inject(Wrap);

            var licenseWrap = new Element('div').addClass('license').inject(this.licenseBlock);

            var LT = new Element('span').set('text', this.licenseModel).inject(licenseWrap);

            this.block = Wrap;

            if (newItem) this.tempObject = null;

            //LT.addEvent('click', this.test.bindWithEvent(this));
        }
        //        ,

        //        test: function(event) {

        //            //console.log('+=== SB [ ' + this.licenseModel + ' ] ITEM INFORMATION ===================================================+');

        //            //console.log('     license: ' + this.licenseModel);
        //            //console.log('     corbisID: ' + this.corbisID);
        //            //console.log('     mediaUID: ' + this.mediaUID);
        //            //console.log('     productUID: ' + this.realProductUID);
        //            //console.log('     lightboxID: ' + this.lightboxID);
        //            //console.log('     isOutline: ' + this.isOutline);
        //            //console.log('     isRfcd: ' + this.isRfcd);

        //        }

    }),



    helpers: {

        ScaleImage: function(ele, options) {

            var Base = {
                marginTop: 90, //basic dimensions of container
                width: 90, // minimum width
                height: 90 // minimum height
            };
            if (options) Base = $merge(Base, options);

            //if(!margin) margin = 128;

            //console.log(Base);

            var OrigCoords = ele.getCoordinates();
            var Coords = { width: 0, height: 0 };
            Coords.width = OrigCoords.width;
            Coords.height = OrigCoords.height;

            var newValues = Base;

            for (var n in Coords) {
                var m = Base[n];
                if (Coords[n] > m && Base[n]) {
                    var o = (n == 'width') ? 'height' : 'width';
                    var r = m / Coords[n];
                    newValues[n] = m;
                    newValues[o] = Math.ceil(Base[o] * r);
                }
            }

            var wrap, img, m;



            if (newValues.height <= Base.marginTop) {
                wrap = (Base.marginTop / 2); //half of wrapper
                img = (newValues.height / 2); //half of image
                newValues.marginTop = (wrap - img);
            }

            if (Coords.height < options.marginTop) {
                newValues.width = 90;
            }

            //console.log('NEW VALUES');
            //console.log(newValues.toSource());

            return newValues;
        },

        ScaleImage2: function(ele, options) {
            var Base = {
                marginTop: 90, //basic dimensions of container
                width: 90, // minimum width
                height: 90 // minimum height
            };
            if (options) Base = $merge(Base, options);

            //if(!margin) margin = 128;

            //console.log(Base);

            var OrigCoords = ele.getCoordinates();
            var Coords = { width: 0, height: 0 };
            Coords.width = OrigCoords.width;
            Coords.height = OrigCoords.height;

            var newValues = Base;

            if (Coords.height > Coords.width) {
                newValues.width = newValues.width * (Coords.width / Coords.height);
            }
            else {
                newValues.height = newValues.height * (Coords.height / Coords.width);
            }

            var wrap, img, m;

            if (newValues.height <= Base.marginTop) {
                wrap = (Base.marginTop / 2); //half of wrapper
                img = (newValues.height / 2); //half of image
                newValues.marginTop = (wrap - img);
            }

            if (Coords.height < options.marginTop) {
                newValues.width = 90;
            }

            newValues.width = newValues.width.round();
            newValues.height = newValues.height.round();
            newValues.marginTop = newValues.marginTop.round();

            return newValues;
        }

    }
};

//End: /Scripts/CorbisUI.SearchConstructors.js
//Begin: /Scripts/CorbisUI.SearchModels.js

/****************************
    NAMESPACES
****************************/
if (typeof (CorbisUI) == 'undefined') {
    CorbisUI = {};
}


/////////////////////////////////////
// MODELS
/////////////////////////////////////
CorbisUI.SearchModels = {

    // product block model
    ProductBlock: new Class({
        Implements: [Options, Events],

        productBlock: null,

        LB: null,
        //QPon: null,
        //QPoff: null,
        QP: null,
        CT: null,
        SB: null,

        activeStates: {
            LB: false,  // lightbox
            QP: false,  // QuickPic
            CT: false,  // cart
            SB: false   // subscription
        },

        subscriptionImage: false,

        licenseModel: null,
        productUID: null,
        corbisID: null,
        isSelected: false,

        isOutline: false,

        QPenabled: false,
        SBenabled: false,
        CTenabled: false,

        basketCase: false,

        refreshPage: false,

        thumbWrap: null,

        isSetup: false,

        initialize: function(el) {
            if (!el) return false;
            this.productBlock = $(el);
            this.isSetup = false;

            var properties = this.productBlock.getProperties('licensemodel', 'productuid', 'corbisid', 'isoutline', 'subscription');
            //console.log(properties);
            this.licenseModel = properties.licensemodel;
            this.productUID = properties.productuid;
            this.corbisID = properties.corbisid;
            this.isOutline = properties.isoutline || false;
            if (properties.subscription == "true") this.subscriptionImage = true;

            // store objecet reference on product block
            //this.productBlock.store('objectReference', this);
            CorbisUI.ProductCache.addObject(this.productUID, this);
            CorbisUI.ProductCache.addObject(this.corbisID, this.productUID);

            //console.log('IN CART? '+CorbisUI.cartMediaUidList.has(this.productUID));
            if (CorbisUI.cartMediaUidList.has(this.productUID)) this.updateIcon('CT', 'selectIcon');

            // add test click stuff
            // TODO: remove later
            if (Browser.Engine.trident) {
                return false;
            } else {
                this.productBlock.getElement('div.LT').addEvent('click', this.test.bindWithEvent(this));
            }
        },

        // this is to give a method to setup an object on demand
        setupObject: function() {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.setupObject');
            if (!this.isSetup) {
                this.thumbWrap = this.productBlock.getElement('.thumbWrap');

                this.isSelected = this.productBlock.hasClass('ProductSelected');

                this.QPenabled = (this.productBlock.getElement('.ICN_quickpic') == null) ? false : true;
                this.SBenabled = (this.productBlock.getElement('.ICN_subscription') == null) ? false : true;

                this.CTenabled = (this.productBlock.getElement('li[class^=ICN_cart]') == null) ? false : true;

                this.LB = this.productBlock.getElement('.ICN_lightbox');

                this.activeStates.LB = (this.LB == null) ? false : this.LB.hasClass('ICN_lightbox_selected');

                if (this.QPenabled) {
                    /*this.QPon = this.productBlock.getElement('.QP_on');
                    this.QPoff = this.productBlock.getElement('.QP_off');
                    this.activeStates.QP = this.QPon.hasClass('ICN_quickpic_selected');*/

                    this.QP = this.productBlock.getElement('.ICN_quickpic');
                    this.activeStates.QP = this.QP.hasClass('ICN_quickpic_selected');
                }
                if (this.SBenabled) {
                    this.SB = this.productBlock.getElement('.ICN_subscription');
                    this.activeStates.SB = this.SB.hasClass('ICN_subscription_selected');
                }

                if (this.CTenabled) {
                    this.CT = this.productBlock.getElement('li[class^=ICN_cart]');
                    this.basketCase = this.CT.hasClass('ICN_cartBasket');

                    if (this.basketCase) {
                        this.activeStates.CT = this.CT.hasClass('ICN_cartBasket_selected');
                    } else {
                        this.activeStates.CT = this.CT.hasClass('ICN_cart_selected');
                    }

                }
                if (this.SBenabled) {
                    this.SB = this.productBlock.getElement('.ICN_subscription');
                    this.activeStates.SB = this.SB.hasClass('ICN_subscription_selected');
                }
                this.isSetup = true;
            }
            return this;
        },

        // quick way to check lightbox status
        checkLightboxStatus: function() {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.checkLightboxStatus');
            var status = (this.isSetup) ? this.activeStates.LB : this.productBlock.getElement('.ICN_lightbox').hasClass('ICN_lightbox_selected');
            return status;
        },


        // TODO: remove later
        test: function(event) {
            this.setupObject();
            //console.log('+=== ITEM INFORMATION ===================================================+');

            //console.log('     license: ' + this.licenseModel);
            //console.log('     corbisID: ' + this.corbisID);
            //console.log('     productUID: ' + this.productUID);
            //console.log('     mediaUID: ' + this.mediaUID);
            //console.log('     isSelected: ' + this.isSelected);
            //console.log('     isOutline: ' + this.isOutline);
            //console.log('     QPenabled: ' + this.QPenabled);
            //console.log('     CTenabled: ' + this.CTenabled);
            //console.log('     basketCase: ' + this.basketCase);
            //console.log('     activeStates: ' + this.activeStates.toSource());
            //console.log('     Subscription: ' + this.subscriptionImage);
        },

        updateIcon: function(type, action) {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.updateIcon');
            this.setupObject();
            //console.log(type+' : '+action);
            this[action](type);
        },

        selectIcon: function(type, priceDetails) {          
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.selectIcon');
            //console.log(this);
            //console.log(type)
            switch (type) {
                case "LB":
                    //console.log(this.LB.hasClass('ICN_lightbox_selected'));
                    if (!this.LB.hasClass('ICN_lightbox_selected')) this.LB.toggleClass('ICN_lightbox_selected');
                    var image = this.LB.getElement('img[id$=Img2]');
                    if (image) {
                        image.setProperties({
                            'title': CorbisUI.GlobalVars.SearchResults.text.removeLightBoxAlt,
                            'alt': CorbisUI.GlobalVars.SearchResults.text.removeLightBoxAlt
                        });
                    }
                    this.activeStates.LB = true;
                    break;
                case "QP":
                    //console.log(this.LB.hasClass('ICN_quickpic_selected'));
                    if (this.QPenabled) {
                        //if (!this.QPon.hasClass('ICN_quickpic_selected')) this.QPon.addClass('ICN_quickpic_selected');
                        //if (!this.QPoff.hasClass('ICN_quickpic_selected')) this.QPoff.addClass('ICN_quickpic_selected');
                        if (!this.QP.hasClass('QP_on')) this.QP.addClass('QP_on');
                        if (this.QP.hasClass('QP_off')) this.QP.removeClass('QP_off');
                        if (!this.QP.hasClass('ICN_quickpic_selected')) this.QP.addClass('ICN_quickpic_selected');
                        var image = this.QP.getElement('img[id$=qpIcon]');
                        if (image) {
                            image.setProperties({
                                'title': CorbisUI.GlobalVars.SearchResults.text.removeQuickpicAlt,
                                'alt': CorbisUI.GlobalVars.SearchResults.text.removeQuickpicAlt
                            });
                        }
                        this.activeStates.QP = true;
                    }
                    break;
                case "SB":
                    if (!this.SB.hasClass('ICN_subscription_selected')) this.SB.toggleClass('ICN_subscription_selected');
                    if (this.SBenabled) {
                        var image = this.SB.getElement('img[id$=sbIcon]');
                        if (image) {
                            image.setProperties({
                                'title': CorbisUI.GlobalVars.SearchResults.text.removeSubscriptionAlt,
                                'alt': CorbisUI.GlobalVars.SearchResults.text.removeSubscriptionAlt
                            });
                        }
                    }
                    this.activeStates.SB = true;
                    break;
                case "CT":
                    //console.log(this.LB.hasClass('ICN_cart_selected'));
                    if (this.CTenabled) {
                        if (this.basketCase) {
                            if (!this.CT.hasClass('ICN_cartBasket_selected')) this.CT.addClass('ICN_cartBasket_selected');
                        } else {
                            if (!this.CT.hasClass('ICN_cart_selected')) this.CT.addClass('ICN_cart_selected');
                        }

                        this.activeStates.CT = true;
                        CorbisUI.cartMediaUidList.set(this.productUID, true);
                        var image = this.CT.getElement('img[id$=addToCartImage]');
                        if (image) {
                            image.setProperties({
                                'title': CorbisUI.GlobalVars.SearchResults.text.removeCartAlt,
                                'alt': CorbisUI.GlobalVars.SearchResults.text.removeCartAlt
                            });
                        }
                        
                        if (priceDetails && priceDetails.price) {
                            var addToCartButton = this.CT.getParent().getElement("a[id$=priceImageLink]");
                            if (addToCartButton) {
                                var self = this;
                                var priceLinkHandler = null;
                                var lightboxId = $(document.body).getElement('div.Lightbox div.Active').id;
                                if(priceDetails.isContactUs) {
                                    priceLinkHandler = function() { CorbisUI.RequestPricing.showModal(self.corbisID, lightboxId, 'Lightbox'); };
                                }
                                else {
                                    if(this.licenseModel == "RM") {
                                        priceLinkHandler = function() { PriceImage('../Pricing/SRMPricing.aspx?CorbisId=' + self.corbisID + '&ProductUid=' + self.productUID + '&ParentPage=Lightbox&LightboxId=' + lightboxId,720,578); };
                                    }
                                    else if(this.licenseModel == "RF") {
                                        priceLinkHandler = function() { PriceImage('../Pricing/RFPricing.aspx?CorbisId=' + self.corbisID + '&ProductUid=' + self.productUID + '&ParentPage=Lightbox&LightboxId=' + lightboxId,640,573); };
                                    }
                                }
                                addToCartButton.removeProperty('onclick');
                                if (Browser.Engine.trident) {
                                    addToCartButton.onclick = null;
                                }
                                addToCartButton.removeEvents();
                                addToCartButton.addEvent('click', priceLinkHandler);
                                
                                var price = priceDetails.price.replace("(", "").replace(")", "");
                                var productBlockNode = this.CT.getParent().getParent().getParent().getParent().getParent();
                                var existingPrice = productBlockNode.getElement("span div.productPriceInfo div");
                                
                                if(existingPrice) {
                                    existingPrice.set("html", price);
                                    
                                    //reset handler for contact us support
                                    existingPrice.removeProperty('onclick');
                                    existingPrice.removeEvents();
                                    existingPrice.addEvent('click', priceLinkHandler);
                                    
                                    var existingPriceStatus = productBlockNode.getElement("span div.productPriceInfo div.priceStatus");
                                    if(existingPriceStatus && !priceDetails.priceStatusText) {
                                        existingPriceStatus.dispose();
                                    }
                                    if(!existingPriceStatus && priceDetails.priceStatusText) {
                                        this.addPriceStatusToProductBlock(productBlockNode.getElement("span div.productPriceInfo"), priceDetails.priceStatusText)
                                    }
                                }
                                else {
                                    var priceNode = new Element('span');
                                    var priceInfoNode = new Element('div', {
                                        "class": "productPriceInfo hide-for-print"
                                    });
                                    var priceTextNode = new Element('div', {
                                        "class": "price",
                                        "html": price,
                                        'events': {
                                            'click': priceLinkHandler
                                        }
                                    });
                                    priceNode.appendChild(priceInfoNode);
                                    priceInfoNode.appendChild(priceTextNode);
                                    productBlockNode.appendChild(priceNode);
                                    
                                    if(priceDetails.priceStatusText) {
                                        this.addPriceStatusToProductBlock(priceInfoNode, priceDetails.priceStatusText)
                                    }
                                }
                            }
                        }
                    }
                    break;
            }
            // update productblock glow
            this.highlightBlock();
        },
        
        addPriceStatusToProductBlock: function(parentNode, priceStatusText) {
            var priceStatusNode = new Element('div', {
                "class": "priceStatus",
                "html": priceStatusText
            });
            parentNode.appendChild(priceStatusNode);
        },

        deselectIcon: function(type) {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.deselectIcon');
            //console.log('deselectIcon(\''+type+'\')');
            switch (type) {
                case "LB":
                    if (this.LB.hasClass('ICN_lightbox_selected')) this.LB.toggleClass('ICN_lightbox_selected');
                    var image = this.LB.getElement('img[id$=Img2]');
                    if (image) {
                        image.setProperties({
                            'title': CorbisUI.GlobalVars.SearchResults.text.addToLightBoxAlt,
                            'alt': CorbisUI.GlobalVars.SearchResults.text.addToLightBoxAlt
                        });
                    }
                    this.activeStates.LB = false;
                    break;
                case "QP":
                    if (this.QPenabled) {
                        //if (this.QPon.hasClass('ICN_quickpic_selected')) this.QPon.toggleClass('ICN_quickpic_selected');
                        //if (this.QPoff.hasClass('ICN_quickpic_selected')) this.QPoff.toggleClass('ICN_quickpic_selected');
                        if (this.QP.hasClass('QP_on')) this.QP.removeClass('QP_on');
                        if (!this.QP.hasClass('QP_off')) this.QP.addClass('QP_off');
                        if (this.QP.hasClass('ICN_quickpic_selected')) this.QP.removeClass('ICN_quickpic_selected');
                        var image = this.QP.getElement('img[id$=qpIcon]');
                        if (image) {
                            image.setProperties({
                                'title': CorbisUI.GlobalVars.SearchResults.text.addQuickpicAlt,
                                'alt': CorbisUI.GlobalVars.SearchResults.text.addQuickpicAlt
                            });
                        }
                        this.activeStates.QP = false;
                    }
                    break;
                case "SB":
                    if (this.SB.hasClass('ICN_subscription_selected')) this.SB.toggleClass('ICN_subscription_selected');
                    var image = this.SB.getElement('img[id$=sbIcon]');
                    if (image) {
                        image.setProperties({
                            'title': CorbisUI.GlobalVars.SearchResults.text.addSubscriptionAlt,
                            'alt': CorbisUI.GlobalVars.SearchResults.text.addSubscriptionAlt
                        });
                    }
                    this.activeStates.SB = false;
                    break;
                case "CT":
                    if (this.CTenabled) {
                        if (this.basketCase) {
                            if (this.CT.hasClass('ICN_cartBasket_selected')) this.CT.toggleClass('ICN_cartBasket_selected');
                        } else {
                            if (this.CT.hasClass('ICN_cart_selected')) this.CT.toggleClass('ICN_cart_selected');
                        }
                        var image = this.CT.getElement('img[id$=addToCartImage]');
                        if (image) {
                            image.setProperties({
                            'title': CorbisUI.GlobalVars.SearchResults.text.addToCartAlt,
                            'alt': CorbisUI.GlobalVars.SearchResults.text.addToCartAlt
                            });
                        }
                        this.activeStates.CT = false;
                    }
                    break;
            }
            // update productblock glow
            this.unhighlightBlock();
        },

        highlightBlock: function() {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.highlightBlock');
            if (this.activeStates.LB
                || (this.QPenabled && this.activeStates.QP)
                || (this.SBenabled && this.activeStates.SB)
                || (this.CTenabled && this.activeStates.CT)) {
                //for check different layout
                if ($(document.body).getElement('div.thumbnailPlusDetails') != null) {
                    if ($(document.body).getElement('div.thumbnailPlusDetails').getStyle('background-position') == "0% 0%") {
                        //console.log(this.productBlock);
                        // this is lame - perfect example of something not quite designed right.
                        var product = (window.location.href.toLowerCase().contains('mylightboxes.aspx')) ? this.productBlock : this.productBlock.getParent();

                        if (!product.hasClass('ProductSelected')) product.toggleClass('ProductSelected');
                    }
                    else {
                        if (!this.productBlock.hasClass('ProductSelected')) this.productBlock.toggleClass('ProductSelected');
                    }
                }
                else {
                    if (!this.productBlock.hasClass('ProductSelected')) this.productBlock.toggleClass('ProductSelected');

                }

            }
        },

        unhighlightBlock: function() {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.unhighlightBlock');
            if (!this.activeStates.LB
                && !this.activeStates.QP
                && !this.activeStates.SB
                && !this.activeStates.CT) {
                if ($(document.body).getElement('div.thumbnailPlusDetails') != null) {
                    if ($(document.body).getElement('div.thumbnailPlusDetails').getStyle('background-position') == "0% 0%") {
                        // this is lame - perfect example of something not quite designed right.
                        var product = (window.location.href.toLowerCase().contains('mylightboxes.aspx')) ? this.productBlock : this.productBlock.getParent();
                        if (product.hasClass('ProductSelected')) product.toggleClass('ProductSelected');
                    }
                    else {
                        if (this.productBlock.hasClass('ProductSelected')) this.productBlock.toggleClass('ProductSelected');
                    }
                } else {
                    if (this.productBlock.hasClass('ProductSelected')) this.productBlock.toggleClass('ProductSelected');
                }

            }
        },

        refreshObject: function() {
            //console.log('CALLING: CorbisUI.SearchModels.ProductBlock.refreshObject');
            // the whole purpose of this method is
            // because update panel messes our scripts
            // up by redrawing the dom when we have 
            // JS object attached to certain dom elements
            var item = CorbisUI.DomCache.get('ProductResults').getElement('span[productuid=' + this.productUID + ']');
            if (item) {
                // reattach this to the current dom object
                this.initialize(item);
                // reattach tooltips - stupid update panel
                this.setupObject();
            }
            //(function(){registerTooltips(false);}).delay(200);
            return this;
        }


    }),
    /* model for subcription item */

    subscriptionBlock: new Class({

        Implements: [CorbisUI.SearchConstructors.pinkyBlockConstructor, Options, Events],

        constructorType: 'subscription',

        options: {},

        tempObject: {},

        initialize: function(mediaUID, corbisID, options, realProductUid) {
            //$extend(this,CorbisUI.Search.pinkyBlockConstructor);
            //console.log($type(mediaUID));
            // this first item is to detect if its supposed
            // to create a new block from the lazy loader
            if ($type(mediaUID) == 'object') {

                // //console.log(tempObject);
                this.tempObject = mediaUID;
                this.mediaUID = this.tempObject.MediaUid;
                this.corbisID = this.tempObject.CorbisId;

                this.createBlock(true, 'subcription'); // true, that it is new and not clone

                // else this creates a block when adding to subscription
                // from search results
            } else {
                if (options) this.setOptions(options);

                this.mediaUID = mediaUID;
                this.corbisID = corbisID;
                this.realProductUID = realProductUid;
                this.createBlock(false, 'subcription'); // false, because it is cloning instead of creating

                // setup block here
            }

            // add delete and cart events here
            if (CorbisUI.ProductCache.has(this.mediaUID)) CorbisUI.ProductCache.get(this.mediaUID).updateIcon('SB', 'selectIcon');

            //inject it into the lightbox pane
            CorbisUI.DomCache.get('subscriptionContainer', true).grab(this.block, this.injectWhere);
        },

        // events
        deleteButtonEvent: function() {
            CorbisUI.Handlers.Subscription.deleteItem(this.mediaUID);
            //Corbis.Web.UI.SearchOld.SearchScriptService.DeleteSubscriptionItem(this.mediaUID);
            if (CorbisUI.ProductCache.has(this.mediaUID)) CorbisUI.ProductCache.get(this.mediaUID).updateIcon('SB', 'deselectIcon');

            //decrement image count for lightbox
            var imageCountProperty = CorbisUI.DomCache.get('subscriptionContainer').getProperty('imageCount');
            var imageCount = parseInt(imageCountProperty);
            if (!isNaN(imageCount)) {
                imageCount -= 1;
            }
            else {
                //item already delete, so don't need to decrement.
                imageCount = CorbisUI.DomCache.get('subscriptionContainer').getElements('div.subscriptionBlock').length;
            }
            CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', imageCount.toString());
            document.body.getElement('.subscriptionCounts span.imageCount').set('text', imageCount.toString());
            this.block.destroy();
            if (CorbisUI.DomCache.get('subscriptionContainer').getElements('div.subscriptionBlock').length == 0 && document.body.getElement("div.subscriptionCounts").getElement('.remainingCount').get('text') == '0') {
                if (CorbisUI.DomCache.get('subscriptionContainer').getElement('.centerMe')) {
                    CorbisUI.DomCache.get('subscriptionContainer').getElement('.centerMe').setStyle('display', 'none');
                }
                if (CorbisUI.DomCache.get('subscriptionContainer').getElement('.remainingZerocenterMe')) {
                    CorbisUI.DomCache.get('subscriptionContainer').getElement('.remainingZerocenterMe').setStyle('display', 'block');
                }
            }
        }

    }),
    /* model for lightbox item */

    lightboxBlock: new Class({

        Implements: [CorbisUI.SearchConstructors.pinkyBlockConstructor, Options, Events],

        constructorType: 'lightbox',

        options: {},

        tempObject: {},

        subscriptionImage: false,

        initialize: function(mediaUID, corbisID, options, realProductUid) {
            //$extend(this,CorbisUI.Search.pinkyBlockConstructor);
            //console.log($type(mediaUID));
            // this first item is to detect if its supposed
            // to create a new block from the lazy loader
            //left side Panel
            if ($type(mediaUID) == 'object') {

                // //console.log(tempObject);
                this.tempObject = mediaUID;
                this.mediaUID = this.tempObject.MediaUid;
                this.corbisID = this.tempObject.CorbisId;
                this.subscriptionImage = this.tempObject.IsSubscription;

                this.createBlock(true, 'lightbox'); // true, that it is new and not clone


                // else this creates a block when adding to lightbox
                // from search results
            } else {
                if (options) this.setOptions(options);

                this.mediaUID = mediaUID;
                this.corbisID = corbisID;
                this.realProductUID = realProductUid;

                //console.log('MI: ' + this.mediaUID);

                //var subscription = $(document.body).getElement('span[productuid='+this.mediaUID+']').getProperty('subscription');

                //if (subscription == "true") this.subscriptionImage = true;

                this.subscriptionImage = CorbisUI.ProductCache.get(this.mediaUID).subscriptionImage;

                this.createBlock(false, 'lightbox'); // false, because it is cloning instead of creating

                // setup block here
            }
            if (this.isInCart()) this.block.addClass('inCart');
            //var a = isSubscriptioinEnabled;
            // we check for trident4 (IE6) so we don't display express checkout icon.
            if (isQuickCheckoutEnabled && !this.isOutline && !this.isRfcd && !Browser.Engine.trident4) {
                var expressIconType = CorbisUI.GlobalVars.SearchResults.isECommerceEnabled ? (CorbisUI.GlobalVars.SearchResults.isBasket ? 'lightboxExpressBasket' : 'lightboxExpressCheckout') : '';
                var quickCheckoutAnchor = new Element('a')
                    .setProperties({
                        alt: CorbisUI.GlobalVars.SearchResults.text.expressCheckoutAlt,
                        title: CorbisUI.GlobalVars.SearchResults.text.expressCheckoutAlt
                    })
                    .addClass(CorbisUI.GlobalVars.SearchResults.isBasket ? 'lightboxExpressBasket' : 'lightboxExpressCheckout')
                    .addEvent('click', this.expressCheckoutButtonEvent.bindWithEvent(this))
                    .inject(this.licenseBlock);

                this.quickCheckoutButton = quickCheckoutAnchor;
            }
            // need to attach event to this
            var cartIconType = CorbisUI.GlobalVars.SearchResults.isECommerceEnabled ? (CorbisUI.GlobalVars.SearchResults.isBasket ? 'lightboxBasket' : 'lightboxCart') : '';
            var cartAnchor = new Element('a')
                .addClass(cartIconType)
                .addEvent('click', this.cartButtonEvent.bindWithEvent(this))
                .inject(this.licenseBlock);

            var altText;
            if (this.isInCart()) {
                altText = CorbisUI.GlobalVars.SearchResults.text.removeCartAlt;
                cartAnchor.addClass('inCart');
            }
            else {
                altText = CorbisUI.GlobalVars.SearchResults.text.addToCartAlt;
            }
            cartAnchor.setProperties
            ({
                alt: altText,
                title: altText
            });

            //var cartIcon = new Element('div').addClass("ICN_cart").inject(cartAnchor);
            this.cartButton = cartAnchor;

            /* for requirment 21981
            if (CorbisUI.GlobalVars.Subscriptions.mode == "Normal" && this.subscriptionImage) {
            this.licenseBlock.getElements('a').each(function(el) {
            el.destroy();
            });
            }*/

            // add delete and cart events here
            if (CorbisUI.ProductCache.has(this.mediaUID)) CorbisUI.ProductCache.get(this.mediaUID).updateIcon('LB', 'selectIcon');

            //inject it into the lightbox pane
            CorbisUI.DomCache.get('LBXContainer', true).grab(this.block, this.injectWhere);
        },

        // events
        deleteButtonEvent: function() {
            //var lightboxId = CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList');
            var lightboxId = CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList').getSelected()[0].value;
            Corbis.Web.UI.SearchOld.SearchScriptService.DeleteProductFromLightbox(lightboxId, this.realProductUID);
            if (CorbisUI.ProductCache.has(this.mediaUID)) CorbisUI.ProductCache.get(this.mediaUID).updateIcon('LB', 'deselectIcon');

            //decrement image count for lightbox
            var imageCountProperty = CorbisUI.DomCache.get('LBXContainer').getProperty('imageCount');
            var imageCount = parseInt(imageCountProperty);
            if (!isNaN(imageCount)) {
                imageCount -= 1;
            }
            else {
                //item already delete, so don't need to decrement.
                imageCount = CorbisUI.DomCache.get('LBXContainer').getElements('div.lightboxBlock').length;
            }
            CorbisUI.DomCache.get('LBXContainer').setProperty('imageCount', imageCount.toString());

            //show empty lighbox message if no images
            if (imageCount == 0 && CorbisUI.DomCache.get('LBXContainer').getElement('.centerMe') != null) {
                CorbisUI.DomCache.get('LBXContainer').getElement('.centerMe').setStyle('display', 'block');
            }

            this.block.destroy();
            //$lambda(false);
            // now delete this item

        },

        cartButtonEvent: function() {
            if (!this.isInCart()) {
                Corbis.Web.UI.SearchOld.SearchScriptService.AddProductToCart(this.mediaUID, this.realProductUID);
                //adjust cart counter here
                var cartCounter = CorbisUI.DomCache.get('cartCount');
                if (cartCounter) {
                    var count = cartCounter.getProperty('text');
                    count++;
                    cartCounter.setProperty('text', count);
                    fixIECheckoutWidgetWidth();
                }
                //highligh the control to show it is in the cart
                this.highlightIcon('cart');
                //add mediaUID to the list
                //cartMediaUidList.include(this.mediaUID);
                CorbisUI.cartMediaUidList.set(this.mediaUID, true);
                if (this.isInCart()) {
                    var anchorTagObj = this.block.getElement('a[class=lightboxCart]') ? this.block.getElement('a[class=lightboxCart]') : this.block.getElement('a[class=lightboxBasket]');
                    if (anchorTagObj) {
                        anchorTagObj.setProperties({
                            'title': CorbisUI.GlobalVars.SearchResults.text.removeCartAlt,
                            'alt': CorbisUI.GlobalVars.SearchResults.text.removeCartAlt
                        });                       
                     $(anchorTagObj).addClass('inCart');
                    }
                }
                if (CorbisUI.ProductCache.has(this.mediaUID)) {
                    CorbisUI.ProductCache.get(this.mediaUID).updateIcon('CT', 'selectIcon');
                }
            }
        },

        expressCheckoutButtonEvent: function() {
            this.lightboxId = $(document.body).getElement('select[name$=lightboxList]').getSelected()[0].value;
            CorbisUI.ExpressCheckout.Open(this.corbisID, this.realProductUID, this.lightboxId);
            //return false;
        }

    }),

    /* model for quickpic item */
    quickPicBlock: new Class({

        Implements: [CorbisUI.SearchConstructors.pinkyBlockConstructor, Options, Events],

        constructorType: 'quickPic',

        options: {},

        initialize: function(mediaUID, corbisID, options) {
            //$extend(this,CorbisUI.Search.pinkyBlockConstructor);

            if (options) this.setOptions(options);

            if ($type(mediaUID) == 'object') {
                this.tempObject = mediaUID;
                this.mediaUID = this.tempObject.MediaUid;
                this.corbisID = this.tempObject.CorbisId;
                this.createBlock(true, 'quickpic'); // true, that it is new and not clone

                // else this creates a block when adding to lightbox
                // from search results
            } else {
                if (options) this.setOptions(options);

                this.mediaUID = mediaUID;
                this.corbisID = corbisID;

                this.createBlock(false, 'quickpic'); // false, because it is cloning instead of creating

                // setup block here
            }

            // add delete and cart events here
            if (CorbisUI.ProductCache.has(this.mediaUID)) CorbisUI.ProductCache.get(this.mediaUID).updateIcon('QP', 'selectIcon');

            var downloadAll = $('SBBX_quickpic').getElement('div[id$=downloadAll]');
            CorbisUI.DomCache.addObject('quickPicDownloadAll', downloadAll);
            // setup block here

            //inject it into the lightbox pane
            var target = CorbisUI.DomCache.get('quickPicsContainer').getFirst();
            //.getFirst()
            //.getElement('.centerMe');

            this.block.inject(target, this.injectWhere);
        },

        // events
        deleteButtonEvent: function() {
            CorbisUI.Handlers.Quickpic.deleteItem(this.corbisID);
        }

    })

};

//End: /Scripts/CorbisUI.SearchModels.js
//Begin: /Picplan/Subscription.js

/***************************
NAMESPACES
****************************/
if (typeof (CorbisUI) == 'undefined') {
    CorbisUI = {};
}
CorbisUI.Subscription = {};

CorbisUI.Subscription = {
    result: null,

    DownloadSubscriptionImages: function(remainingCount, isContinue, isPurchase) {
        var dropDown = $('SBBX_subscriptions').getElement('select.subscriptionFileSize');
        var FileSize = dropDown.options[dropDown.selectedIndex].value;
        if (isContinue == true) {
            Corbis.Web.UI.Subscription.SubscriptionScriptService.DownloadSubscriptionImages($('SBBX_subscriptions').getElement('div.txtProjectName input').value, FileSize, remainingCount, isContinue, isPurchase, CorbisUI.Subscription.continueDownloadSuccess, CorbisUI.Subscription.DownloadImageFailed);
        }
        else {
            Corbis.Web.UI.Subscription.SubscriptionScriptService.DownloadSubscriptionImages($('SBBX_subscriptions').getElement('div.txtProjectName input').value, FileSize, remainingCount, isContinue, isPurchase, CorbisUI.Subscription.DownloadExceptionCheck, CorbisUI.Subscription.DownloadImageFailed);
            CorbisUI.Subscription.OpenProgressModal();
        }
    },
    DownloadExceptionCheck: function(result) {
        HideModal('downloadProgress');
        if (result.Status == 1) {
            CorbisUI.Subscription.result = result;
            CorbisUI.Subscription.emptySubscriptionBuddy(document.body);
            window.location.href.toLowerCase().contains('mylightboxes.aspx') ? setGlassButtonDisabled($(CorbisUI.GlobalVars.Lightbox.subscriptionDownloadAllBtn), true) : setGlassButtonDisabled(CorbisUI.GlobalVars.SearchResults.subscriptionDownloadAllBtn, true);
            OpenNewIModal(CorbisUI.GlobalVars.SearchResults.urls.downloadSubscription, 640, 540, 'Subscription');
        } else {
            CorbisUI.Subscription.result = result;
            OpenNewIModal(CorbisUI.GlobalVars.SearchResults.urls.downloadSubscriptionException + "?DownloadResult=" + result.Status, 350, 50, 'SubscriptionExceptions');
            if (result.Status == 8) {
                document.body.getElement("div.subscriptionCounts").getElement('.remainingCount').set('text', '0');
            }
        }
    },
    continueDownloadSuccess: function(result) {
        if (result.Status == 1) {
            CorbisUI.Subscription.result = result;
            OpenNewIModal(CorbisUI.GlobalVars.SearchResults.urls.downloadSubscription, 640, 540, 'Subscription');
        } else {
            CorbisUI.Subscription.result = result;
            OpenNewIModal(CorbisUI.GlobalVars.SearchResults.urls.downloadSubscriptionException + "?DownloadResult=" + result.Status, 350, 50, 'SubscriptionExceptions');
        }
    },
    emptySubscriptionBuddy: function(iBody) {
        iBody.getElement("div.subscriptionCounts").getElement('.imageCount').set('text', '0');
        if (iBody.getElement("div.subscriptionCounts").getElement('.remainingCount').get('text') == '0' && iBody.getElement("div.subscriptionCounts").getElement('.imageCount').get('text') == '0') {
            if (iBody.getElement("div.subscriptionContainer").getElement('.centerMe')) {
                iBody.getElement("div.subscriptionContainer").getElement('.centerMe').setStyle('display', 'none');
            }
            if (CorbisUI.DomCache.get('subscriptionContainer').getElement('.remainingZerocenterMe')) {
                iBody.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe').setStyle('display', 'block');
            }

        }
    },
    setDownloadInfo: function(result) {
        var downloadDiv = $('download');
        var linksContainer = downloadDiv.getElement('div.downloadLinks');
        linksContainer.empty();

        if (!result) {
            CorbisUI.Subscription.DownloadImageFailed(null);
            return;
        }

        $('orderNumber').set('text', result.OrderNumber);
        $('projectName').set('text', result.ProjectName);
        $('emailedTo').set('text', result.ConfirmationEmail);

        //  if (!$('selectImage').hasClass('hdn')) $('selectImage').addClass('hdn');
        downloadDiv.removeClass('hdn');
        if (parent.location.pathname.toLowerCase().endsWith('mylightboxes.aspx')) {
            if (result && result.PackagedCorbisIds) {
                for (var i = 0; i < result.PackagedCorbisIds.length; i++) {
                    var corbisId = result.PackagedCorbisIds[i];
                    var mediaId = parent.CorbisUI.ProductCache.get(corbisId);
                    var product = parent.CorbisUI.ProductCache.get(mediaId);

                    if (product) product.updateIcon('SB', 'deselectIcon');
                }
            }
            CorbisUI.Subscription.Refresh();
        }
        else {

            if (result && result.PackagedCorbisIds) {
                for (var i = 0; i < result.PackagedCorbisIds.length; i++) {
                    var corbisId = result.PackagedCorbisIds[i];
                    var mediaId = parent.CorbisUI.ProductCache.get(corbisId);
                    var product = parent.CorbisUI.ProductCache.get(mediaId);

                    if (product) product.updateIcon('SB', 'deselectIcon');
                }
            }
            CorbisUI.Subscription.Refresh();
        }


        var zipPattern = new RegExp(/[.]zip/i);
        var showHelpText = false;
        result.DownloadPackages.each(
			    function(el) {
			        showHelpText = showHelpText || zipPattern.test(el.Key);
			        var newLink = new Element('a', {
			            'href': el.Value,
			            'html': el.Key
			        });
			        newLink.inject(linksContainer, 'bottom');
			        var win;
			        if (Browser.Engine.webkit) {
			            //Safari doesnt close the download window after the download process is initiated.
			            //Bug: 17179.
			            //TODO: Need to find a better solution or check in the next version of Safari. 
			            //Right now the window will close itself after 5 seconds.
			            win = window.open(el.Value, '_blank', 'height=1,width=1');
			            win.setTimeout("self.close();", 5000);
			        } else {
			            win = window.open(el.Value, '_blank', 'height=100,width=100');
			        }
			    }
		    )

        var dotDiv = downloadDiv.getElement('div.dots');
        var helpTextDiv = downloadDiv.getElement('div.helpText');
        if (showHelpText) {
            dotDiv.removeClass('hdn');
            helpTextDiv.removeClass('hdn');
        }
        else {
            if (!dotDiv.hasClass('hdn')) dotDiv.addClass('hdn');
            if (!helpTextDiv.hasClass('hdn')) helpTextDiv.addClass('hdn');
        }
        if (window.parent.MVCTilePage) {
            window.parent.picplanDownloadCallbackOverride();
        }
    },
    DownloadImageFailed: function(result) {
        if (!executer.get_aborted()) {
            OpenModal('subscriptiondownloaderrormodal');
            window.frames[0].$('modalOverlay').setStyle('opacity', 0.7);
        }
    },
    Refresh: function() {
        parent.CorbisUI.Search.Handler.refreshsubScriptioinBuddy();
    },
    updateRemaining: function(result) {
        parent.document.body.getElement('span.remainingCount').set('text', result.toString());
    },
    methodFailed: function(results, methodName) {
        alert(results.get_message());
    },
    OpenProgressModal: function(url) {
        var options = {
            cornerRadius: 0,
            headerHeight: 0,
            footerHeight: 0,
            contentBgColor: 'transparent',
            useCanvas: false,
            createFromHTML: false
        };
        new CorbisUI.Popup('downloadProgress', options);
        window.frames[0].$('modalOverlay').setStyle('opacity', 0.7);
        window.frames[0].$(parent.document).getElement('#SubscriptionWindow_overlay').setStyles({
            'background-image': 'url(../Images/SubscriptionProgressBackground.gif)',
            'background-repeat': 'no-repeat'
        });
    },

    HideProgressModal: function() {
        $(parent.document).getElement('#SubscriptionWindow_overlay').setStyle('background-image', 'none');
        HideModal('downloadProgress');
    },

    CancelDownload: function() {
        if (executer && executer.get_started()) {
            executer.abort();
        }

        this.HideProgressModal();
    },

    SetFileSize: function(size) {
        $('selectImage').getElements('select.fileSize').each(function(el) {
            el.selectedIndex = (size == 'smallest' ? el.options.length - 1 : 0);
        }
		);
    },
    /* reuse the same code as order page */
    OpenProgressModal: function() {
        keyWatch.start();
        var options = {
            cornerRadius: 0,
            headerHeight: 0,
            footerHeight: 0,
            contentBgColor: 'transparent',
            useCanvas: false
        };
        new CorbisUI.Popup('downloadProgress', options);
        $('modalOverlay').setStyle('opacity', 0.8);
    },
    OpenExpireModal: function() {
        new CorbisUI.Popup('picplanExpireModal', {
            showModalBackground: false,
            closeOnLoseFocus: true,
            positionVert: 0,
            positionHoriz: 0
        });
        ResizeModal('picplanExpireModal');
        var expireModal = document.body.getElement('img.picPlanExpired');
        $('picplanExpireModalWindow').setStyles({
            top: expireModal.offsetHeight + 40,
            left: expireModal.offsetWidth + 90
        });

    }
}

//End: /Picplan/Subscription.js
//Begin: /SearchOld/Search.js

/* 
                    .+~                :xx++::
                   :`. -          .!!X!~"?!`~!~!. :-:.
                  <             .!!!H":.~ ::+!~~!!!~ `%X.
                  '             ~~!M!!>!!X?!!!!!!!!!!...!~.
                              <!:!MM!~:XM!!!!!!.:!..~ !.  `<
                  <: `   :~ .:<~!!M!XXHM!!!X!XXHtMMHHHX!  ~ ~
                ~~~~<' ~!!!:!!!!!XM!!M!!!XHMMMRMSXXX!!!!!!:  <`
                  `<  <::!!!!!X!X?M!!M!!XMMMMXXMMMM??!!!!!?!:~<
               : '~~~<!!!XMMH!!XMXMXHHXXXXM!!!!MMMMSXXXX!!!!!!!~
            :    ::`~!!!MMMMXXXtMMMMMMMMMMMHX!!!!!!HMMMMMX!!!!!: ~
               '~:~!!!!!MMMMMMMMMMMMMMMMMMMMMMXXX!!!M??MMMM!!X!!i:
               <~<!!!!!XMMMMMMMMMMMM8M8MMMMM8MMMMMXX!!!!!!!!X!?t?!:
               ~:~~!!!!?MMMMMM@M@RMRRR$@@MMRMRMMMMMMXSX!!!XMMMX<?X!
             :XX <!!XHMMMM88MM88BR$M$$$$8@8RN88MMMMMMMMHXX?MMMMMX!!!
           .:X! <XMSM8M@@$$$$$$$$$$$$$$$$$$$B8R$8MMMMMMMMMMMMMMMMX!X
          :!?! !?XMMMMM8$$$$8$$$$$$$$$$$$$$BBR$$MMM@MMMMMMMMMMMMMM!!X
        ~<!!~ <!!XMMMB$$$$$$$$$$$$$$$$$$$$$$$$MMR$8MR$MMMMMMMMMMMMM!?!:
        :~~~ !:X!XMM8$$$$$$$$$$$$$$$$$$$$$$$RR$$MMMMR8NMMMMMMMMMMMMM<!`-
    ~:<!:~`~':!:HMM8N$$$$$$$$$$$$$$$$$$$$$$$$$8MRMM8R$MRMMMMMMMMRMMMX!
  !X!``~~   :~XM?SMM$B$$$$$$$$$$$$$$$$$$$$$$BR$$MMM$@R$M$MMMMMM$MMMMX?L
 X~.      : `!!!MM#$RR$$$$$$$$$$$$$$$$$R$$$$$R$M$MMRRRM8MMMMMMM$$MMMM!?:
 ! ~ <~  !! !!~`` :!!MR$$$$$$$$$$RMM!?!??RR?#R8$M$MMMRM$RMMMM8MM$MMM!M!:>
: ' >!~ '!!  !   .!XMM8$$$$$@$$$R888HMM!!XXHWX$8$RM$MR5$8MMMMR$$@MMM!!!< ~
!  ' !  ~!! :!:XXHXMMMR$$$$$$$$$$$$$$$$8$$$$8$$$MMR$M$$$MMMMMM$$$MMM!!!!
 ~<!!!  !!! !!HMMMMMMMM$$$$$$$$$$$$$$$$$$$$$$$$$$MMM$M$$MM8MMMR$$MMXX!!!!/:`
  ~!!!  !!! !XMMMMMMMMMMR$$$$$$$$$$$$R$RRR$$$$$$$MMMM$RM$MM8MM$$$M8MMMX!!!!:
  !~ ~  !!~ XMMM%!!!XMMX?M$$$$$$$$B$MMSXXXH?MR$$8MMMM$$@$8$M$B$$$$B$MMMX!!!!
  ~!    !! 'XMM?~~!!!MMMX!M$$$$$$MRMMM?!%MMMH!R$MMMMMM$$$MM$8$$$$$$MR@M!!!!!
  <>    !!  !Mf x@#"~!t?M~!$$$$$RMMM?Xb@!~`??MS$M@MMM@RMRMMM$$$$$$RMMMMM!!!!
  !    '!~ <!!:!?M   !@!M<XM$$R5M$8MMM$! -XXXMMRMBMMM$RMMM@$R$BR$MMMMX??!X!!
  !    '!  !!X!!!?::xH!HM:MM$RM8M$RHMMMX...XMMMMM$RMMRRMMMMMMM8MMMMMMMMX!!X!
  !     ~  !!?:::!!!MXMR~!MMMRMM8MMMMMS!!M?XXMMMMM$$M$M$RMMMM8$RMMMMMMMM%X!!
  ~     ~  !~~X!!XHMMM?~ XM$MMMMRMMMMMM@MMMMMMMMMM$8@MMMMMMMMRMMMMM?!MMM%HX!
           !!!!XSMMXXMM .MMMMMMMM$$$BB8MMM@MMMMMMMR$RMMMMMMMMMMMMMMMXX!?H!XX
           XHXMMMMMMMM!.XMMMMMMMMMR$$$8M$$$$$M@88MMMMMMMMMMMMMMM!XMMMXX!!!XM
      ~   <!MMMMMMMMRM:XMMMMMMMMMM8R$$$$$$$$$$$$$$$NMMMMMMMM?!MM!M8MXX!!/t!M
      '   ~HMMMMMMMMM~!MM8@8MMM!MM$$8$$$$$$$$$$$$$$8MMMMMMM!!XMMMM$8MR!MX!MM
          'MMMMMMMMMM'MM$$$$$MMXMXM$$$$$$$$$$$$$$$$RMMMMMMM!!MMM$$$$MMMMM<!M
          'MMMMMMMMM!'MM$$$$$RMMMMMM$$$$$$$$$$$$$$$MMM!MMMX!!MM$$$$$M$$M$M!M
           !MMMMMM$M! !MR$$$RMM8$8MXM8$$$$$$$$$$$$NMMM!MMM!!!?MRR$$RXM$$MR!M
           !M?XMM$$M.< !MMMMMMSUSRMXM$8R$$$$$$$$$$#$MM!MMM!X!t8$M$MMMHMRMMX$
    ,-,   '!!!MM$RMSMX:.?!XMHRR$RM88$$$8M$$$$$R$$$$8MM!MMXMH!M$$RMMMMRNMMX!$
   -'`    '!!!MMMMMMMMMM8$RMM8MBMRRMR8RMMM$$$$8$8$$$MMXMMMMM!MR$MM!M?MMMMMM$
          'XX!MMMMMMM@RMM$MM@$$BM$$$M8MMMMR$$$$@$$$$MM!MMMMXX$MRM!XH!!??XMMM
          `!!!M?MHMMM$RMMMR@$$$$MR@MMMM8MMMM$$$$$$$WMM!MMMM!M$RMM!!.MM!%M?~!
           !!!!!!MMMMBMM$$RRMMMR8MMMMMRMMMMM8$$$$$$$MM?MMMM!f#RM~    `~!!!~!
           ~!!HX!!~!?MM?MMM??MM?MMMMMMMMMRMMMM$$$$$MMM!MMMM!!
           '!!!MX!:`~~`~~!~~!!!!XM!!!?!?MMMM8$$$$$MMMMXMMM!!
            !!~M@MX.. <!!X!!!!XHMHX!!``!XMMMB$MM$$B$M!MMM!!
            !!!?MRMM!:!XHMHMMMMMMMM!  X!SMMX$$MM$$$RMXMMM~
             !M!MMMM>!XMMMMMMMMXMM!!:!MM$MMMBRM$$$$8MMMM~
             `?H!M$R>'MMMM?MMM!MM6!X!XM$$$MM$MM$$$$MX$f
              `MXM$8X MMMMMMM!!MM!!!!XM$$$MM$MM$$$RX@"
               ~M?$MM !MMMMXM!!MM!!!XMMM$$$8$XM$$RM!`
                !XMMM !MMMMXX!XM!!!HMMMM$$$$RH$$M!~
                'M?MM `?MMXMM!XM!XMMMMM$$$$$RM$$#
                 `>MMk ~MMHM!XM!XMMM$$$$$$BRM$M"
                  ~`?M. !M?MXM!X$$@M$$$$$$RMM#
                    `!M  !!MM!X8$$$RM$$$$MM#`
                      !% `~~~X8$$$$8M$$RR#`
                       !!x:xH$$$$$$$R$R*`
                        ~!?MMMMRRRM@M#`       -Search is delicious-
                         `~???MMM?M"`
                             ``~~
*/

//Moved code from here to AddToLightbox.ascx

// Due to the similarity of function for search load progress, attach the progress handling function here -- MIKE

/***************************
SCRIPT VARIABLES
****************************/
var timer, timer2, thumbTips, noLicense, noCat, noColor, noPhoto;
var _clarifyCheckCount = 0;
var stopSearch = false;

/****************************
NAMESPACES
****************************/
if (typeof(CorbisUI) == 'undefined') {
    CorbisUI = {};
}

if (typeof (CorbisUI.Search) == 'undefined') {
    CorbisUI.Search = {};
    CorbisUI.ProductTooltip = null;
}

if (typeof (CorbisUI.Handlers) == 'undefined') {
    CorbisUI.Handlers = {};
}

if (typeof (CorbisUI.ProductCache) == 'undefined') {
    CorbisUI.ProductCache = new CorbisUI.CachingClass();
}

if (typeof (CorbisUI.Search.AutoCompleteDisplayOptions
) == 'undefined') {
    CorbisUI.Search.AutoCompleteDisplayOptions = {};
}


/////////////////////////////////////
// MAIN SEARCH NAMESPACE OBJECT
/////////////////////////////////////

CorbisUI.Search = {

    MoveQuickPick: function(ctl, ctl2, corbisId, Url128, licenseModel, aspectRatio, title, toQuickPick) {
        // see if quickpic tab is active, if not then "click" it
        // this interacts with objects in SearchBuddy.js
        if (CorbisUI.SearchBuddy.init.activeTab != "quickpic") {
            var qp = CorbisUI.SearchBuddy.init.tabs.get("quickpic");
            qp.el.fireEvent('click');
        }

        if (toQuickPick) {

            Corbis.Web.UI.SearchOld.SearchScriptService.AddItemToQuickPick(corbisId, Url128, licenseModel, aspectRatio, title, updateQuickPicView, methodFailed);
            var item = $(ctl);
            item.getParent().addClass('hdn');
            var hideQP = item.getParent('ul').getElement('.QP_off');
            if (hideQP) {
                hideQP.removeClass('hdn');
            }
        }
        else {
            Corbis.Web.UI.SearchOld.SearchScriptService.RemoveItemFromQuickPick(corbisId, updateQuickPicView, methodFailed)
            var item = $(ctl);
            item.getParent().addClass('hdn');
            var ulItem = item.getParent('ul');
            if (ulItem) {
                var showQP = ulItem.getElement('.QP_on');
                if (showQP) {
                    showQP.removeClass('hdn');
                }
            }
        }

    },

    WindowScrollFX: null,

    SetPageFocus: function() {
        if (this.WindowScrollFX == null) {
            this.WindowScrollFX = new Fx.Scroll($(window), {
                offset: {
                    'x': 0,
                    'y': 0
                }
            });
        }
        if ($('ProductResults') != null) this.WindowScrollFX.toTop();
    }
};

CorbisUI.QueueManager.addQueue('SearchMacros', {
    canRerun: true,
    delay: true
}).addItem('pageScrollToTop', function() {
    CorbisUI.Search.SetPageFocus();
});



/////////////////////////////////////
// HANDLER FUNCTIONS
/////////////////////////////////////


CorbisUI.Search.Handler = {

    fetchProductObject: function(id, idType) {
        switch (idType) {
            case "productuid":
                return CorbisUI.ProductCache.get(id);
                break;
            case "corbisid":
                var productuid = CorbisUI.ProductCache.get(id);
                return CorbisUI.ProductCache.get(productuid);
                break;
        }
    },
    selectQuickpicIcon: function(id, idType) {
        var product = this.fetchProductObject(id, idType);
        (function() {
            product.refreshObject()
                .updateIcon('QP', 'selectIcon');
        }).delay(200);
    },

    deselectQuickpicIcon: function(id, idType) {
        var product = this.fetchProductObject(id, idType);
        (function() {
            product.refreshObject()
                .updateIcon('QP', 'deselectIcon');
        }).delay(200);
    },

    syncLightboxToImages: function() {
        CorbisUI.Handlers.Lightbox.syncLightboxToImages();
        //        //deselect all selected images
        //        CorbisUI.DomCache.get('ProductResults').getElements('span.ProductBlock').each(function(el) {
        //            //var productBlock = el.retrieve('objectReference');
        //            var productid = el.getProperty('productuid');

        //            var productBlock = CorbisUI.ProductCache.get(productid);
        //            //productBlock.setupObject();
        //            //if (productBlock.activeStates.LB) {
        //            if (productBlock.checkLightboxStatus()) {
        //                productBlock.updateIcon('LB', 'deselectIcon');
        //            }
        //        });

        //        //Update images that's in current lightbox
        //        CorbisUI.DomCache.get('SBBX_lightboxes').getElements('div.lightboxBlock').each(function(el) {
        //            var lightboxImage = CorbisUI.ProductCache.get(el.getProperty('mediaUid'));
        //            if (lightboxImage != null) lightboxImage.refreshObject().updateIcon('LB', 'selectIcon');
        //        });
    },

    addProductToCart: function(corbisId) {
        if (CorbisUI.Auth.GetSignInLevel() < 1) {
            CorbisUI.Auth.Check(1, CorbisUI.Auth.ActionTypes.Execute, "CorbisUI.Search.Handler.doAddProductToCart('" + corbisId + "')");
        } else {
            CorbisUI.Search.Handler.doAddProductToCart(corbisId);
        }
    },

    doAddProductToCart: function(corbisId, reloadPage) {
        var mediaId = CorbisUI.ProductCache.get(corbisId);
        var product = CorbisUI.ProductCache.get(mediaId);
        if (product) product.refreshObject().setRefreshPage(reloadPage).addProductToCart();
    },

    refreshCartItem: function(corbisId, cartItemCount) {
        var mediaId = CorbisUI.ProductCache.get(corbisId);
        CorbisUI.Handlers.Cart.refreshItemAdded(mediaId, corbisId, cartItemCount);
    },
    refreshsubScriptioinBuddy: function() {
        CorbisUI.Handlers.Subscription.getSubscriptionItems(); //call getSubscription from database
        var subscriptionTab = CorbisUI.DomCache.get('SearchBuddy').getElement('li.SBT_subscriptions');
        //subscriptionTab.fireEvent('click'); //MooTool event
        Corbis.Web.UI.SearchOld.SearchScriptService.GetRemainingDownloadCount(CorbisUI.Search.Handler.updateRemaining, CorbisUI.Handlers.Subscription.methodFailed);
    },
    updateRemaining: function(result) {
        document.body.getElement('span.remainingCount').set('text', result.toString());
        if (result == 0) {
            CorbisUI.DomCache.get('subscriptionContainer').getElements('.subscriptionBlock').each(function(el) { el.destroy(); });
        }
        var count = CorbisUI.DomCache.get('subscriptionContainer').getElements('div.subscriptionBlock').length;
        if (count > 0) {
            CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', count);
            document.body.getElement('span.imageCount').set('text', count);

        } else {
            if (count == 0 && result == 0) {
                CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', '0');
                document.body.getElement('span.imageCount').set('text', '0');
                if (document.body.getElement("div.subscriptionContainer").getElement('.centerMe') != null) {
                    var msg = CorbisUI.GlobalVars.SearchResults.text.remainingZeoSubscriptionMessage.replace('{0}', CorbisUI.GlobalVars.SearchResults.text.additionalPrice);
                    document.body.getElement("div.subscriptionContainer").getElement('.centerMe').set('html', msg);
                    document.body.getElement("div.subscriptionContainer").getElement('.centerMe').setStyle('display', 'block');
                }
                else if (document.body.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe') != null) {
                    document.body.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe').setStyle('display', 'block');
                }
            }

        }

    },
    refreshQuickPicBuddy: function() {
        var quickpicField = CorbisUI.DomCache.get('SBBX_quickpic').getElement('input[id$=quickpicField]');
        quickpicField.onclick(); //AJAX control
        var quickpicTab = CorbisUI.DomCache.get('SearchBuddy').getElement('li.SBT_quickpic');
        quickpicTab.fireEvent('click'); //MooTool event
    }

};


/////////////////////////////////////
// NEW HANDLER FUNCTIONS
/////////////////////////////////////

CorbisUI.Handlers.Lightbox = {
    delayedLoadItem: false,
    currentLightboxItems: null,
    corbisIdToAdd: null,
    afterSignIn_cookieEvent: function(vars) {
        //1.get lightbox id first
        var lightboxId = CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList').getSelected()[0].value;
        //2.do the ajax call
        Corbis.Web.UI.SearchOld.SearchScriptService.AddSearchItemToLightbox(vars.MID, lightboxId,
                    function() { CorbisUI.SearchBuddy.activateTab("lightboxes") }, CorbisUI.Handlers.Lightbox.methodFailed);
    },
    afterSignIn: function(CorbisId) {

        var mediaId = CorbisUI.ProductCache.get(CorbisId);

        // setup cookie event
        CorbisUI.CookieEvents.addCookieEvent(function() {
            CorbisUI.Handlers.Lightbox.afterSignIn_cookieEvent(this.vars);
        }, { CID: CorbisId, MID: mediaId });

        window.location.reload();

    },
    addTo: function(CorbisId) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.addTo');
        if (CorbisUI.Auth.GetSignInLevel() < 1) {
            CorbisUI.Auth.Check(1, CorbisUI.Auth.ActionTypes.Execute, "CorbisUI.Handlers.Lightbox.afterSignIn('" + CorbisId + "'); ");
        }
        else {
            CorbisUI.Handlers.Lightbox.addProductToLightbox(CorbisId);
        }
    },
    addProductToLightbox: function(CorbisId, reloadPage) {
        LogOmnitureEvent("event12");
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.addProductToLightbox');
        var mediaId = CorbisUI.ProductCache.get(CorbisId);
        var product = CorbisUI.ProductCache.get(mediaId);
        product.refreshObject().setupObject();

        if (reloadPage) product.refreshPage = reloadPage;

        // if items not already in lightbox
        if (!product.activeStates.LB) {

            if (CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList').getSelected()[0]) {
                //1.get lightbox id first
                var lightboxId = CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList').getSelected()[0].value;
                //2.do the ajax call

                // check to see if ligthbox data has been loaded for the first time after a page load
                // see BUG 20288
                if (!CorbisUI.SearchBuddy.init.tabs.get('lightboxes').dataLoaded && !window.location.href.contains('imagegroups')) {

                    // create delayed item object to be loaded after lightbox items get loaded
                    CorbisUI.Handlers.Lightbox.delayedLoadItem = {
                        CID: product.corbisID,
                        MID: mediaId,
                        LBID: lightboxId,
                        HANDLER: CorbisUI.Handlers.Lightbox.addToResponseNew,
                        METHODFAILED: CorbisUI.Handlers.Lightbox.methodFailed
                    }

                } else {
                    // if lightbox items have been loaded already after page load, just call the service.
                    Corbis.Web.UI.SearchOld.SearchScriptService.AddSearchItemToLightboxNew(product.corbisID, mediaId, lightboxId, CorbisUI.Handlers.Lightbox.addToResponseNew, CorbisUI.Handlers.Lightbox.methodFailed);
                }


            }
            else {
                CorbisUI.Handlers.Lightbox.corbisIdToAdd = CorbisId;
                openCreateLightbox();
            }

            CorbisUI.SearchBuddy.init.tabs.get('lightboxes').el.fireEvent('click');
        }
    },
    reloadLightbox: function(lightboxId, lightboxName) {
        var lightboxList;
        var isMediasetSearch = false;
        //TODO: mediasetsearch buddy has lightbox in SBBX_filters, need to consolidate at some stage.
        if (CorbisUI.DomCache.get('SBBX_lightboxes')) {
            lightboxList = CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList');
        }
        else if (CorbisUI.DomCache.get('SBBX_filters')) {
            lightboxList = CorbisUI.DomCache.get('SBBX_filters').getElement('select.lightboxList');
            isMediasetSearch = true;
        }

        if (lightboxList) {
            if (lightboxName) {
                var option = new Option(lightboxName, lightboxId);
                try {
                    lightboxList.add(option, null);
                }
                catch (Error) {
                    lightboxList.add(option);
                }
            }

            var curLightboxId = lightboxList.getSelected()[0].value;
            if (curLightboxId != lightboxId) {
                var curLightbox = lightboxList.getElement('option[value=' + lightboxId + ']');
                if (curLightbox) curLightbox.selected = true;
            }

            if (isMediasetSearch) {
                $(CorbisUI.GlobalVars.SearchResults.refreshLightboxControl).onclick();
            }
            else {
                if (CorbisUI.SearchBuddy.init.tabs.get('lightboxes').dataLoaded ||
                    CorbisUI.SearchBuddy.init.tabs.get('lightboxes').buddy.activeTab == 'lightboxes') {
                    CorbisUI.Handlers.Lightbox.getLightboxItems(lightboxId);
                }
                if (CorbisUI.SearchBuddy.init.tabs.get('lightboxes').buddy.activeTab != 'lightboxes') {
                    CorbisUI.SearchBuddy.init.tabs.get('lightboxes').el.fireEvent('click');
                }
            }

        }
    },
    addToResponseNew: function(result, context, methodName) {
        //To not break the existing functionality added this new method
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.addToResponseNew');
        //1. highlight the current item
    //2. add it to the active lightbox
        new CorbisUI.SearchModels.lightboxBlock(result.MediaUID, result.CorbisID, { direction: 'top' }, result.RealProductUid);
        var count = CorbisUI.DomCache.get('LBXContainer').getElements('div.lightboxBlock').length;
        CorbisUI.Handlers.Lightbox.emptyItemDisplay(count);

        //increment image in lightbox count
        var imageCountProperty = CorbisUI.DomCache.get('LBXContainer').getProperty('imageCount');
        var imageCount = parseInt(imageCountProperty);
        if (!isNaN(imageCount)) {
            imageCount += 1;
        }
        else {
            //item already delete, so don't need to increment.
            imageCount = CorbisUI.DomCache.get('LBXContainer').getElements('div.lightboxBlock').length;
        }
        CorbisUI.DomCache.get('LBXContainer').setProperty('imageCount', imageCount.toString());
    },
    addToResponse: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.addToResponse');
        //1. highlight the current item
        //2. add it to the active lightbox
        new CorbisUI.SearchModels.lightboxBlock(results, null, { direction: 'top' });
        var count = CorbisUI.DomCache.get('LBXContainer').getElements('div.lightboxBlock').length;
        CorbisUI.Handlers.Lightbox.emptyItemDisplay(count);
    },

    deleteItem: function(el) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.deleteItem');
    },

    deleteItemResponse: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.deleteItemResponse');
    },
    emptyItemDisplay: function(count) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.emptyItemDisplay');
        if (CorbisUI.DomCache.get('LBXContainer').getElement('.centerMe') != null) {
            CorbisUI.DomCache.get('LBXContainer').getElement('.centerMe').setStyle('display', (count == 0) ? 'block' : 'none');
        }
    },
    getLightboxItems: function(lightboxId) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.getLightboxItems');
        CorbisUI.DomCache.get('lightboxProgress').setStyle('display', 'block');
        if ($type(CorbisUI.Handlers.Lightbox.currentLightboxItems) == 'array') {
            CorbisUI.Handlers.Lightbox.currentLightboxItems.stopChunk();
        }
        Corbis.Web.UI.SearchOld.SearchScriptService.GetLightBoxItemsV2(lightboxId, CorbisUI.Handlers.Lightbox.getLightboxItemsResponse, CorbisUI.Handlers.Lightbox.methodFailed);
        //Corbis.Web.UI.SearchOld.SearchScriptService.GetLightBoxItems(lightboxId, CorbisUI.Handlers.Lightbox.getLightboxItemsResponse, CorbisUI.Handlers.Lightbox.methodFailed);
    },

    getLightboxItemsResponse: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.getLightboxItemsResponse');
        CorbisUI.DomCache.get('lightboxProgress').setStyle('display', 'none');
        CorbisUI.DomCache.get('LBXContainer').getElements('.lightboxBlock').each(function(el) { el.destroy(); });
        CorbisUI.DomCache.get('LBXContainer').setProperty('imageCount', results.length);
        var tmpURL = window.location.href;
        if (tmpURL.indexOf("SearchTips") < 0)
            CorbisUI.Handlers.Lightbox.syncLightboxToImages();

        //console.log(results);
        //console.log(results);

        //console.log(CorbisUI.Handlers.Lightbox.delayedLoadItem);

        // this makes sure that the lightboxlist gets called first before attempting to
        // add an item to the lightbox for the very first time after page load
        // see BUG 20288
        if (CorbisUI.Handlers.Lightbox.delayedLoadItem) {
            var delayed = CorbisUI.Handlers.Lightbox.delayedLoadItem;
            Corbis.Web.UI.SearchOld.SearchScriptService.AddSearchItemToLightboxNew(delayed.CID, delayed.MID, delayed.LBID, delayed.HANDLER, delayed.METHODFAILED);
            CorbisUI.Handlers.Lightbox.delayedLoadItem = false;
        }

        CorbisUI.Handlers.Lightbox.emptyItemDisplay(results.length);
        if (results.length > 0) {
            // cleanup the old items
            // display each lightbox item

            CorbisUI.Handlers.Lightbox.currentLightboxItems = results;
            CorbisUI.Handlers.Lightbox.currentLightboxItems.flip().chunk(CorbisUI.Handlers.Lightbox.chunkProcess, 50);
        }
    },
    methodFailed: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.methodFailed');
        if (methodName == 'GetLightBoxItems') {
            CorbisUI.DomCache.get('lightboxProgress').setStyle('display', 'none');
            CorbisUI.DomCache.get('LBXContainer').getElements('.lightboxBlock').each(function(el) { el.destroy(); });
            CorbisUI.Handlers.Lightbox.resetLightboxToImages();
            CorbisUI.Handlers.Lightbox.emptyItemDisplay(results.length);
            alert(results.get_message());
        }
    },
    chunkProcess: function(item) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.chunkProcess');
        //console.log(item);
        new CorbisUI.SearchModels.lightboxBlock(item);
    },

    syncLightboxToImages: function() {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.syncLightboxToImages');
            //deselect all selected images
        CorbisUI.DomCache.get('ProductResults').getElements('span.ProductBlock').each(function(el) {
            var productid = el.getProperty('productuid');

            var productBlock = CorbisUI.ProductCache.get(productid);

            if (productBlock.checkLightboxStatus()) productBlock.updateIcon('LB', 'deselectIcon');
        });

        //Update images that's in current lightbox
        if (CorbisUI.DomCache.get('SBBX_lightboxes') != null) {
            CorbisUI.DomCache.get('SBBX_lightboxes').getElements('div.lightboxBlock').each(function(el) {
                var productBlock = CorbisUI.ProductCache.get(el.getProperty('mediaUid'));
                if (productBlock != null) productBlock.refreshObject().updateIcon('LB', 'selectIcon');
            });
        }
    },

    refreshItemAdded: function(corbisId, lightboxId, newLightboxName) {
        //console.log('CALLING: CorbisUI.Handlers.Lightbox.refreshItemAdded');
        var mediaId = CorbisUI.ProductCache.get(corbisId);
        var product = CorbisUI.ProductCache.get(mediaId);

        if (product) {
            product.refreshObject().updateIcon('LB', 'selectIcon')
        }

        this.reloadLightbox(lightboxId, newLightboxName);
    }
};

CorbisUI.Handlers.Quickpic = {

    downloadAll: function() {

        if (CorbisUI.Auth.GetSignInLevel() < 2) {
            CorbisUI.Auth.Check(2, CorbisUI.Auth.ActionTypes.Execute, "CorbisUI.Handlers.Quickpic.downloadAll_openModal()");
        }
        else {
            CorbisUI.Handlers.Quickpic.downloadAll_openModal();
        }

    },

    downloadAll_openModal: function() {
        if ($('quickPicsContainer').getElements('div.quickPicBlock').length > 0) {
            OpenNewIModal(CorbisUI.GlobalVars.SearchResults.urls.downloadQuickPic, 640, 540, 'QuickPic');
        }
    },

    moveQuickpic: function(ctl, corbisId, Url128, licenseModel, aspectRatio, title) {
        //console.log('CALLING: CorbisUI.Handlers.Quickpic.moveQuickpic');
        var item = $(ctl).getParent();
        //console.log(item);
        var method = (item.hasClass('QP_on')) ? 'delete' : 'add';
        //console.log(method);

        // see if quickpic tab is active, if not then "click" it
        // this interacts with objects in SearchBuddy.js
        if (window.location.href.toLowerCase().contains('mylightboxes.aspx')) {
            var pageInit = CorbisUI.MyLightboxes.init;
        } else {
            var pageInit = CorbisUI.SearchBuddy.init;
        }
        if (pageInit.activeTab != "quickpic") {
            var qp = pageInit.tabs.get("quickpic");
            qp.el.fireEvent('click');
        }

        switch (method) {
            case 'add':
                CorbisUI.Handlers.Quickpic.addTo(corbisId, Url128, licenseModel, aspectRatio, title);
                break;
        }

    },

    addTo: function(corbisId, Url128, licenseModel, aspectRatio, title) {
        LogOmnitureEvent("event15");
        //console.log('CALLING: CorbisUI.Handlers.Quickpic.addTo');
        Corbis.Web.UI.SearchOld.SearchScriptService.AddItemToQuickPick(corbisId, Url128, licenseModel, aspectRatio, title, CorbisUI.Handlers.Quickpic.addToResponse, CorbisUI.Handlers.Quickpic.addTo_methodFailed);
    },

    addToResponse: function(results, context, methodName) {
        var corbisId = results;
        console.log(corbisId);
        if (corbisId === "" || corbisId === null) {
            new CorbisUI.Popup('quickpicMaximumAlert', {
                showModalBackground: false,
                closeOnLoseFocus: true,
                positionVert: 'middle',
                positionHoriz: 'right'
            });

            ResizeModal('quickpicMaximumAlert');
        }
        else {
            //console.log('CALLING: CorbisUI.Handlers.Quickpic.addToResponse');

            //no product cache for lightbox, probably coming from enlargement, create new product
            if (!CorbisUI.ProductCache.has(results) && window.location.pathname.toLowerCase().endsWith('mylightboxes.aspx')) {
                var productBlock = new CorbisUI.Lightbox.ProductBlock(results);
            }

            var mediaId = CorbisUI.ProductCache.get(results);
            var product = CorbisUI.ProductCache.get(mediaId);
            if (CorbisUI.ProductCache.get("quickPicsContainer").getElement('div[corbisid=' + results + ']') == null) {
                new CorbisUI.SearchModels.quickPicBlock(mediaId, results);
            }
            var centerMe = CorbisUI.ProductCache.get("quickPicsContainer").getElement('.centerMe');
            if (!centerMe.hasClass('hdn')) { centerMe.addClass('hdn'); centerMe.setStyle('display', 'none'); }

            //var downloadAll = $('SBBX_quickpic').getElement('span[id$=quickPicDownloadAllLink]');
            CorbisUI.Handlers.Quickpic.emptyItemDisplay(1);
        }
    },

    addTo_methodFailed: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Quickpic.deleteItem_methodFailed');
        //console.log(results);
        //TODO: use mochaUI for alert window
        alert(results.get_message());
    },

    deleteItem: function(corbisId) {
        //console.log('CALLING: CorbisUI.Handlers.Quickpic.deleteItem');
        Corbis.Web.UI.SearchOld.SearchScriptService.RemoveItemFromQuickPick(corbisId, CorbisUI.Handlers.Quickpic.deleteItemResponse, CorbisUI.Handlers.Quickpic.deleteItem_methodFailed);
    },

    deleteItemResponse: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Quickpic.deleteItemResponse');
        var mediaId = CorbisUI.ProductCache.get(results);
        var product = CorbisUI.ProductCache.get(mediaId);
        if (product) product.updateIcon('QP', 'deselectIcon');

        // need delete action below here
        //console.log(results);
        if (CorbisUI.ProductCache.get("quickPicsContainer").getElement('div[corbisid=' + results + ']') != null)
            CorbisUI.ProductCache.get("quickPicsContainer").getElement('div[corbisid=' + results + ']').destroy();
        var qpBlocks = CorbisUI.ProductCache.get("quickPicsContainer").getElements('.quickPicBlock');
        if (qpBlocks.length == 0) {
            CorbisUI.ProductCache.get("quickPicsContainer").getElement('.centerMe').removeClass('hdn');
            CorbisUI.ProductCache.get("quickPicsContainer").getElement('.centerMe').setStyle('display', 'block');
        }
        else {
            CorbisUI.ProductCache.get("quickPicsContainer").getElement('.centerMe').addClass('hdn');
            CorbisUI.ProductCache.get("quickPicsContainer").getElement('.centerMe').setStyle('display', 'none');
        }
        CorbisUI.Handlers.Quickpic.emptyItemDisplay(qpBlocks.length);

    },

    deleteItem_methodFailed: function(results, context, methodName) {
        //console.log('CALLING: CorbisUI.Handlers.Quickpic.deleteItem_methodFailed');
        //console.log(results);
        //TODO: use mochaUI for alert window
        alert(results.get_message());
    },
    emptyItemDisplay: function(count) {
        if (CorbisUI.GlobalVars.SearchResults) {
            if (CorbisUI.GlobalVars.SearchResults.quickPicDownloadAllBtn != null) {
                setGlassButtonDisabled(CorbisUI.GlobalVars.SearchResults.quickPicDownloadAllBtn, count == 0);
            }
        }
        if (CorbisUI.GlobalVars.Lightbox) {
            if (CorbisUI.GlobalVars.Lightbox.quickPicDownloadAllBtn != null) {
                setGlassButtonDisabled(CorbisUI.GlobalVars.Lightbox.quickPicDownloadAllBtn, count == 0);
            }
        }

        //CorbisUI.DomCache.get('LBXContainer').getElement('.centerMe').setStyle('display', (count == 0) ? 'block' : 'none');
    },

    refreshItemAdded: function(corbisId) {
        var mediaId = CorbisUI.ProductCache.get(corbisId);
        var product = CorbisUI.ProductCache.get(mediaId);

        if (product) {
            product.refreshObject().updateIcon('QP', 'selectIcon')
        }

        CorbisUI.Search.Handler.refreshQuickPicBuddy();

        this.emptyItemDisplay(1);
    }
};

CorbisUI.Handlers.Subscription = {
    delayedLoadItem: false,

    downloadAll: function() {

        if (CorbisUI.Auth.GetSignInLevel() < 2) {
            CorbisUI.Auth.Check(2, CorbisUI.Auth.ActionTypes.Execute, "CorbisUI.Handlers.Subscription.downloadAll_openModal()");
        }
        else {
            var remainingCount = document.body.getElement("div.subscriptionCounts").getElement('.remainingCount').get('text');
            if (remainingCount != null) {
                CorbisUI.Subscription.DownloadSubscriptionImages(remainingCount, false, false);
            }
            // Corbis.Web.UI.SearchOld.SearchScriptService.GetRemainingDownloadCount(CorbisUI.Handlers.Subscription.checkOverCount, CorbisUI.MethodFailed);
        }
    },
   
    downloadAll_openModal: function() {
        if ($('subscriptionContainer').getElements('div.subscriptionBlock').length > 0) {
            OpenNewIModal(CorbisUI.GlobalVars.SearchResults.urls.downloadSubscription, 640, 540, 'Subscription');
        }
    },
    afterSignIn: function(CorbisId) {
        var mediaId = CorbisUI.ProductCache.get(CorbisId);

        // setup cookie event
        CorbisUI.CookieEvents.addCookieEvent(function() {
            CorbisUI.Handlers.Subscription.afterSignIn_cookieEvent(this.vars);
        }, { CID: CorbisId, MID: mediaId });

        window.location.reload();

    },
    addTo: function(CorbisId) {
        //console.log('CALLING: CorbisUI.Handlers.Subscription.addTo');
        if (CorbisUI.Auth.GetSignInLevel() < 1) {
            CorbisUI.Auth.Check(1, CorbisUI.Auth.ActionTypes.Execute, "CorbisUI.Handlers.Subscription.afterSignIn('" + CorbisId + "'); ");
        }
        else {
            CorbisUI.Handlers.Subscription.addProductToSubscription(CorbisId);
        }
    },

    addProductToSubscription: function(CorbisId, reloadPage) {

        //console.profile();
        var mediaId = CorbisUI.ProductCache.get(CorbisId);
        var product = CorbisUI.ProductCache.get(mediaId);
        product.refreshObject().setupObject();

        if (reloadPage) product.refreshPage = reloadPage;

        // check if we are on lightbox page or not
        var LBPage = (window.location.href.toLowerCase().contains('mylightboxes.aspx')) ? true : false;

        // condensed the action down to 7 lines from 17 lines
        if (!product.activeStates.SB && CorbisUI.DomCache.get('SBBX_subscriptions')) {
            var CorbisID = (LBPage) ? CorbisId : product.corbisID;
            var MediaID = (LBPage) ? product.mediaUID : mediaId;
            var ActionObject = (LBPage) ? "MyLightboxes" : "SearchBuddy";
            Corbis.Web.UI.SearchOld.SearchScriptService.AddSearchItemToSubscriptionNew(CorbisID, MediaID, CorbisUI.Handlers.Subscription.addToResponseNew, CorbisUI.Handlers.Subscription.methodFailed);
            CorbisUI[ActionObject].init.tabs.get('subscriptions').el.fireEvent('click');
        }

    },

    addToResponseNew: function(result, context, methodName) {
        if (result == null) {
            new CorbisUI.Popup('subscriptionMaximumAlert', {
                showModalBackground: false,
                closeOnLoseFocus: true,
                positionVert: 'middle',
                positionHoriz: 'right'
            });
            ResizeModal('subscriptionMaximumAlert');

        } else {
        LogOmnitureEvent("event45"); 
            new CorbisUI.SearchModels.subscriptionBlock(result.MediaUID, result.CorbisID, { direction: 'top' }, null);
            
            var imageCount = parseInt(CorbisUI.DomCache.get('subscriptionContainer').getProperty('imageCount'));
            
            if (!isNaN(imageCount)) {
                imageCount++;
                CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', imageCount);
                CorbisUI.DomCache.get('SBBX_subscriptions').getElement('span.imageCount').set('text', imageCount);
            }
            
            if (window.location.href.toLowerCase().contains('mylightboxes.aspx')) {
                setGlassButtonDisabled($(CorbisUI.GlobalVars.Lightbox.subscriptionDownloadAllBtn), false);
            }
            else {
                setGlassButtonDisabled(CorbisUI.GlobalVars.SearchResults.subscriptionDownloadAllBtn, false);
            }

            
            if (document.body.getElement("div.subscriptionContainer").getElement('.centerMe') != null) {
                document.body.getElement("div.subscriptionContainer").getElement('.centerMe').setStyle('display', 'none');
            }
            if (document.body.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe') != null) {
                document.body.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe').setStyle('display', 'none');
            }

        }

    },
    /*addToResponse: function(results, context, methodName) {
    //console.log('CALLING: CorbisUI.Handlers.Lightbox.addToResponse');
    //1. highlight the current item
    //2. add it to the active lightbox
    new CorbisUI.SearchModels.subscriptionBlock(results, null, { direction: 'top' });
    var count = CorbisUI.DomCache.get('subscriptionContainer').getElements('div.subscriptionBlock').length;
    CorbisUI.Handlers.Subscription.emptyItemDisplay(count);
    },*/
    deleteItem: function(mediaUid) {
        Corbis.Web.UI.SearchOld.SearchScriptService.DeleteSubscriptionItem(mediaUid, CorbisUI.Handlers.Subscription.deleteItemResponse, CorbisUI.Handlers.Subscription.deleteItem_methodFailed);
    },
    deleteItemResponse: function(results, context, methodName) {
        console.log('CALLING: CorbisUI.Handlers.Quickpic.deleteItemResponse');
        var mediaId = CorbisUI.ProductCache.get(results);
        var product = CorbisUI.ProductCache.get(mediaId);
        if (product) product.updateIcon('SB', 'deselectIcon');

        // need delete action below here
        //console.log(results);  
        if (CorbisUI.ProductCache.get("subscriptionContainer").getElement('div[corbisid=' + results + ']') != null)
            CorbisUI.ProductCache.get("subscriptionContainer").getElement('div[corbisid=' + results + ']').destroy();
        var sbBlocks = CorbisUI.ProductCache.get("subscriptionContainer").getElements('.subscriptionBlock');
        if (sbBlocks.length == 0 && document.body.getElement("div.subscriptionContainer").getElement('.centerMe') != null) CorbisUI.ProductCache.get("subscriptionContainer").getElement('.centerMe').removeClass('hdn');
        CorbisUI.Handlers.Subscription.emptyItemDisplay(sbBlocks.length);
        CorbisUI.DomCache.get('SBBX_subscriptions').getElement('span.imageCount').set('text', sbBlocks.length.toString());

        if (window.location.href.toLowerCase().contains('mylightboxes.aspx') && sbBlocks.length == 0) {
            setGlassButtonDisabled($(CorbisUI.GlobalVars.Lightbox.subscriptionDownloadAllBtn), true);
        }
    },

    deleteItem_methodFailed: function(results, context, methodName) {
        alert(results.get_message());
    },

    getSubscriptionItems: function() {
        //CorbisUI.DomCache.get('lightboxProgress').setStyle('display', 'block');
        Corbis.Web.UI.SearchOld.SearchScriptService.GetSubscriptionItems(CorbisUI.Handlers.Subscription.getSubscriptionItemsResponse, CorbisUI.Handlers.Subscription.methodFailed);
    },

    getSubscriptionItemsResponse: function(results, context, methodName) {
        if (results != null) {
            CorbisUI.DomCache.get('subscriptionContainer').getElements('.subscriptionBlock').each(function(el) { el.destroy(); });
            CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', results.length);

            var tmpURL = window.location.href;
            if (tmpURL.indexOf("SearchTips") < 0)
                CorbisUI.Handlers.Subscription.syncSuscriptionToImages();

            if (CorbisUI.Handlers.Subscription.delayedLoadItem) {
                var delayed = CorbisUI.Handlers.Subscription.delayedLoadItem;
                Corbis.Web.UI.SearchOld.SearchScriptService.AddSearchItemToSubscriptionNew(delayed.CID, delayed.MID, null, delayed.HANDLER, delayed.METHODFAILED);
                CorbisUI.Handlers.Subscription.delayedLoadItem = false;
            }

            CorbisUI.Handlers.Subscription.emptyItemDisplay(results.length);
            if (results.length > 0) {
                // cleanup the old items
                // display each lightbox item
                CorbisUI.Handlers.Subscription.currentLightboxItems = results;
                CorbisUI.Handlers.Subscription.currentLightboxItems.chunk(CorbisUI.Handlers.Subscription.chunkProcess, 25);
                CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', results.length.toString());
                //document.body.getElement('span.imageCount').set('text', results.length.toString());
                CorbisUI.DomCache.get('SBBX_subscriptions').getElement('span.imageCount').set('text', results.length.toString());
                if (window.location.href.toLowerCase().contains('mylightboxes.aspx')) setGlassButtonDisabled($(CorbisUI.GlobalVars.Lightbox.subscriptionDownloadAllBtn), false);
            }
        }
    },

    emptyItemDisplay: function(count) {
        if (CorbisUI.GlobalVars.SearchResults) {
            if (CorbisUI.GlobalVars.SearchResults.subscriptionDownloadAllBtn != null) {
                setGlassButtonDisabled(CorbisUI.GlobalVars.SearchResults.subscriptionDownloadAllBtn, count == 0);
            }
        }
        if (CorbisUI.DomCache.get('subscriptionContainer').getElement('.centerMe') != null) {
            CorbisUI.DomCache.get('subscriptionContainer').getElement('.centerMe').setStyle('display', (count == 0 && document.body.getElement("div.subscriptionCounts").getElement('.remainingCount').get('text') != '0') ? 'block' : 'none');
        }
        if (CorbisUI.DomCache.get("subscriptionContainer").getElement('.remainingZerocenterMe') != null) {
            CorbisUI.DomCache.get("subscriptionContainer").getElement('.remainingZerocenterMe').setStyle('display', (count == 0 && document.body.getElement("div.subscriptionCounts").getElement('.remainingCount').get('text') == '0') ? 'block' : 'none');
        }

    },

    chunkProcess: function(item) {
        //console.log(item);
        new CorbisUI.SearchModels.subscriptionBlock(item);
    },
    syncSuscriptionToImages: function() {
        //deselect all selected images
        CorbisUI.DomCache.get('ProductResults').getElements('span.ProductBlock').each(function(el) {
            //var productBlock = el.retrieve('objectReference');
            var productid = el.getProperty('productuid');

            var productBlock = CorbisUI.ProductCache.get(productid);

            // if (productBlock.checkLightboxStatus()) productBlock.updateIcon('LB', 'deselectIcon');
        });

        //Update images that's in current lightbox
        if (CorbisUI.DomCache.get('SBBX_subscriptions') != null) {
            CorbisUI.DomCache.get('SBBX_subscriptions').getElements('div.subscriptionBlock').each(function(el) {
                var productBlock = CorbisUI.ProductCache.get(el.getProperty('mediaUid'));
                if (productBlock != null) productBlock.refreshObject().updateIcon('SB', 'selectIcon');
            });
        }
    },
    refreshSubscriptionItemAdded: function(result, context, methodName) {
        //if there is a sign in link it means the user has just signed in and the whole page will need to be updated.
        //since the image result maybe different and the buddy would be different also.
        if ($(CorbisUI.GlobalVars.SearchResults.buddySignInLink)) {
            window.location.reload();
        }
        else {
            new CorbisUI.SearchModels.subscriptionBlock(result.MediaUID, result.CorbisID, { direction: 'top' }, null);
            var count = CorbisUI.DomCache.get('subscriptionContainer').getElements('div.subscriptionBlock').length;
            CorbisUI.Handlers.Subscription.emptyItemDisplay(count);
            //increment image in Subscription count
            var imageCountProperty = CorbisUI.DomCache.get('subscriptionContainer').getProperty('imageCount');
            var imageCount = parseInt(imageCountProperty);
            if (!isNaN(imageCount)) {
                imageCount += 1;
            }
            else {
                //item already delete, so don't need to increment.
                imageCount = CorbisUI.DomCache.get('subscriptionContainer').getElements('div.subscriptionBlock').length;
            }
            if (imageCount > 0) {
                if (document.body.getElement("div.subscriptionContainer").getElement('.centerMe') != null) {
                    document.body.getElement("div.subscriptionContainer").getElement('.centerMe').addClass('hdn');
                }
                if (document.body.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe') != null) {
                    document.body.getElement("div.subscriptionContainer").getElement('.remainingZerocenterMe').setStyle('display', 'none');
                }
            }
            CorbisUI.DomCache.get('subscriptionContainer').setProperty('imageCount', imageCount.toString());
            document.body.getElement('span.imageCount').set('text', imageCount.toString());
            if (window.location.href.toLowerCase().contains('mylightboxes.aspx')) {
                if (CorbisUI.MyLightboxes.init.tabs.get('subscriptions') != null) {
                    CorbisUI.MyLightboxes.init.tabs.get('subscriptions').el.fireEvent('click');
                }
            }
            else {
                if (CorbisUI.SearchBuddy.init.tabs.get('subscriptions') != null) {
                    CorbisUI.SearchBuddy.init.tabs.get('subscriptions').el.fireEvent('click');
                }
            }
        }
    },

    refreshItemAdded: function(corbisId) {
        var mediaId = CorbisUI.ProductCache.get(corbisId);
        var product = CorbisUI.ProductCache.get(mediaId);

        if (product) {
            product.refreshObject().updateIcon('SB', 'selectIcon')
        }

        CorbisUI.Search.Handler.refreshsubScriptioinBuddy();

        this.emptyItemDisplay(1);
    },

    methodFailed: function(results, context, methodName) {
        CorbisUI.MethodFailed(results, context, methodName);
    }
};
CorbisUI.Search.AutoCompleteDisplayOptions = {

setAutoCompleteOption: function() 
{    
    var var_AC = $('moreDisplayOptionsWindow').getElement('div[id$=chk_AutoComplete]');
    var checkedState = CorbisUI.ImageCb.getImageCbObject(var_AC).getCheckedState();    
    //-------------------    
       
       CorbisUI.Search.AutoCompleteDisplayOptions.AutoCompleteExtenderUpdateToggler(checkedState)  ;
       CorbisUI.Search.AutoCompleteDisplayOptions.ChkAutoCompleteUpdater("setString")   ;
    return false;
},
    AutoCompleteExtenderUpdateToggler: function(result) {
        Corbis.Web.UI.SearchOld.SearchScriptService.displayOptionsAutoComplete(result,
         CorbisUI.Search.AutoCompleteDisplayOptions.AutoCompleteExtenderUpdateTogglerInner,
            CorbisUI.methodFailed);
    },
    AutoCompleteExtenderUpdateTogglerInner: function(result) {
        var var_AutoCompleteDiv = $("KeywordsAutoComplete_Window");
        if (var_AutoCompleteDiv) {
            if (result) {
                if ($("varDivAc_chkStatus")) {
                    $("varDivAc_chkStatus").innerHTML = "true";
                }

            }
            else {
                $("KeywordsAutoComplete_Window").setStyle('display', 'none');
                if ($("varDivAc_chkStatus")) {
                    $("varDivAc_chkStatus").innerHTML = "false";
                }
            }
        }
    },
    ChkAutoCompleteUpdater: function(setOptionInPrm) { //Possible Values For The Parameter:  setChkBox setString
        // No functionality without parameters
        var var_AC = null;
        var var_varDivAC = null;
        if ($('moreDisplayOptionsWindow')) {
            var_AC = $('moreDisplayOptionsWindow').getElement('div[id$=chk_AutoComplete]');
        }
        if ($('varDivAc_chkStatus')) {
            var_varDivAC = $("varDivAc_chkStatus");
        }

        if (setOptionInPrm == "setChkBox") {
            if (var_varDivAC) {
                var statusBool = false;

                if (var_varDivAC.innerHTML.toLowerCase() == 'true')
                { statusBool = true; }


                var var_AC = $('moreDisplayOptionsWindow').getElement('div[id$=chk_AutoComplete]');
                if (var_AC) {
                    CorbisUI.ImageCb.getImageCbObject(var_AC).setCheckState(statusBool, false);

                }
            }
        }

        else if (setOptionInPrm == "setString") {
            var var_AC =


$('moreDisplayOptionsWindow').getElement('div[id$=chk_AutoComplete]');
            if (var_AC) {
                if (var_varDivAC) {
                    var_varDivAC.innerHTML = CorbisUI.ImageCb.getImageCbObject(var_AC).getCheckedState() + '';
                }
            }
        }
    },


    ChkClarificationUpdater: function(setOptionInPrm) { //Possible Values For The Parameter:  setChkBox setString
        // No functionality without parameters

        var var_AC = null;
        var var_varDivAC = null;
        if ($('moreDisplayOptionsWindow')) {
            var_AC = $('moreDisplayOptionsWindow').getElement('div[id$=termClarf]');
        }
        if ($('varDivCl_chkStatus')) {
            var_varDivAC = $("varDivCl_chkStatus");
        }


        if (setOptionInPrm == "setChkBox") {
            if (var_varDivAC) {
                var statusBool = false;


                if (var_varDivAC.innerHTML.toLowerCase() == 'true')
                { statusBool = true; }

                if (var_AC) {
                    CorbisUI.ImageCb.getImageCbObject(var_AC).setCheckState(statusBool, false);
                }
            }
            else {
                if (var_AC) {
                    if (var_varDivAC) {
                        var_varDivAC.innerHTML = CorbisUI.ImageCb.getImageCbObject(var_AC).getCheckedState() + '';
                    }
                }
            }
        }
        else if (setOptionInPrm == "setString") {
            if (var_AC) {
                if (var_varDivAC) {
                    var_varDivAC.innerHTML = CorbisUI.ImageCb.getImageCbObject(var_AC).getCheckedState() + '';
                }
            }
        }
    }


};

CorbisUI.Handlers.Cart = {

addTo: function(CorbisId) {
    //console.log('CALLING: CorbisUI.Handlers.Cart.addTo');
    if (CorbisUI.Auth.GetSignInLevel() < 1) {

        var mediaId = CorbisUI.ProductCache.get(CorbisId);
        CorbisUI.Auth.Check(1, CorbisUI.Auth.ActionTypes.Execute,
"CorbisUI.Handlers.Cart.addProductToCart_AfterLogIn('" + CorbisId + "','" + mediaId
+ "')");
    } else {
        CorbisUI.Handlers.Cart.addProductToCart(CorbisId);
    }
},

addProductToCart_AfterLogIn: function(CorbisId, mediaId) {
    CorbisUI.CookieEvents.addCookieEvent(function() {
        var temp_Str = "CorbisUI.Handlers.Cart.addProductToCart('" +
this.vars.UID + "','media','" + this.vars.PrID + "');";
        setTimeout(temp_Str, 200);
    }, { UID: CorbisId, PrID: mediaId });
    setTimeout("window.location.reload();", 500);
},

addProductToCart: function(CorbisId, reloadPage, mediaId_param) {
    //console.log('CALLING: CorbisUI.Handlers.Cart.addProductToCart');
    var product;
    var mediaId = CorbisUI.ProductCache.get(CorbisId);
    if (!mediaId) {
        if (reloadPage) {
            if (mediaId_param) {
                if (reloadPage.toString() == 'media') {
                    var addToCart = new CorbisUI.Cart.AddToCart(mediaId_param);
                    addToCart.addOfferingToCart();
                }
            }
        }
    }
    else {
        if (reloadPage) {
            if (reloadPage.toString() == 'media')
            { reloadPage = null; }
        }
        product = CorbisUI.ProductCache.get(mediaId);
        product.refreshObject().setupObject();
        if (reloadPage) product.refreshPage = reloadPage;
        //if (product)         product.refreshObject().setRefreshPage(reloadPage).addProductToCart();
        if (!product.activeStates.CT) {
            var addToCart = new CorbisUI.Cart.AddToCart(product.productUID);
            addToCart.context = product;
            addToCart.onSuccess = CorbisUI.Handlers.Cart.addToResponse;
            if (reloadPage) addToCart.refreshPage = reloadPage;
            addToCart.addOfferingToCart();
        }
    }
},

    addToResponse: function(results, context) {
        //console.log('CALLING: CorbisUI.Handlers.Cart.addToResponse');
        //console.log(results);
        //console.log(this.context);

        var thisItem
        if (context) {
            thisItem = context;
        }
        else if (this.context) {
            thisItem = this.context;
        }
        else {
            thisItem = this;
        }

        thisItem.setupObject();

        thisItem.updateIcon('CT', 'selectIcon');

        //update lighbox buddy
        var lightboxItem = CorbisUI.DomCache.get('LBXContainer').getElement('div[corbisid=' + thisItem.corbisID + ']');
        if (lightboxItem) {
            CorbisUI.Handlers.Lightbox.reloadLightbox(CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList').value, null);
        }

        //update cart count
        UpdateCartCount(results);

        if (thisItem.refreshPage) {
            window.location = window.location;
        }
    },

    syncCartToImages: function() {
        //deselect all selected images
        CorbisUI.DomCache.get('productBlocks').each(function(el) {
            //var productBlock = el.retrieve('objectReference');
            var productid = el.getProperty('productuid');

            var productBlock = CorbisUI.ProductCache.get(productid);

            if (CorbisUI.cartMediaUidList.has(productid)) productBlock.updateIcon('CT', 'selectIcon');
        });

    },

    refreshItemAdded: function(mediaId, corbisId, cartCount) {
        //if there is a sign in link it means the user has just signed in and the whole page will need to be updated.
        //since the image result maybe different and the buddy would be different also.
        if ($(CorbisUI.GlobalVars.SearchResults.buddySignInLink)) {
            window.location.reload();
        }
        else {
            var productBlock = CorbisUI.ProductCache.get(mediaId);
            if (productBlock) {
                CorbisUI.Handlers.Cart.addToResponse(cartCount, productBlock);
            }
            else {
                //if there no product, we just update the buddy.
                var lightboxItem = $('LBXContainer').getElement('div[corbisid=' + corbisId + ']');
                if (lightboxItem) {
                    //Adding item to cart cache
                    CorbisUI.cartMediaUidList.set(mediaId, true);
                    CorbisUI.Handlers.Lightbox.reloadLightbox(CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList').value, null);
                }

                UpdateCartCount(cartCount);
            }
        }
    }
};

//TODO: refactor a this a little more
CorbisUI.cartMediaUidList = new Hash({});
function getCartMediaUidListResponse(results, context, methodName) {
    //console.log('CALLING: getCartMediaUidListResponse:');
    //console.log(results);
    results.each(function(item) {
        CorbisUI.cartMediaUidList.set(item, true);
    });
    //cartMediaUidList = results;
}


/////////////////////////////////////
// WINDOW DOMREADY EVENTS
// if you add new functions,
// add them in statics
/////////////////////////////////////



// setup queue
CorbisUI.QueueManager.addQueue('searchDomReady', {
    canRerun: true,
    delay: true
}).addItem('domCacheSetup', function() {

    //todo: refactor
    //push the productuid list from the server during the page load, don't use the extra call from client
    Corbis.Web.UI.SearchOld.SearchScriptService.GetCartMediaUidList(getCartMediaUidListResponse);

    // set some cached items
    CorbisUI.DomCache.add([
            'ProductResults',
            'hiddenWorkshop',
            'LBXContainer',
            'SBBX_lightboxes',
            'cartCount',
            'quickPicsContainer',
            'SearchBuddy',
            'modalOverlay',
            'FooterContent',
            'searchProgIndicator'
        ]);
    //if (window.location.href.toLowerCase().contains('imagegroups.aspx')) CorbisUI.DomCache.addObject('SBBX_lightboxes', $('SBBX_filters'));

    //Check to make sure there are products on the page (this might be SearchTips with 0 products)
    if (document.getElements('span.ProductBlock').length > 0)
        CorbisUI.DomCache.addCollection('productBlocks', CorbisUI.DomCache.get('ProductResults').getElements('span.ProductBlock'));

    if ($('goBtn') != null) {
        var removeAction = ";$('goBtn').getElement('a').removeAttribute('href');";
        var href = $('goBtn').getElement('a').getAttribute('href') + removeAction;
        $('goBtn').getElement('a').setAttribute('href', href);
    }


}).addItem('simplestuff', function() {
    //registerTooltips(false);

    CorbisUI.ProductTooltip = new CorbisUI.Tooltip('#ProductResults .thumbWrap', {
        className: 'TIP-product-block',
        onHide: function(tip) {
            //console.log('HIDE');
            if (showTooltip()) tip.fade(this.options.hideMethod);
        },
        onShow: function(tip) {
            //console.log('SHOW');
            if (showTooltip()) tip.fade(this.options.showMethod);
        }
    });

    if ($('EditorialChildren') != null) {
        CorbisUI.ExtendedSearch.setCheckedState_flyout($('EditorialChildren').getElement('div[id$=documentary]'));
        CorbisUI.ExtendedSearch.setCheckedState_flyout($('CreativeChildren').getElement('div[id$=rightsManaged]'));
    }

    noPeopleChanged(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.noPeople);
}).addItem('productBlockSetup', function() {
    // apply product block objects to dom elements if they exist on the page
    /*if (window.location.href.toLowerCase().contains('mylightboxes.aspx')) {
        if (document.getElements('span.ProductBlock').length > 0) {
            CorbisUI.DomCache.get('productBlocks').each(function(el) {
                var item = new CorbisUI.SearchModels.ProductBlock(el);
            });
        }
    } else {*/
        if (document.getElements('span.ProductBlock').length > 0) {
            CorbisUI.DomCache.get('productBlocks').each(function(el) {
                var item = new CorbisUI.SearchModels.ProductBlock(el);
            });
        }
    /*}*/
    
}).addItem('finalItems', function() {
    //search term clarification if exists on page (might not with SearchTips)
    if ($(CorbisUI.GlobalVars.SearchResults.showClarificationPopup)) {
        var displayClarificationPopup = $(CorbisUI.GlobalVars.SearchResults.showClarificationPopup);
        if (displayClarificationPopup.value == 'true' || displayClarificationPopup.value == 'True') {
            OpenAmbiguousModal();
        }
    }

    var getZeroSearchResults = $(CorbisUI.GlobalVars.SearchResults.zeroSearchResults).value;
    if (getZeroSearchResults == 'True') {
        applyZeroResultsStyles();
    }

    // load lightbox data for imagegroups
    if (window.location.href.toLowerCase().contains('imagegroups.aspx')) {
        this.dataLoaded = true;
        //handle data load
        // 1 grab lightboxId
        //var lightboxDropdown = this.getElement('select[name$=lightboxList]');
        // 2 call web service
        //var lightboxId = lightboxDropdown.getSelected();

        var selectedList = CorbisUI.DomCache.get('SBBX_lightboxes').getElement('select.lightboxList');
        if (selectedList != null && selectedList.getSelected()[0] != null) {

            var selectedIndex = selectedList.selectedIndex;
            var lightboxId = selectedList.options[selectedIndex].value;

            //console.log(lightboxId);
            // 3 return handling
            //Corbis.Web.UI.SearchOld.SearchScriptService.GetLightBoxItems(lightboxId, this.getLightboxItemsCallback.bind(this));
            // 4 lightbox items display

            // LAUNCH the getLightboxItems handler
            CorbisUI.Handlers.Lightbox.getLightboxItems(lightboxId);
        }
    }
});

// setup the queue to run
if (window.location.href.toLowerCase().contains('searchresults.aspx') || window.location.href.toLowerCase().contains('imagegroups.aspx')) {
    CorbisUI.QueueManager.searchDomReady.setupDomReady();
}



/////////////////////////////////////
// SERVICE FUNCTIONS?
/////////////////////////////////////

function methodFailed(results, context, methodName)
{
    //console.log(results);
    //TODO: use mochaUI for alert window
    alert(results.get_message());
}

function endRequestHandler(sender, args) {
    //alert(sender._postBackSettings.sourceElement.id);
    if (sender._postBackSettings.sourceElement &&
                (sender._postBackSettings.sourceElement.id.contains('quickpicField')
                  || sender._postBackSettings.sourceElement.id.contains('subScriptioinField')
                  || sender._postBackSettings.sourceElement.id.contains('addToLightboxBtn'))
       )
        return;
}        

//function registerTooltips(isFirstTime)
//{
//   
//    $('aspnetForm').getAllNext('.TIP-product-block').destroy();
//    
//    var tipShowDelay = 500;
//    var tipHideDelay = 100;
//    var tipShowMethod = "in";
//    var tipHideMethod = "out";
//    if(Browser.Engine.trident) {
//        tipShowDelay = 0;
//        tipHideDelay = 0;
//        tipShowMethod = "show";
//        tipHideMethod = "hide";
//    }
//    thumbTips = new Tips('#ProductResults .thumbWrap', {
//        showDelay: tipShowDelay,
//        hideDelay: tipHideDelay,
//        className: 'TIP-product-block', 
//        onHide: function(tip){
//            if (showTooltip()) tip.fade(tipHideMethod);
//        }, 
//        onShow:function(tip) {
//            if (showTooltip()) tip.fade(tipShowMethod);
//        }
//    });

//    

//}

function showTooltip() {
    var previewCb = $('header2').getElement('div[id$=previewCheckbox]');
    if (previewCb == null)
        return true;
    if (CorbisUI.ImageCb.getImageCbObject(previewCb) == null)
        return true;
    var previewValue = CorbisUI.ImageCb.getImageCbObject(previewCb).getCheckedState() ? '0' : '1';
    return previewValue == '0';
    //return ($$('.previewOffSelected').length == 0);
}

function InitiateTimer() {
// No longer used - 15065
	if (timer!=null)window.clearInterval(timer);
	timer = window.setInterval("window.clearInterval(timer);if (testSBCategoriesChecked()) secondTimer()", 2000);
}

function resetSearchCategoryChecks() {
    // kill the search timer first
    //stopSearch = true;
    if (timer != null) window.clearInterval(timer);
    if (timer2 != null) window.clearInterval(timer2);
    // reset the checks
 if (CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.subscriptionOnly)) {
        CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.subscriptionOnly).setCheckState(false, true);
    }    
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.creative).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.editorial).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rmLicense).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rfLicense).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.noPeople).setCheckState(false, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.photography).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.illustration).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.color).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.blackWhite).setCheckState(true, true);
    CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.onlyModelReleased).setCheckState(false, true);
    // clearn up the triggered timer
//    if (timer != null) window.clearInterval(timer);
//    if (timer2 != null) window.clearInterval(timer2);
    //
}

function testSBCategoriesChecked()
{
if (window.location.href.toLowerCase().contains('searchresults.aspx')) 
   {
       noLicense = !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rmLicense).getCheckedState() &&
                   !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rfLicense).getCheckedState();
       noCat = !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.editorial).getCheckedState() &&
               !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.creative).getCheckedState();
       noPhoto = !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.photography).getCheckedState() &&
                 !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.illustration).getCheckedState();
       noColor = !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.color).getCheckedState() &&
                 !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.blackWhite).getCheckedState();
        
    var noResults = noLicense || noCat || noColor || noPhoto;
    
    //alert(noResults);
    if (noResults)
    {
        if (!$('noSearchResultsWarningWindow'))
        {
            var sbCoords = CorbisUI.DomCache.get('SearchBuddy').getCoordinates();
            var sbScroll = $(document.body).getScroll();
            var scrollOffset = sbCoords.top + sbScroll.y;
            var vPos = noCat ? 10 : noLicense ? 98 : noPhoto ? 232 : 287;
            vPos += scrollOffset;
            new CorbisUI.Popup('noSearchResultsWarning', { 
                createFromHTML: true,
                showModalBackground: false,
                centerOverElement: 'noSearchResultsWarning',
                closeOnLoseFocus: true,
                positionVert: vPos, 
                positionHoriz: 212,
                replaceText: [ '' ]
            });
            setTimeout(setErrorOptions, 100);
        }
        return false;
    }
    else
    {
        MochaUI.CloseModal('noSearchResultsWarning');
        return true;
    }
    }
}

function setErrorOptions()
{
    var pop = $('noSearchResultsWarningWindow');
    if (!pop) return false;
    
    var items = {
        license : pop.getElement('p[textKey=License]'),
        category : pop.getElement('p[textKey=Category]'),
        color : pop.getElement('p[textKey=Color]'),
        photo : pop.getElement('p[textKey=Photo]')
    }
    
    items.license.setStyle('display', 'none');
    items.category.setStyle('display', 'none');
    items.color.setStyle('display', 'none');
    items.photo.setStyle('display', 'none');
    
    if (noCat)
        items.category.setStyle('display', 'block');
    else if (noLicense)
        items.license.setStyle('display', 'block');
    else if (noColor)
        items.color.setStyle('display', 'block');
    else if (noPhoto)
        items.photo.setStyle('display', 'block');

    CorbisUI.DomCache.get('modalOverlay').addEvent('click', function() {
        $(this).setStyle('display', 'none');
    });
    CorbisUI.DomCache.get('searchProgIndicator').setStyle('display', 'none');
    
}

// This is no longer used
function secondTimer() {
    if (stopSearch) {
        if (timer) window.clearInterval(timer);
        if (timer2) window.clearInterval(timer2);
        stopSearch = false;
        return;
    }
    if (timer2 != null) window.clearInterval(timer);
	timer2 = window.setInterval("window.clearInterval(timer2);invokeSearch(true)", 1500);
	CorbisUI.DomCache.get('searchProgIndicator')
	    .setStyles({
	        'display': 'block',
	        'height': document.body.scrollHeight + 'px',
	        'left': '206px'
	    });
	$('processingFilters').setStyle('display', 'block');
}

function noPeopleChanged(chk) {
   if (window.location.href.toLowerCase().contains('searchresults.aspx')) 
   {
        var checked = CorbisUI.ImageCb.getImageCbObject(chk).getCheckedState();
        $('divNoPeopleIcon').setStyle('background-position', checked ? 'bottom right' : 'top right');
   }

}

function subscriptionOnlyChanged1(chk,inSearchBuddy) {
    //debugger
    var checked = CorbisUI.ImageCb.getImageCbObject(chk).getCheckedState();
    var value = (checked) ? 'center -43px' : 'center -23px';
    var itemToGet = (inSearchBuddy) ? $('SearchBuddy').getElement('div.searchBuddy_subscription') : $('subscriptionIcon');
    //console.log(itemToGet);
    itemToGet.setStyle('background-position', value);
}
function EditorialChanged(checked)
{
    var checks = $('EditorialChildren').getElements('div.imageCheckbox');

    checks.each(function(cb) {
        CorbisUI.ImageCb.getImageCbObject(cb).setCheckState(checked, false);
    });
}

//var showTooltip = $$('previewOffSelected');
function openCreateLightbox()
{

    //console.log('CALLING: openCreateLightbox');
    
	if (!CorbisUI.GlobalVars.SearchResults.isAnonymous)
	{
	    new CorbisUI.Popup('createLightboxModalPopup', { 
			showModalBackground: false,
			centerOverElement: 'SearchBuddy',
			closeOnLoseFocus: true,
			positionVert: '60', 
			positionHoriz: '5'
		});

		//Reposition because getCoordinate() does not work so well for Safari.
		var SB = CorbisUI.DomCache.get('SearchBuddy');
		$('createLightboxModalPopupWindow').setStyles({
			top: SB.offsetTop + window.getScroll().y + 60,
			left: SB.offsetLeft + window.getScroll().x + 5
		});

		var clmpw = $('createLightboxModalPopup');
		//Use cancel button ID to retrieve the cancel button . See Bug 17818
		var group = new Hash({
            'mo': $('modalOverlay'),
            'close': clmpw.getElement('div.ModalTitleBar input.Close'),
            'cancel': $(CorbisUI.GlobalVars.CreateLightbox.cancelButtonID)
        });

        closeLightboxEvent = CloseCreateLightbox.bindWithEvent(clmpw, group);
            
        group.each(function(value,key,hash){
            hash.get(key).addEvent('click',closeLightboxEvent);
        });            		
            
		ResizeModal('createLightboxModalPopup');
		setTimeout('$(CorbisUI.GlobalVars.CreateLightbox.newLightboxName).focus();$(CorbisUI.GlobalVars.CreateLightbox.newLightboxName).select();', 500);            
	}
}

function CloseCreateLightbox(e, grp)
{
    var validationSummary = this.getElement('.ValidationSummary');
    if (validationSummary != null) {
        validationSummary.setStyle('display', 'none');
    }

    var newNameField = this.getElement('input[type=text]');
    newNameField.value = '';
    newNameField.setStyle('color', '#333333');

    grp.each(function(value, key, hash) {
        hash.get(key).removeEvent('click', closeLightboxEvent);
    });
    grp = $lambda(false);    
}

function createLightbox_success(){
    //console.log('CALLING: createLightbox_success');
    if(CorbisUI.Handlers.Lightbox.corbisIdToAdd)
    {
        CorbisUI.Handlers.Lightbox.addTo(CorbisUI.Handlers.Lightbox.corbisIdToAdd);
        CorbisUI.DomCache.get('lightboxProgress').setStyle('display', 'none');
        CorbisUI.Handlers.Lightbox.corbisIdToAdd = null;
    }
    
    CorbisUI.DomCache.get(['LBXContainer', 'SBBX_lightboxes'], true);
}

function confirmItemAdded(link)//icon_cart_selected
{
    new CorbisUI.Popup('addToCartConfirm', { 
        createFromHTML: true,
        showModalBackground: false,
        centerOverElement: link,
        closeOnLoseFocus: true,
        positionVert: 'top', 
        positionHoriz: 'center',
        replaceText: []
    });
    return false;
}

function OpenAmbiguousModal(element)
{
    new CorbisUI.Popup('ambiguousModal');
    setGlassButtonDisabled(CorbisUI.GlobalVars.SearchResults.clarificationUpdate, true);
    ResizeModal('ambiguousModal');  
}

function applyZeroResultsStyles() {
    CorbisUI.DomCache.get('FooterContent').addClass('zeroResults');
    CorbisUI.DomCache.get('SearchBuddy').addClass('zeroResultsBuddy');
}
        
function updateClarificationCount(isChecked)
{
    (isChecked) ? _clarifyCheckCount++ : _clarifyCheckCount--;
    setGlassButtonDisabled(CorbisUI.GlobalVars.SearchResults.clarificationUpdate, _clarifyCheckCount < 1);
}

function getClarifactionChecked(method)
{
    var base = $('ambiguousModal');
    var clarificationGroups = base.getElements('.Clarification');
    var clarificationString = '';

    clarificationGroups.each(function(el) {
        clarificationString += ',';

        el.getElements('.checkboxWrap').each(function(itemEl) {
            var cbx = itemEl.getElement('input[type=checkbox]');
            (cbx.checked) ? cbx.value = 1 : cbx.value = 0;
            clarificationString += cbx.value;
        });
    });
    

    clarificationString = clarificationString.substring(1);
    var queryFlags = $(CorbisUI.GlobalVars.SearchResults.clarificationQueryFlags);
    queryFlags.value = clarificationString;
    if (method == "cancel") {
        HideModal('ambiguousModal');
    } else {
        MochaUI.CloseModal('ambiguousModal');
        //CorbisUI.ExtendedSearch.validateSearch();
        return clarificationString;
    }
    
    
}
function SuggestedKeySearch(SearchUrl) {
    if (SearchUrl != "") {
        CorbisUI.ExtendedSearch.vars._isSearching = true;
        CorbisUI.ExtendedSearch.ShowSearchProgIndicator();

        LogOmnitureEvent('event44');
        location.href = SearchUrl;
    }
}


//End: /SearchOld/Search.js
//Begin: /SearchOld/SearchBuddy.js


/****************************************************
	Corbis Javascript namespace
	
	Search Buddy
	
	=============================================
		Chris Esler, 2008-04-25
	=============================================
****************************************************/

/***************************
    GLOBAL VARIABLES
****************************/
var Floater;

/***************************
    NAMESPACES
****************************/
if (typeof(CorbisUI) == 'undefined') {
    CorbisUI = {};
}

/***************************
    SEARCH BUDDY
****************************/
CorbisUI.SearchBuddy = {
    init: new Class({

        tabs: null,
        buddy: null,

        activeWindow: null,
        activeTab: null,

        initialize: function() {
            //console.log('CorbisUI.SearchBuddy INIT');
            this.buddy = CorbisUI.DomCache.get('SearchBuddy');
            this.tabs = new Hash({});


            var tabItems = this.buddy.getElement('ul.SB_tabs').getChildren();
            //console.log($type(this.tabs));

            tabItems.each(function(el) {
                var id = el.get('id');
                id = id.substr(id.indexOf('SBT_'));
                id = id.replace('SBT_', '');
                //console.log($type(this.tabs));
                switch (id) {
                    case "filters":
                    case "lightboxes":
                    case "quickpic":
                    case "subscriptions":
                        this.tabs.set(id, new CorbisUI.SearchBuddy.tab(el, this));
                        break;
                }
            }, this);
            CorbisUI.SearchBuddy.activateTab = this.activateTab.bind(this);
        },
        // we can active any tab here
        activateTab: function(tabName) {
            if (this.activeTab != tabName) {
                this.tabs.each(function(item) {
                    if (item.name == tabName) item.el.fireEvent('click');
                });
            }
        }

    }),

    // placeholder for alias
    activateTab: null,

    fireLightboxEvent: function(ele) {
        var el = $(ele).getParent().getParent().getParent();

        var lbId = el.get('id').replace('cartBlock_', 'LBX_');
        //el.setStyle('border','1px solid red');

        // check to see if lbx item exists already
        if (!$(lbId)) {
            var lbItem = el.getElement('div.thumbWrap').getFirst().getFirst().getFirst().clone().removeProperties('title', 'class');
            lbItem.setProperty('id', lbId).setStyles({
                'float': 'left',
                'clear': 'both',
                'margin': 4
            })

            var lb = CorbisUI.SearchBuddy.init.tabs.get('lightboxes');

            lb.el.fireEvent('click');
            lb.panel.getElement('div.LBXContainer').grab(lbItem, 'top');
        }
    },

    tab: new Class({
        name: null,
        el: null,
        buddy: null,
        panel: null,
        dataLoaded: false,
        initialize: function(el, buddy) {
            this.el = el;
            this.name = el.get('id').substr(el.get('id').indexOf('SBT_') + 4);
            this.buddy = buddy;
            this.panel = CorbisUI.DomCache.get('SBBX_' + this.name);
            this.el.addEvent('click', this.clickEvent.bindWithEvent(this));
            if (this.el.hasClass('SBT_' + this.name + '_ON')) {
                this.buddy.activeTab = this.name;
            }
        },

        clickEvent: function() {

            // In case DOM loaded and element clicked before base JS finished processing

            if (!Corbis.Web.UI.SearchOld) {
                setTimeout('CorbisUI.SearchBuddy.init.tabs[CorbisUI.SearchBuddy.init.activeTab].clickEvent();', 1000);
                return;
            };

            //comment out "if" block for bug 15955, based on the spec        
            //            if (CorbisUI.Auth.GetSignInLevel() < 1 && this.name == 'lightboxes') {

            //                //CorbisUI.Auth.Check(1, CorbisUI.Auth.ActionTypes.Execute, "CorbisUI.CookieEvents.addCookieEvent(function(){CorbisUI.SearchBuddy.activateTab('lightboxes');}); window.location.reload();");
            //            }
            //            else

            //alert('clicked tab :' + this.name);
            //alert(this.buddy.tabs.getKeys());
            if (this.buddy.activeTab != this.name) {
                var active = this.buddy.tabs.get(this.buddy.activeTab);
                active.el.removeClass('SBT_' + this.buddy.activeTab + '_ON');
                active.panel.addClass('hdn');
                this.buddy.activeTab = this.name;
                this.el.addClass('SBT_' + this.name + '_ON');
                this.panel.removeClass('hdn');
                if (this.name == 'lightboxes' && !this.dataLoaded) {
                    if (CorbisUI.GlobalVars.SearchResults.isAnonymous) {
                        $('lightboxProgress').setStyle('display', 'none');
                        CorbisUI.DomCache.get('LBXContainer').getElement('.centerMe').setStyle('display', 'block');

                    }
                    else {
                        //console.log('CALLING: CorbisUI.SearchBuddy.tab.clickEvent IS LIGHTBOX');
                        // set dataLoaded first to block the second call 
                        this.dataLoaded = true;
                        //handle data load
                        // 1 grab lightboxId
                        //var lightboxDropdown = this.getElement('select[name$=lightboxList]');
                        // 2 call web service
                        //var lightboxId = lightboxDropdown.getSelected();

                        var selectedList = CorbisUI.DomCache.get('SBBX_lightboxes', true).getElement('select.lightboxList');
                        if (selectedList != null && selectedList.getSelected()[0] != null) {

                            var selectedIndex = selectedList.selectedIndex;
                            var lightboxId = selectedList.options[selectedIndex].value;

                            //console.log('GET LIGHBOX: '+lightboxId);
                            // 3 return handling
                            //Corbis.Web.UI.SearchOld.SearchScriptService.GetLightBoxItems(lightboxId, this.getLightboxItemsCallback.bind(this));
                            // 4 lightbox items display

                            // LAUNCH the getLightboxItems handler
                            CorbisUI.Handlers.Lightbox.getLightboxItems(lightboxId);
                        }
                    }
                }
                if (this.name == 'subscriptions' && !this.dataLoaded) {
                    this.dataLoaded = true;
                    CorbisUI.Handlers.Subscription.getSubscriptionItems();

                }
            }
        }

    }),

    /* SEARCH BUDDY FLOATER */
    floater: new Class({

        box: null,
        boxOffsetHeight: null,
        wrap: null,
        footer: null,
        progressContainer: null,
        progressLoader: null,

        initialize: function(el, wrap, footer, progressContainer) {

            //alert('NORMAL BUDDY');
            this.box = el;
            this.wrap = wrap;
            this.footer = footer;
            this.progressContainer = progressContainer;
            var wC = this.wrap.getCoordinates();



            this.box.setStyles({
                'top': wC.top + 10
            });

            this.boxOffsetHeight = this.box.offsetHeight;
            
            this.wC = {
                top: wC.top,
                bottom: wC.top + wC.height
            };

            // add window events
            window.addEvent('scroll', this.windowScroll.bindWithEvent(this));
            window.addEvent('resize', this.windowScroll.bindWithEvent(this));

            // run the Scroll for the first time
            // fixes problem of coming back to a page
            // and the buddy is messed up
            this.windowScroll();
        },

        windowScroll: function() {
            //Close create lightbox popup so we don't have to reposition it.
            HideModal('createLightboxModalPopup');

            // WINDOW SCROLL
            var wScroll = window.getScroll();
            //console.log('WINDOW SCROLL: '+wScroll.toSource());

            // WRAP POSITION
            var pos = this.wrap.getPosition();

            // WRAP COORDS
            var wrapC = this.wrap.getCoordinates();

            // FOOTER COORDINATES
            var fC = this.footer.getCoordinates();

            // WINDOW COORDINATES
            var wiC = window.getCoordinates();

            // Magical powers detect the SCROLL-X
            (wScroll.x > 0) ? this.box.setStyle('left', '-' + wScroll.x + 'px') : this.box.setStyle('left', 0);

            // Magical powers detect the SCROLL-Y

            // if global nav still visible
            if (wScroll.y < this.wC.top) {
                this.box.setStyle('top', (pos.y - wScroll.y) + 10);
            } else {
                // if footer is visible
                if ((wScroll.y + wiC.height) > fC.top) {
                    // if footer is visible and buddyheight > screenheight, means buddy is overlapping footer
                    // pull up and add some constant(10 here) to show padding effect
                    if (this.boxOffsetHeight > wiC.height) {
                        this.box.setStyle('top', fC.top - (wScroll.y + wiC.height) - (this.boxOffsetHeight - wiC.height) - 10);
                    }
                    else {
                        this.box.setStyle('top', fC.top - (wScroll.y + wiC.height));
                    }
                    // if footer is not visible
                } else {
                    if (this.box.getStyle('top').toInt() != 10) this.box.setStyle('top', 10);
                }
            }

            // detect distance from top of footer

            // get value for footer distance check
            var fCheck = fC.top - wiC.height;

            // if footer visible
            if (wScroll.y > fCheck) {
                this.box.setStyle('bottom', (wiC.height - (fC.top - wScroll.y)) + 10);
                // if footer is not visible
            } else {
                if (this.box.getStyle('bottom').toInt() != -50) this.box.setStyle('bottom', 10);
            }

            var browser = navigator.appName; // detect IE6 & IE7
            var b_version = navigator.appVersion;
            var version = parseFloat(b_version);


            if ((browser == "Microsoft Internet Explorer") && (version <= 7)) {
                var lbxContainerHeight;  // this is for IE only
                var distance = 160;
                var fixMe = 0;
                if (wScroll.y > fCheck) distance = 155;

                lbxContainerHeight = this.box.getStyle('height').toInt() - distance;
                CorbisUI.DomCache.get('LBXContainer').setStyle('height', lbxContainerHeight);

            }



        }

    }),

    /* IE6 gets its own flaoter because IE6 
    stupidly handles browser coordinate 
    values differently 
    */
    floater_ieSIX: new Class({

        box: null,
        wrap: null,
        footer: null,
        progressContainer: null,
        progressLoader: null,

        initialize: function(el, wrap, footer, progressContainer) {
            //alert('IE6 BUDDY');
            this.box = el;
            this.wrap = wrap;
            this.footer = footer;
            this.progressContainer = progressContainer;
            var wC = this.wrap.getCoordinates();

            this.box.getElement('div.inSearchBuddy').setStyle('position', 'relative');

            this.box.setStyles({
                'margin-top': 10
            });

            //alert(this.box.getCoordinates().height);
            this.box.setStyle('position', 'absolute');
            this.box.setStyle('display', 'block');
            //this.box.setStyle('border', '1px solid cyan');
            //this.wrap.setStyle('border', '1px solid purple');


            // get FILTERS panel
            this.SBBXF = this.box.getElement('div.SBBX_filters');
            // if (this.SBBXF) this.SBBXF.setStyle('border', '1px solid green');

            // get LIGHTBOX panel
            this.SBBXL = this.box.getElement('div.SBBX_lightboxes');
            //this.SBBXL.setStyle('border', '1px solid green');

            // get SUBSCRIPTION panel
            this.SBBXS = this.box.getElement('div.SBBX_subscriptions');

            // get QUICKPIC panel
            this.SBBXQ = this.box.getElement('div.SBBX_quickpic');
            if (this.SBBXQ) {
                //this.SBBXQ.setStyle('border', '1px solid green');
                // fetch QUICKPIC items container
                // have to fetch this each time since it might be updated by an update panel
                var QPC = this.box.getElement('div.quickPicsContainer');
                QPC.setStyle('overflow', 'scroll');
            }

            // get container of the actual lightbox items
            // have to fetch this each time since it might be updated by an update panel
            var LBXC = this.box.getElement('div.LBXContainer');
            LBXC.setStyle('overflow', 'scroll');
            //LBXC.setStyle('border', '1px solid magenta');
            //LBXC.setStyle('position', 'relative');

            var boxHeight = window.getCoordinates().height - this.wrap.getCoordinates().top;
            //this.el.setStyle('height', boxHeight);
            this.box.setStyle('height', boxHeight);
            this.SBBXL.setStyle('height', boxHeight);
            if (this.SBBXF) this.SBBXF.setStyle('height', boxHeight + 200);
            if (this.SBBXQ) this.SBBXQ.setStyle('height', boxHeight);


            LBXC.setStyle('height', boxHeight - (LBXC.getCoordinates(this.box).top));
            if (this.SBBXQ) QPC.setStyle('height', boxHeight - (LBXC.getCoordinates(this.box).top));

            //LBXC.setStyle('height', boxHeight - 100 );

            //var wScroll = window.getScrollSize();
            //alert(window.getCoordinates().height - this.wrap.getCoordinates().top);

            //alert(this.box.id);




            this.wC = {
                top: wC.top,
                bottom: wC.top + wC.height
            };

            // add window events
            window.addEvent('scroll', this.windowScroll.bindWithEvent(this));
            window.addEvent('resize', this.windowScroll.bindWithEvent(this));

            // run the Scroll for the first time
            // fixes problem of coming back to a page
            // and the buddy is messed up
            this.windowScroll();
        },

        windowScroll: function() {
            //Close create lightbox popup so we don't have to reposition it.
            HideModal('createLightboxModalPopup');

            // have to fetch this each time since it might be updated by an update panel
            var LBXC = this.box.getElement('div.LBXContainer');

            // WINDOW SCROLL
            var wScroll = window.getScroll();
            //console.log('WINDOW SCROLL: '+wScroll.toSource());

            // WRAP POSITION
            var pos = this.wrap.getPosition();

            // WRAP COORDS
            var wrapC = this.wrap.getCoordinates();

            // FOOTER COORDINATES
            var fC = this.footer.getCoordinates();

            // WINDOW COORDINATES
            var wiC = window.getCoordinates();

            // Magical powers detect the SCROLL-X
            (wScroll.x > 0) ? this.box.setStyle('left', '-' + wScroll.x + 'px') : this.box.setStyle('left', 0);

            // Magical powers detect the SCROLL-Y

            // if global nav still visible
            //alert(wScroll.y + " : " + this.wC.top);
            if (wScroll.y < this.wC.top) {
                //alert('gnav visible');
                var boxHeight = 0; 
                this.box.setStyles({
                    'margin-top': 10
                });
                boxHeight = (wiC.height - (wrapC.top - wScroll.y)) + 20;
                if (boxHeight >= 0) {
                    this.box.setStyle('height', boxHeight);
                }

                boxHeight = wiC.height - (wrapC.top - wScroll.y);
                if (boxHeight >= 0) {
                    this.SBBXL.setStyle('height', boxHeight);
                }

                boxHeight = boxHeight - (LBXC.getCoordinates(this.box).top);
                if (boxHeight >= 0) {
                    LBXC.setStyle('height', boxHeight);
                }

            } else {
                // if footer is visible
                if ((wScroll.y + wiC.height) > fC.top) {
                    //alert('footer visible');
                    //this.box.setStyle('margin-top', (fC.top - wScroll.y) - wiC.height);
                    // if footer is not visible
                } else {
                    //alert('no gnav no footer visible');
                    //if (this.box.getStyle('margin-top').toInt() != 10) {
                    //alert(wiC.top);
                    this.box.setStyles({
                        'margin-top': ((wScroll.y - wrapC.top) + 10),
                        'height': wiC.height - 10
                    });
                    var boxHeight = wiC.height - 10
                    //alert(boxHeight + " : " + (boxHeight + 50));
                    this.SBBXL.setStyle('height', boxHeight + 60);
                    LBXC.setStyle('height', boxHeight + 30);
                    //}
                }
            }

            // detect distance from top of footer

            // get value for footer distance check
            var fCheck = fC.top - wiC.height;

            // if footer visible
            if (wScroll.y > fCheck) {
                this.box.setStyle('bottom', (wiC.height - (fC.top - wScroll.y)) + 10);
                // if footer is not visible
            } else {
                if (this.box.getStyle('bottom').toInt() != -50) this.box.setStyle('bottom', 10);
            }

            var browser = navigator.appName; // detect IE6 & IE7
            var b_version = navigator.appVersion;
            var version = parseFloat(b_version);

            //alert('ping!');

            if ((browser == "Microsoft Internet Explorer") && (version <= 7)) {
                var lbxContainerHeight;  // this is for IE only
                var distance = 160;
                var fixMe = 0;
                if (wScroll.y > fCheck) distance = 155;

                //alert(this.box.getCoordinates().top);
                lbxContainerHeight = this.box.getStyle('height').toInt() - distance;

                // THERE IS A PROBLEM HERE WITH IE6
                var container = CorbisUI.DomCache.get('LBXContainer', true);
                //alert(lbxContainerHeight);
                if (lbxContainerHeight > 0)
                    CorbisUI.DomCache.get('LBXContainer', true).setStyle('height', lbxContainerHeight + "px");
            }


        }

    }),

    getValidateAlertPosition: function(el) {
        var coords = $(el).getCoordinates();
        var filterErrorHeight = CorbisUI.DomCache.get('filterErrorWindow').getCoordinates().height;
        var scroll = $(document.body).getScroll();
        var position = coords.top + scroll.y - filterErrorHeight + 75;

        if (Browser.Engine.webkit) position = position - 182;  //bug 13674, safari bug


        if (position < scroll.y) position = scroll.y + 5;

        return position;
    },


    validateCheckBoxes: function() {
        CorbisUI.DomCache.get('filterErrorCategories').setStyle('display', 'none');
        CorbisUI.DomCache.get('filterErrorColor').setStyle('display', 'none');
        CorbisUI.DomCache.get('filterErrorPhotography').setStyle('display', 'none');
        CorbisUI.DomCache.get('filterErrorRMRF').setStyle('display', 'none');

        // Validate checkboxes to see what to return
        // Case 1: No Creative, no editorial boxes checked
        if (!CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.creative).getCheckedState() && !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.editorial).getCheckedState()) {
            CorbisUI.DomCache.get('filterErrorCategories').setStyle('display', 'block');
            new CorbisUI.Popup('filterError', { showModalBackground: false, closeOnLoseFocus: true });
            ResizeModal('filterError');
            CorbisUI.DomCache.get('filterErrorWindow').setStyles({
                "left": 185,
                "top": this.getValidateAlertPosition(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.editorial)
            });
            return false;
        }
        //        if (!CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rmLicense).getCheckedState() && !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rfLicense).getCheckedState()) {
        //            CorbisUI.DomCache.get('filterErrorRMRF').setStyle('display', 'block');
        //            new CorbisUI.Popup('filterError', { showModalBackground: false, closeOnLoseFocus: true });
        //            ResizeModal('filterError');
        //            CorbisUI.DomCache.get('filterErrorWindow').setStyles({
        //                "left": 185,
        //                "top": this.getValidateAlertPosition(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.rmLicense)
        //            });
        //            return false;
        //        }
        if (!CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.photography).getCheckedState() && !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.illustration).getCheckedState()) {
            CorbisUI.DomCache.get('filterErrorPhotography').setStyle('display', 'block');
            new CorbisUI.Popup('filterError', { showModalBackground: false, closeOnLoseFocus: true });
            ResizeModal('filterError');
            CorbisUI.DomCache.get('filterErrorWindow').setStyles({
                "left": 185,
                "top": this.getValidateAlertPosition(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.photography)
            });
            return false;
        }
        if (!CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.color).getCheckedState() && !CorbisUI.ImageCb.getImageCbObject(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.blackWhite).getCheckedState()) {
            CorbisUI.DomCache.get('filterErrorColor').setStyle('display', 'block');
            new CorbisUI.Popup('filterError', { showModalBackground: false, closeOnLoseFocus: true });
            ResizeModal('filterError');
            CorbisUI.DomCache.get('filterErrorWindow').setStyles({
                "left": 185,
                "top": this.getValidateAlertPosition(CorbisUI.GlobalVars.SearchResults.checkBoxIDS.color)
            });
            return false;
        }
        return true;
    },

    lightboxLogin: function() {
        CorbisUI.Auth.Check(1, 'execute', 'CorbisUI.SearchBuddy.lightboxLogin_cookieEvent()');
    },

    lightboxLogin_cookieEvent: function() {
        CorbisUI.CookieEvents.addCookieEvent(function() {
            setTimeout("CorbisUI.SearchBuddy.activateTab('lightboxes')", 500);
        }, {});
        window.location.reload();
    }

};
	
/***************************
    WINDOW DOM READY
****************************/

CorbisUI.addQueueItem('domReady', 'searchBuddySetup', function() {
    // setup search buddy
    CorbisUI.SearchBuddy.init = new CorbisUI.SearchBuddy.init();

    // initialize search buddy
    // buddy version is for IE6 compatibility
    var buddyVersion = (Browser.Engine.trident4) ? 'floater_ieSIX' : 'floater';
    Floater = new CorbisUI.SearchBuddy[buddyVersion](CorbisUI.DomCache.get('SearchBuddy'), CorbisUI.DomCache.get('contentBar'), CorbisUI.DomCache.get('FooterContent'));
});


//End: /SearchOld/SearchBuddy.js
//Begin: /Checkout/AddToCart.js

/******************************
    CORBIS ADD TO CART
*******************************/

/***************************
    NAMESPACES
****************************/
if (typeof(CorbisUI) == 'undefined') {
	CorbisUI = {};
}
CorbisUI.Cart = {};
var addToCartVar = null;
CorbisUI.Cart.AddToCartInst = function() {
    if (!addToCartVar) {
        addToCartVar = new CorbisUI.Cart.AddToCart();
    }
    return addToCartVar;
}
CorbisUI.Cart.AddToCart = new Class({
    context: null,
    offeringUid: null,
    onSuccess: $empty,

    initialize: function(offeringUid) {
        this.offeringUid = offeringUid;
        Corbis.Web.UI.Checkout.CartScriptService.set_defaultUserContext(this);
    },
    addRFCDToCart: function(el) {
        
        if (!CorbisUI.Pricing.IsAuthenticated(el.id)) {
            return false;
        }
        return true;
    },
    addOfferingToCart: function() {
        LogOmnitureEvent("scAdd");
        Corbis.Web.UI.Checkout.CartScriptService.AddOfferingToCart(this.offeringUid, this.addOfferingToCartSuccess, this.methodFailed);
    },

    addProductToCart: function(corbisId, productUid) {
        LogOmnitureEvent("scAdd");
        Corbis.Web.UI.Checkout.CartScriptService.AddProductToCart(corbisId, productUid, this.addOfferingToCartSuccess, this.methodFailed);
    },
    displaySuccessDialog: function(context) {
        var options = {
            createFromHTML: false,
            showModalBackground: false,
            closeOnLoseFocus: true,
            positionVert: 'top',
            positionHoriz: -250
        };

        if (context && $type(context.CT) == 'element') {
            options.centerOverElement = context.CT;
        }

        new CorbisUI.Popup('addToCartConfirm', options);
        
        $('addToCartConfirmWindow').getElement('input.Close').setStyle('visibility', 'visible');
    },
    addOfferingToCartSuccess: function(results, context, methodName) {
        if (results > 0) {
            context.onSuccess(results);
            //CorbisUI.Cart.AddToCartInst().displaySuccessDialog(context.context); for bug 15191
        }
        else {
            //TODO: Open login popup.
        }
    },

    methodFailed: function(results, context, methodName) {
        //console.log(results);
        //TODO: use mochaUI for alert window
        alert(results.get_message());
    }
});    


//End: /Checkout/AddToCart.js
CorbisUI.debug = true;