// vim: set tabstop=4 shiftwidth=4 foldmethod=marker expandtab :
/**
 * Handle the card selector.
 *
 * @requires onload.js for binding to objects after loading.
 * @requires utils.js for calculating the pagination information
 * @provides PlxEcardTplSelectUI global variable that manages card selection UI
 * @todo deal with relative image placement
 */

var doTooltip = false;
var PlxEcardTplSelectUI = {
    // =============  CONSTANTS  =============

    _ID_BREADCRUMB_NAV: 'breadcrumbs_nav',
    _ID_CATEGORY_NAV: 'metadata_navigation',
    _ID_THUMBNAILS: 'thumbnail_list',
    _ID_PAGINATION_NAV: 'pagination_navigation',
    _ID_SIGNIN: 'signin_box',
    _ID_YOUR_PHOTO: 'your_photo',
    _ID_YOUR_PHOTO_AHREF: 'your_photo_ahref',
    _ID_MORE_CARDS: 'more_cards',
    _ID_HEADER:'theme_header',
    _filterText:'', //in order to handle things localized by filter

    _NUM_PAGINATION_SPAN: 5,
    _NUM_PAGINATION_END_SPAN: 2,
    _NUM_PAGE_SIZE_MINIMUM: 10,

    _html_your_photo: '',
    //_CONTENT_YOUR_PHOTO_MIDDLE: '" title="Add Your Photo"><img class="your_photo" alt="This could be you! Click here to add your own photo." src="m/im/tpl/ecard/add_your_photo.gif" /></a></td></tr></table><div class="title"><a href="customize.php?imgId=-1&filters=',
    //_CONTENT_YOUR_PHOTO_END: '" title="Add Your Photo">Add Your Photo</a></div></div>',
    //_CONTENT_YOUR_PHOTO_START: '<div id="your_photo" class="thumbnail"><table class="thumb_img"><tr><td><a id="your_photo_ahref" href="customize.php?imgId=-1&filters=',
    //_CONTENT_YOUR_PHOTO_MIDDLE: '" title="Add Your Photo"><img class="your_photo" alt="This could be you! Click here to add your own photo." src="m/im/tpl/ecard/add_your_photo.gif" /></a></td></tr></table>',
    //_CONTENT_YOUR_PHOTO_END: '</div>',
    _CONTENT_MORE_CARDS_START: '<div class="thumbnail"><table class="thumb_img"><tr><td><a href="#" title="More Cards" onclick="return EcardSelector.doThumbMove(',
    _CONTENT_MORE_CARDS_END: ', \'more_cards\');"><img alt="More Cards" src="m/im/tpl/ecard/more_cards.gif" class="more" /></a></td></tr></table></div>',
    _CONTENT_HEADER_START:'m/txt/en/ec_pink/',
    _CONTENT_HEADER_END:'.gif',

    _OCCASION_HEADERS: {0:'_',9:'anniversary',10:'birthdays',51:'blank',28:'congratulations',41:'easter',48:'fathers_day',42:'fourth',12:'get_well',53:'graduation',23:'halloween',26:'hanukkah',38:'kwanzaa',47:'mothers_day',13:'new_year',54:'secretaries',40:'st_patricks',16:'sympathy',43:'thanksgiving',17:'thank_you',14:'thinking',39:'valentines',15:'xmas'},

    // =============  MEMBER VARIABLES  =============

    _ad_last_updated: 0,
    _page_size: -1,
    _page_start_index: -1,
    _page_current_num: -1,
    _page_total_num_items: -1,
    _page_pagination_style: {},

    // This is actually true/false but set it to 0 because that's how we
    // are consistent for history saving...
    _mode_show_all: 0,      //"Show All" selected

    _div_crumbs: null,
    _div_navigation: null,
    _div_pagination: null,
    _div_signin: null,

    _thumbs: [], //list of thumb objects (show, html, img, src)
    _html_more_cards: '',
    // =============  CONSTRUCTOR / INITIALIZER  =============
    // {{{ - init()
    /**
     * Sets up all the internal values needed for the UI
     */
    init: function() {
        //ecdbug('init(): called');

        //this._html_your_photo = this._CONTENT_YOUR_PHOTO_START + '-1' + this._CONTENT_YOUR_PHOTO_MIDDLE + '-1' + this._CONTENT_YOUR_PHOTO_END;
        this._html_your_photo = this.yourPhotoHtml('');
        this._page_size = this.recalculatePageSize();
        this._page_start_index = 0;
        this._page_current_num = 0;
        this._page_total_num_items = 0;
        this._mode_show_all = 0;

        // Now, create references to important page objects
        // so we do not have to look them up each time.

        this._div_crumbs = getObject(this._ID_BREADCRUMB_NAV);
        this._div_navigation = getObject(this._ID_CATEGORY_NAV);
        this._div_pagination = getObject(this._ID_PAGINATION_NAV);
        this._div_signin = getObject(this._ID_SIGNIN);

        // Finally, add the "your photo" and "more" into the layout
        // (no need to call since we reset it when we call refreshFilter() which
        // is called by another onload handler.)
        this.resetThumbnailHtml();
    },
    // }}}
    // =============  PUBLIC METHODS  =============
    // {{{ - yourPhotoHtml(filters)
    /**
     * generate "Upload your own photo" HTML
     */
    yourPhotoHtml: function(filters) {
        return '<div id="your_photo" class="thumbnail"><table class="thumb_img"><tr><td><a id="your_photo_ahref" href="#" onclick="return do_customize(false, -1,\''+ escape(filters) +'\')" title="Add Your Photo"><img class="your_photo" alt="This could be you! Click here to add your own photo." src="m/txt/en/sp/ec_select/add_photo.png" /></a></td></tr></table></div>';
    },
    // }}}
    // {{{ - setPageSize(size)
    /**
     * If the size is -1, we show all
     */
    setPageSize: function(size) {
        size = parseInt(size);

        if (size != -1) {
            size = Math.max(size, this._NUM_PAGE_SIZE_MINIMUM);
        }
        //alert("Size is: " + size);

        // Do nothing when the size doesn't change
        if (this._page_size == size) { return; }


        // We hide objects if we're shrinking,
        // we show objects if we're expanding.
        if (size == -1) { //show all
            this.setShowAllMode(true);
            // Special case:  We show all items that are not on the current page
            if (this._page_start_index > 0) {
                this._showImages(0, this._page_start_index - 1);
            }
            this._showImages(this._page_start_index + this._page_size, this._page_total_num_items);
        } else if (size > this._page_size ) {
            // We must show those currently hidden.
            this._showImages(this._page_start_index + this._page_size, this._page_start_index + size - 1);
            this._page_size = size;
        } else {
            this._hideImages(this._page_start_index + size - 1, this._page_start_index + this._page_size - 1);
            this._page_size = size;
        }

        //this.refreshPaginationNavigation();
        //this.refreshThumbs();

    },
    // }}}
    // {{{ - getPageSize()
    getPageSize: function() {
        if (this.getShowAllMode()) {
            // Bug #8814 + danger of lock up.
            //return this._page_total_num_items;
            //return 1000;
            // Bug #10060: we need to treat "show all" specially to avoid interference with pagination
            return -1;
        } else {
            return this._page_size;
        }
    },
    // }}}
    // {{{ - recalculatePageSize()
    recalculatePageSize: function() {
        var winW = 0;
        var winH = 0;

        if (parseInt(navigator.appVersion)>3) {
             if (navigator.appName=="Netscape") {
              winW = window.innerWidth-16;
              winH = window.innerHeight-16;
             }
             if (navigator.appName.indexOf("Microsoft")!=-1) {
              winW = document.body.offsetWidth-20;
              winH = document.body.offsetHeight-20;
             }
        }
        if (winH<731) { winH = 731; } //make sure there are at least 4 rows vertically
        //var numFittingImages = (Math.floor((winH-127)/168)) * (Math.floor((winW-260)/171)) - 2;
        var numFittingImages = (Math.floor((winH-127)/151)) * (Math.floor((winW-260)/151)) - 2; //the -2 thing is because the add a photo and more link
        //alert("h:"+winH+"; w:"+winW+"; Fit: "+numFittingImages);

        if (numFittingImages < 1) {
            numFittingImages = 10;
        }
        return numFittingImages;
    },
    // }}}
    // {{{ - setShowAllMode(is_show_all)
    /**
     * Toggles whether or not we're showing all items
     *
     */
    setShowAllMode: function(is_show_all) {
        var end =  this._page_start_index + this._page_size;

        if (is_show_all) {
            if (this._page_start_index > 0) {
                this._showImages(0, this._page_start_index -1);
            }
            if (end < this._page_total_num_items) {
                this._showImages(end, this._page_total_num_items -1);
            }
        } else {
            // Hide any item not on this page.

            if (this._page_start_index > 0) {
                this._hideImages(0, this._page_start_index -1);
            }
            if (end < this._page_total_num_items) {
                this._hideImages(end, this._page_total_num_items - 1);
            }
        }
        this._mode_show_all = is_show_all;

        // We must show or hide accordingly
        //this.refreshThumbs();
    },
    // }}}
    // {{{ - getShowAllMode()
    getShowAllMode: function() {
        return this._mode_show_all;
    },
    // }}}
    // {{{ - setPageStartIndex(num)
    /**
     * When we change the start index, we need to hide
     * and show the appropriate images and recalculate
     * the page navigation.
     */
    setPageStartIndex: function(num) {
        //ecdbug('setPageStartIndex('+num+'): called');
        num = parseInt(num);
        // If no change, return
        if (num == this._page_start_index) { return; }


        var oldStart = this._page_start_index;
        var oldEnd = oldStart + this._page_size - 1;
        var newStart = num;
        var newEnd = newStart + this._page_size - 1;


        if (num < oldStart) {
            this._hideImages(Math.max(oldStart, newEnd), oldEnd);
            this._showImages(newStart, Math.min(oldStart, newEnd));

        } else {
            this._hideImages(oldStart, Math.min(oldEnd, newStart));
            this._showImages(Math.max(oldEnd, newStart), newEnd);
        }

        // finally, set our new start index
        this._page_start_index = num;

        //this.refreshPaginationNavigation();
        //this.refreshThumbs();
    },
    // }}}
    // {{{ - setTotalNumberOfItems(num)
    setTotalNumberOfItems: function(num) {
        num = parseInt(num);
        //alert('setting total # of items to:' + num);
        this._page_total_num_items = num;
        //this.refreshPaginationNavigation();
    },
    // }}}
    // {{{ - getNavigationDiv()
    getNavigationDiv: function() {
        return getObject(this._ID_CATEGORY_NAV);
    },
    // }}}
    // {{{ - setNavigationHtml(html)
    setNavigationHtml: function(html) {
        return ajax_inject_html(this._ID_CATEGORY_NAV, html);
    },
    // }}}
    // {{{ - getBreadcrumbDiv()
    getBreadcrumbDiv: function() {
        return getObject(this._ID_BREADCRUMB_NAV);
    },
    // }}}
    // {{{ - setBreadcrumbHtml(html)
    setBreadcrumbHtml: function(html) {
        return ajax_inject_html(this._ID_BREADCRUMB_NAV, html);
    },
    // }}}
    // {{{ - resetThumbnailHtml()
    resetThumbnailHtml: function() {
        //ecdbug('resetThumbnailHtml(): called');
        // Clear out all our tracking info
        this._thumbs = [];
        this.setMoreCardsPos(0);
        this.refreshThumbs();
    },
    // }}}
    // {{{ - getPaginationNavigationDiv()
    getPaginationNavigationDiv: function() {
        return getObject(this._ID_PAGINATION_NAV);
    },
    // }}}
    // {{{ - setPaginationNavigationHtml(html)
    setPaginationNavigationHtml: function(html) {
        return ajax_inject_html(this._ID_PAGINATION_NAV, html);
    },
    // }}}
    // - {{{ -getSignInDiv()
    getSignInDiv: function() {
        return getObject(this._ID_SIGNIN);
    },
    // }}}
    // - {{{ setSignInHtml(html)
    setSignInHtml: function(html) {
        return ajax_inject_html(this._ID_SIGNIN, html);
    },
    // }}}
    // {{{ - setMoreCardsPos(pos)
    /**
     * Create our "More Cards" div.
     */
    setMoreCardsPos: function(pos) {
        //ecdbug('setMoreCardsPos('+pos+'): called');
        if (pos >= 0) {
            this._html_more_cards = '<div id="' + this._ID_MORE_CARDS + '" style="height:156px;width:151px;display:block;">'+this._CONTENT_MORE_CARDS_START + pos + this._CONTENT_MORE_CARDS_END+'</div>';
        } else {
            this._html_more_cards = '';
        }
    },
    // }}}
    // {{{ - addImage(index,imageUrl,imageAlt,imageId,isFree,filterId,filters)
    addImage: function(index,imageUrl,imageAlt,imageId,isFree,filterId,filters) {
        var free_text = (isFree) ? 'true' : 'false';
        var html = '<div id="thumbnail_div_"'+index+'" class="thumbnail">'
        var click_action = 'do_customize(' + free_text + ',' + imageId + ',\'' + filters + '\');'
        html += '<table class="thumb_img"><tr><td><a href="#" onclick="return '+ click_action + '" title="Select this eCard"><img onmouseover="if (show_mag) {return show_mag(event,this, \'' + imageId + '\', \'' + escape(click_action) + '\');}" onmouseout="if (hide_mag) {return hide_mag(event);}" alt="'+imageAlt+'" src="'+imageUrl+'" /></a></tr></td></table>';
        html += '</div>';
        //html += '<table class="thumb_img"><tr><td><a href="'+ targetUrl +'" title="Select this eCard" onmouseover="doTooltip(event,'+imageId+','+filterId+');" onmouseout="hideTip();"><img alt="'+imageAlt+'" src="'+imageUrl+'" /></a></tr></td></table>';
        //html += '<div class="title"><a href="'+targetUrl+'" title="Select this eCard">'+imageAlt+'</a></div>';
        //html += '<table class="thumb_img"><tr><td><a href="dyn/ttsamp/'+imageId+'.jpeg" rel="lightbox" selectLink="' + targetUrl + '" title="'+imageAlt+'"><img alt="'+imageAlt+'" src="'+imageUrl+'" /></a></tr></td></table><div class="title"><a href="dyn/ttsamp/'+imageId+'.jpeg" rel="lightbox" selectLink="' + targetUrl + '" title="'+imageAlt+'">'+imageAlt+'</a></div></div>';
        var obj = {
            show:1,
            html:html,
            img:new Image(),
            src:imageUrl
        };
        this._thumbs[index] = obj;
    },
    // }}}
    // {{{ - setHeader(filters)
    setHeader: function(filters) {
        //ecdbug('setHeader('+filters+')');
        if (!getObject(this._ID_HEADER)) { return; }

        for (var idx=0; idx<filters.length; ++idx) {
            var name = this._OCCASION_HEADERS[filters[idx]];
            if (name) {
                //ecdbug('setHeader(): img='+this._CONTENT_HEADER_START + name + this._CONTENT_HEADER_END);
                getObject(this._ID_HEADER).src = this._CONTENT_HEADER_START + name + this._CONTENT_HEADER_END;
                // Bug #8843
                return;
            }
        }
        getObject(this._ID_HEADER).src = this._CONTENT_HEADER_START + this._OCCASION_HEADERS[0] + this._CONTENT_HEADER_END;
    },
    // }}}
    // {{{ - setAddPhotoFilters(filters)
    setAddPhotoFilters: function(filters) {
        this._filterText = filters;
        //this._html_your_photo = this._CONTENT_YOUR_PHOTO_START + escape(filters) + this._CONTENT_YOUR_PHOTO_MIDDLE + escape(filters) + this._CONTENT_YOUR_PHOTO_END;
        //this._html_your_photo = this._CONTENT_YOUR_PHOTO_START + escape(filters) + this._CONTENT_YOUR_PHOTO_MIDDLE + this._CONTENT_YOUR_PHOTO_END;
        this._html_your_photo = this.yourPhotoHtml(filters);

        var yp = getObject(this._ID_YOUR_PHOTO);
        yp = getObject(this._ID_YOUR_PHOTO);
        if (yp) {
            yp.innerHTML = this._html_your_photo;
            pngfix();
        }
    },
    // }}}
    // =============  PRIVATE INTERNAL DATA MANAGEMENT FUNCTIONS  =============
    // {{{ - _hideImages(start,end)
    _hideImages: function(start, end) {
        return this._change_image_display(start, end, false);
    },
    // }}}
    // {{{ - _showImages(start,end)
    _showImages: function(start, end) {
        return this._change_image_display(start, end, true);
    },
    // }}}
    // {{{ - _change_image_display(start, end, shouldShow)
    _change_image_display: function(start, end, shouldShow) {
        if (start > end) { return; }
        if (start < 0) { start = 0; }
        if (end < 0) { end = 0; }

        for (var i=start; i <= end; i++) {
            if (this._thumbs[i]) {
                //alert(displayStyle +" #"+i);
                this._thumbs[i].show = shouldShow;
            }
        }
    },
    // }}}
    // {{{ - refreshThumbs()
    refreshThumbs: function() {
        //ecdbug('refreshThumbs(): called');
        var images = new Array();
        var count = 0;
        var total = 0;
        var rendered_count = -1;
        var obj = this;

        var html = obj._html_your_photo;
        for (var i=0; i<this._thumbs.length; ++i) {
            if (this._thumbs[i] && this._thumbs[i].show) {
                html += obj._thumbs[i].html;
            }
        }
        html += obj._html_more_cards;
        setInnerHtml(obj._ID_THUMBNAILS, html);
        pngfix(); //add a photo png
        //initLightbox();
    },
    // }}}
    // {{{ - updateTheme(currentFilters)
    updateTheme: function(currentFilters, filters_json, changeAd) {
      // TODO: This is the default theme.
      if (currentFilters && (currentFilters.length === 0)) {
         // Blank Cards --> if blank cards gets something other than the default
         // theme, this will have to be changed.
        currentFilters = [51];
      }
      
      //console.debug("updateTheme called -- currentFilters: "+dojo.toJson(currentFilters) + ", json: "+dojo.toJson(filters_json));
      // See if any of the current filters matches
      if (!currentFilters || currentFilters.length <= 0) { return; }
      var i = 0;
      var themeInfo = {};
      
      for (; i < currentFilters.length; i++) {
        //console.debug("i: " + i);
        if (filters_json[currentFilters[i]]) {
          // Change the elements on the page to match the theme
          // Put in an optimization to know that default theme
          // is set so we don't change it every time

          themeInfo = filters_json[currentFilters[i]];
          //console.debug("themeInfo: " + dojo.toJson(themeInfo));
          if (themeInfo.browser) {
            //console.debug("theme.browser exists");
            var b = themeInfo.browser;
            if (b.page) {
              //console.debug("browser.page exists");
              var p = b.page;
              var bodyNode = document.getElementById("page_body");
              var pageBox = document.getElementById("page_box");
              
              if (bodyNode && pageBox && p.background_color) {
                //console.debug("bodyNode getting set to :"+p.background_color);
                bodyNode.style.backgroundColor = p.background_color;
                pageBox.style.backgroundColor = p.background_color;
              }
              
              if (p.border_color) {
                var borderBottom = document.getElementById("browser_page_border_color_bottom");
                if (borderBottom) { borderBottom.style.backgroundColor = p.border_color; }
              }
              
//              if (p.footer_style) {
//                var footerStyle = document.getElementById("browser_page_footer_style");
//                if (footerStyle) {
//                  //footerStyle.setAttribute("style",  p.footer_style);
//                  // MUST DO IT THIS WAY FOR IE!
//                  footerStyle.style.cssText = p.footer_style;
//                }
//              }
              
            }
            
            if (b.heading) {
              var h = b.heading;
              
              if (h.background_color) {
                var headingTd = document.getElementById("browser_heading_td");
                if (headingTd) {
                  headingTd.style.backgroundColor = h.background_color;
                  if (h.image_height) {
                    headingTd.style.height = h.image_height + 'px';
                  }
                }
              }
           
              var headingImageDiv = document.getElementById("browser_heading_image");
              if (headingImageDiv && h.image) {
                headingImageDiv.style.backgroundImage = 'url('+h.image+')';
              }
              if (headingImageDiv && h.image_height) {
                headingImageDiv.style.height = h.image_height+"px";
              }
              
              if (h.links_style) {
                var headingLinks = document.getElementById("browser_heading_links");
                if (headingLinks) {
                  //headingLinks.setAttribute("style", h.links_style);
                  headingLinks.style.cssText = h.links_style;
                  
                  // for every child, apply the style
//                  var i=0;
//                  for (i = 0; i < headingLinks.childNodes.length; i++) {
//                    var c = headingLinks.childNodes[i];
//                    c.style.cssText = h.links_style;
//                  }
                  
                }
                
                var headingActivateText = document.getElementById("browser_heading_text_activate");
                if (headingActivateText) {
                  //headingActivateText.setAttribute("style", h.links_style);
                  headingActivateText.style.cssText = h.links_style;
                }

                var headingHelpText = document.getElementById("browser_heading_text_help");
                if (headingHelpText) {
                  //headingHelpText.setAttribute("style", h.links_style);
                  headingHelpText.style.cssText = h.links_style;
                }

                var headingPulseText = document.getElementById("browser_heading_text_pulse");
                if (headingPulseText) {
                  headingPulseText.style.cssText = h.links_style;
                }

                var headingMessagesText = document.getElementById("browser_heading_text_messages");
                if (headingMessagesText) {
                  headingMessagesText.style.cssText = h.links_style;
                }

                var headingSettingsText = document.getElementById("browser_heading_text_settings");
                if (headingSettingsText) {
                  headingSettingsText.style.cssText = h.links_style;
                }

                var headingSignText = document.getElementById("browser_heading_text_sign");
                if (headingSignText) {
                  //headingSignText.setAttribute("style", h.links_style);
                  headingSignText.style.cssText = h.links_style;
                }
              }
              
              if (h.text_style) {
                var headingText = document.getElementById("browser_heading_text");
                if (headingText) {
                  //headingText.setAttribute("style", h.text_style);
                  headingText.style.cssText = h.text_style;
                }
                
              }
              
            }
            
            if (b.header_bar) {
              var hb = b.header_bar;
              
              if (hb.background_color) {
                var headerTable = document.getElementById("browser_header_bar");
                if (headerTable) {
                  headerTable.style.backgroundColor = hb.background_color;
                }
              }
              
              if (hb.powered_by) {
                var poweredImg = document.getElementById("browser_header_bar_powered_by");
                if (poweredImg) {
                  poweredImg.src = hb.powered_by;
                  pngfix();
                }
              } 

              var headerMessage = document.getElementById("browser_header_bar_message");
              if (headerMessage) {
                if (hb.message_style) {
                  headerMessage.setAttribute("style", hb.message_style);
                }
                if (hb.message) {
                  headerMessage.innerHTML = hb.message;
                }
              }
              
              if (hb.pagination_style) {
                // We'll store the style info so that when we create the pagination
                // elements, we can give them the appropriate styles
                this._page_pagination_style = hb.pagination_style;
                this._renderPageNavigation();
              }
            }
            
            if (b.navigation) {
              var nav = b.navigation;
              
              if (nav.cell_style) {
                var navCell = document.getElementById("browser_navigation_cell");
                if (navCell) { navCell.setAttribute("style", nav.cell_style); }
              }
              
              if (nav.style) {
                var navDiv = document.getElementById("metadata_navigation");
                if (navDiv) {
                  //navDiv.setAttribute("style", nav.style);
                  navDiv.style.cssText = nav.style;
                }
              }
            }
                
          }
          
          
          // Update the box_ad
         
          var boxAd = document.getElementById('browse_mini_sells');
          var defaultTheme;
          if (filters_json[51] && filters_json[51].browser) {
            defaultTheme = filters_json[51].browser; // Use the blank cards theme for the default
          }
          if (boxAd && defaultTheme && defaultTheme.box_ad) {
            var isPrem = false;
            var nowDate = new Date();
            var nowTime = nowDate.getTime();
            // if the ad was changed more than 4 seconds ago.
            if ( (nowTime - this._ad_last_updated) > 4000) {
              this._ad_last_updated = nowTime;

              //  Show different ads based on premium / non-premium
              var adArray = [];
              if ((EcardSelector && EcardSelector.showFree == false) && (defaultTheme.box_ad.uhid != 0)) {
                // Premium
                if (defaultTheme.box_ad && defaultTheme.box_ad.premium) {
                  adArray = defaultTheme.box_ad.premium;
                  isPrem = true;
                }
              } else {
                // Not premium
                if (defaultTheme.box_ad && defaultTheme.box_ad.nonpremium) {
                  adArray = defaultTheme.box_ad.nonpremium;
                } else if (defaultTheme.box_ad && defaultTheme.box_ad.premium) {
                  // We want to serve them some sort of ad.
                  adArray = defaultTheme.box_ad.premium;
                }
              }
            
              if (adArray.length > 0 ) {
                var index = Math.floor(Math.random()*adArray.length);
                var ad = adArray[index];
                if (isPrem) {
                  isPrem = " target='_blank' ";
                } else {
                  isPrem = '';
                }
                boxAd.innerHTML = '<div class="mini_sell" style="background-color:'+ad.background_color+'; background-image: url(\''+ad.background_image+'\'); background-repeat: repeat-x;"><a href="'+ad.url+'" '+isPrem+' onclick="PlxClick.send(\'browse\', \'mini_sell\', \''+ad.click_key+'\', {\'sell_id\':\''+ad.id+'\'}); return true;" title="'+ad.alt+'"><img src="'+ad.src+'" alt="'+ad.alt+'" style="display: inline; padding: 0px; margin: 0px;" /></a></div>';
              }
            }
          }

          // Only set one theme's look & feel
          break;
        }
      }
      
      
    },
    // }}}
    // {{{ - refreshPaginationNavigation()
    /**
     * Recalculating of the navigation will happen when the user changes
     * the page size, or when the user changes the startThumbId
     *
     * There are rules by which we must abide when we perform these
     * recalculations
     *
     * -- We have the option to change our page number.
     * -- When rendered, the current page number will be "selected"
     * -- There may be overlap between page 1 and page 2
     * -- If one clicks "Show All", we must save the current view size.
     *      -> If "show_normal_size" is not null, we display a link to
     *         revert the "Show All" navigation back to paged nav.
     */
    refreshPaginationNavigation: function() {
        //ecdbug('refreshPaginationNavigation()');

        var paginationInfo = new Array();
        paginationInfo = calculatePagination(
            this._page_start_index + 1,
            this._page_size,
            this._page_total_num_items,
            true
        )

        // Now let's compile our info for the rendering function.

        var navigationArr = new Array();
        var pageNum;
        var selected;
        var startIndex;
        var text;
        for (var i = 0; i < paginationInfo.displayListArr.length; i++) {
            pageNum = paginationInfo.displayListArr[i];
            if (pageNum == -1) {
                startIndex = -999;
                text = "&hellip;";
                selected = false;
            } else {
                selected = (pageNum == paginationInfo.currentPageNum) && !this.getShowAllMode();
                startIndex = paginationInfo.pageInfoArr[pageNum].start - 1;
                text = pageNum;
            }

            navigationArr[navigationArr.length] = {
                index: startIndex,
                text: text,
                selected: selected
            };
        }


        var moreCardsIdx = this._page_start_index + this._page_size;
        if ((moreCardsIdx >= this._page_total_num_items) || this.getShowAllMode()) {
            moreCardsIdx = -1;
        }

        // Finally determine if we need a "Show All" link.  Not needed if we're
        // already showing all the images for the category.
        if ( this.getShowAllMode() ) {
            navigationArr[navigationArr.length] = {index: -999, text: 'Show&nbsp;All', selected: true};
        } else {
            navigationArr[navigationArr.length] = {index: -2, text: 'Show&nbsp;All', selected: false};
        }

        this._renderPageNavigation(navigationArr, moreCardsIdx);
        this.setMoreCardsPos(moreCardsIdx);
        //this.refreshThumbs(); //No need to call because we call this manually from ecard_select
    },
    // }}}
    // {{{ - _renderPageNavigation(navigationsArr, moreCardsIdx)
    /**
     * The navigation array will consist of the following info
     * for each element:
     *   "startIndex" -- The index # for the first element on that page
     *   "text" -- The text for the link
     *   "selected" -- Whether the item is selected
     *
     * If an item does not have a startIndex, it will not be linked.
     * This can be used for when we want to display elipsis do indicate
     * there are pages between.
     *
     * The full rendered navigation should look like:
     *     "Start" ... 4 5 *6* 7 8 ... End  |  All Images
     *
     */
    _renderPageNavigation: function(navigationArr, moreCardsIdx) {
      
      if (navigationArr && moreCardsIdx) {
        this._last_navigationArr = navigationArr;
        this._last_moreCardsIdx = moreCardsIdx;
      } else {
        navigationArr = this._last_navigationArr;
        moreCardsIdx = this._last_moreCardsIdx;
      }
        //ecdbug('_renderPageNavigation('+navigationArr+','+moreCardsIdx+'): called');
        // Generate some style info from this._page_pagination_style
        var styleStr = '';
        if (this._page_pagination_style && this._page_pagination_style.unselected) {
          var styles = this._page_pagination_style.unselected;
          for (prop in styles) {
            switch (prop) {
              case 'color':
              case 'background-color':
              case 'text-decoration':
               styleStr += prop + ':' + styles[prop] + ';';
               break;
              default:
            }
          }
        }

        var html = '<div style="'+styleStr+'float: left; padding: 4px;">Page:</div>';
        var tmp = '';
        var styleClass = '';



        for (var i = 0; i < navigationArr.length; i++) {

            if (navigationArr[i].selected) {
                styleClass = 'selected';
            } else {
                styleClass = '';
            }

            var sideWidth;
            var linkText;
            if (!navigationArr[i].selected) {
                if (navigationArr[i].text == '&hellip;') {
                    sideWidth = 1;
                    linkText = '<span style="' + styleStr + '">' + navigationArr[i].text + '</span>';
                } else {
                    sideWidth = 4;
                    linkText ='<a href="#" class="'+styleClass+'" style="' + styleStr + '" onclick="EcardSelector.doThumbMove('+navigationArr[i].index+', \'page_nav\');return false;" title="Go to page '+navigationArr[i].text +' of images">'+navigationArr[i].text+'</a>'
                }
                tmp = '<div style="float: left; padding: 4px;">'+linkText+'</div>';

            } else {
                tmp = '<div style="float: left; padding: 4px; border: 1px 1px 0px 1px; border-color: #333333; background-color: white; font-weight:bold;">'+navigationArr[i].text+'</div>';
            }
            html += tmp;
        }
        //html = html.substring(0, html.length-2);
        //html = '<table border="0" cellspacing="0" cellpadding="0"><tr>' + html + '</tr></table>';
        this.setPaginationNavigationHtml(html);
    },
    // }}}
    // {{{ - _sort_navigation_arr(a,b)
    _sort_navigation_arr: function(a,b) {
        return a.index - b.index;
    }
    // }}}
}
function PlxEcardTplSelectUI_onload() {
    PlxEcardTplSelectUI.init();
}
SafeAddOnload(PlxEcardTplSelectUI_onload);

// {{{ show_mag(e,imgObj,imgId,onClickAction)
function show_mag(e, imgObj, imgId, onClickAction) {
    if (!e) var e = window.event;
    var sample = document.getElementById('thumb_mag_preview');
    var hover = document.getElementById('thumb_mag_hover');
    var glass = document.getElementById('thumb_mag_glass');
    var pos_x = findPosX(imgObj);
    var pos_y = findPosY(imgObj);
    var sample_img_src = 'dyn/ttsamp/'+imgId+'_'+PlxEcardTplSelectUI._filterText+'.jpeg';
    //ecdbug('tooltip: '+sample_img_src);
    var page_sizes=get_page_size(); //from popover.js
    glass.style.left = (pos_x+10) + 'px';
    glass.style.top = (pos_y+3) + 'px';
    hover.style.display = 'none';
    //sample.innerHTML = '<img id="thumb_mag_sample_' + index + '" src="'+sample_img_src+'" />';
    sample.innerHTML = '<a href="#" onclick="return ' + unescape(onClickAction) + '" title="Select this ecard"><img id="thumb_mag_sample" src="'+sample_img_src+'" alt="' + imgId + '"/></a>';
    glass.onclick = function() { eval(unescape(onClickAction)); }
    //sample.innerHTML = '<img id="thumb_mag_sample" src="m/im/cus/middle_loading_animated.gif" />';
    // set default position {{{
    //alert(pos_x+','+pos_y);return;
    if (pos_x > (page_sizes[2]-300)) {
        hover.style.left = (page_sizes[2]-500) + 'px';
    } else {
        hover.style.left = pos_x + 'px';
    }
    if (pos_y > (page_sizes[1]-300)) {
        hover.style.top = (page_sizes[1]-400) + 'px';
    } else {
        hover.style.top = (pos_y+35) + 'px';
    }
    // }}}
    // reposition on image load {{{
    var load_img = new Image();
    load_img.px = pos_x;
    load_img.py = pos_y;
    load_img.pid = 'thumb_mag_sample';
    load_img.pidx = imgId;
    load_img.pageSizes = page_sizes;
    load_img.onload = function()
    {
        //ecdbug('onload(): called ' + this.pidx);
        var w = this.width;
        var h = this.height;
        if (!document.images[this.pid] || (document.images[this.pid].alt != this.pidx)) { return; } //scrolling around too fast? drop it!
        //document.images[this.pid].src = this.src;
        var hover = document.getElementById('thumb_mag_hover');
        //alert(this.px+'+'+w+' vs '+this.pageSizes);
        if (this.px + w + 20 > this.pageSizes[2]) {
            hover.style.left = (this.px - w + 10 + 15 - 3) + 'px';
        } else {
            hover.style.left = (this.px + 10 - 3) + 'px';
        }
        if ((this.py + h +20 > this.pageSizes[3]) && (this.py - h > 0)) {
            hover.style.top = (this.py - h - 3) + 'px';
        } else {
            hover.style.top = (this.py + 3 + 25 - 3) + 'px';
        }
    }
    load_img.src = sample_img_src;
    // }}}
    glass.style.display = 'block';
}
// }}}
// {{{ hide_mag(e)
/**
 * relTarg needed to avoid triggering mouseout when mouse moves over
 *  magnifying glass itself
 */
function hide_mag(e) {
    var relTarg;
    if (!e) var e = window.event;
    if (e.relatedTarget ) relTarg = e.relatedTarget;
    else if (e.toElement) relTarg = e.toElement;
    if (relTarg && relTarg.id != 'thumb_mag_glass') {
        document.getElementById('thumb_mag_glass').style.display = 'none';
        //document.getElementById('thumb_mag_preview').style.display = 'none';
    } else {    
        // onmouseover event for the preview
        var sample = document.getElementById('thumb_mag_hover');
        ensureElementFromObject(sample);
        sample.setOpacity(0);
        sample.fade(100,0,100,10,10,10);
        sample.style.display = 'block';
    }
}
// }}}

// {{{ - do_customize(isFree, id, escfilters)
isPremium = false;
/**
 * Show premium popover if the user is not premium member, else jump
 * directly to the customize page.
 */
function do_customize(isFree, id, escFilters)
{
    // Log the click
    PlxClick.send('browse', 'thumbnails', 'select_card', {'card_id':id, 'is_free':(isFree)?1:0});
    var url = 'customize.php?imgId='+escape(id);
    if (escFilters) { url += '&filters='+escFilters; }
    url += '&hash='+escape(window.location.hash.substr(1));
    if (true || isFree || isPremium) { //if card is free or user is premium. NOTE: Added true to allow to go through to customize page (v2.15 decision)
        window.location = url;
    } else {
        //document.getElementById('popover_order_link').href = 'HELLO';
        premium_popover(id);
    }
    return false;
}
// }}}

// {{{ premium_popover()
var premium_popover_signup = false;
function premium_popover(id) {
    if (!premium_popover_signup) {
        premium_popover_signup = document.getElementById('popover_signup_link').getAttribute('href');
    }
    if (id<0) {
        document.getElementById('popover_signup_link').setAttribute('href',premium_popover_signup+'ecard_web_prempopup_addphoto');
    } else {
        document.getElementById('popover_signup_link').setAttribute('href',premium_popover_signup+'ecard_web_prempopup_premcard');
    }
    show_popover('premium_popover',445,300);
    log_it('ECARD PREMIUM POPOVER: shown ID:'+id);
    //pngfix();
}
// }}}
// {{{ close_premium();
function close_premium() {
    return hide_popover('premium_popover');
}
// }}}

// {{{ welcome_popover()
function welcome_popover() {
    show_popover('welcome_popover',630,(30+400+30));
    //pngfix();
}
// }}}
// {{{ close_welcome();
function close_welcome() {
    return hide_popover('welcome_popover');
}
// }}}

// {{{ log_it(message)
function log_it_ignore() { }
function log_it(message)
{
    var post_obj = {type:'click_stream',message:message};
    ajax_query(log_it_ignore,'ajax/log.php',post_obj);
}
// }}}

function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}
