// vim: set tabstop=4 shiftwidth=4 foldmethod=marker :
/**
 * Handle the card selector.
 *
 * @requires ajax.js for remote scripting
 * @requires onload.js for binding to objects after loading.
 * @requires dhtmlHistory.js for implementing back button + bookmarking
 * @requires ecard_tpl_select.js for creating the UI interface object
 * @expects PlxEcardTplSelectUI to be defined and created by the ecard_tpl_select.js file
 * @provides EcardSelector global variable controling the ecard selection page
 * @todo save dhtml history with session
 * @todo reconstruct dhtml history from #link
 */
var EcardSelector = {
    showFree: true,
    groups: {}, //mapping of groups ids to object with name & filters
    filters: {}, //mapping of filter ids to name
    filters_json: {}, // json that has data for the customizations
    currentFilters: [],//current set of filters
    counts: {}, //how many cards there are in each filter
    thumbs: {}, //thumbnail images currently viewed
    thumbStart: 0,
    thumbLimit: 22,
    currentRevision: 0,
    // - property manipulation {{{
    // {{{ - cleanFilters()
    /**
     * Sometimes the filters get in a bad state (Bug #8963). Let's fix it.
     */
    cleanFilters: function() {
        var new_filters = [];
        for (var i=0,max=this.currentFilters.length;i<max;++i) {
            if (!this.currentFilters[i]) { continue; } //empty case
            var same = false;
            for (var j=0,jmax=new_filters.length;j<jmax;++j) {
                if (this.currentFilters[i] == new_filters[j]) { same=true; break; }
            }
            if (!same) {
                new_filters.push(this.currentFilters[i]);
            }
        }
        this.currentFilters = new_filters;
    },
    // }}}
    // {{{ - addGroup(gid, groupName)
    /**
     * Create a master list of filter groups
     */
    addGroup: function(gid, groupName) {
        //ecdbug('addGroup('+gid+','+groupName+'): called');
    	var group_obj = {name: groupName};
    	group_obj.filters = [];
    	this.groups[gid] = group_obj;
    },
    // }}}
    // {{{ - addFilter(fid, filterName, gid)
    /**
     * Create a master list of filters and bind them to the groups
     */
    addFilter: function(fid, filterName, filterJson, gid) {
    	this.filters[fid] = filterName;
    	if (filterJson != '') {
      	this.filters_json[fid] = eval( "(" + filterJson + ");" );
    	} else {
    	  this.filters_json[fid] = {};
    	}
    	
    	// be sure to add reference to filter to the groups
    	this.groups[gid].filters.push(fid);
    },
    // }}}
    // {{{ - flushCounts()
    flushCounts: function() {
    	this.counts = {};
    },
    // }}}
    // {{{ - addCount(filterId, total)
    /**
     * Create a list of counts for navigation
     */
    addCount: function(filterId, total) {
    	this.counts[filterId] = parseInt(total);
    },
    // }}}
    // {{{ - flushThumbs()
    flushThumbs: function() {
    	this.thumbs = [];
    },
    // }}}
    // {{{ - addThumb(thumbId, location, alt, free)
    /**
     * Create a list of counts for navigation
     */
    addThumb: function(thumbId, location, alt, free) {
    	this.thumbs.push({id:thumbId,location:location,alt:alt,free:free});
    },
    // }}}
    // }}}
    // - render*() html*() url*() {{{
    // {{{ - urlCurrentFilters()
    /**
     */
    urlCurrentFilters: function() {
        url = this.currentFilters.toString();
    	return escape(url);
    },
    // }}}
    // {{{ - htmlCurrentFilters()
    /**
     * Generate the html for the cookie crumbs of the filters
     */
    htmlCurrentFilters: function() {
        //ecdbug('htmlCurrentFilters(): filters='+this.currentFilters);
        // generate cookie crumbs array {{{
    	var textArray = [{text:'All Occasions', id:0}];
        this.cleanFilters();
    	for (var filter_id=0; filter_id<this.currentFilters.length; ++filter_id) {
            if (!this.currentFilters[filter_id]) { continue; }
    	    textArray.push({text: this.filters[this.currentFilters[filter_id]], id: this.currentFilters[filter_id]});
    	}
        // }}}
        //alert("lengths:\n"+this.currentFilters.length+"\n"+textArray.length);
        // generate html {{{
    	var html = '<table><tr>';
    	for (var i=0; i <textArray.length-1; i++) {
    	    html += '<td><table border="0" cellspacing="0" cellpadding="0">';
    	    html += '  <tr>';
    	    html += '    <td></td>';
    	    html += '    <td valign="middle" wrap="nowrap"><span class="body_copy">';
    	    html += '<a href="#htmlCurrentFilters1" onclick="return EcardSelector.doFilter(-'+ textArray[i]['id'] + ');">';
    	    html += textArray[i]['text'];
    	    html += '</a></span></td>';
    	    html += '    <td></td>';
    	    html += '  </tr>';
    	    html += '  <tr><td colspan="3"><img src="m/im/com/sp.gif" height="8" width="8" /></td></tr>';
    	    html += '</table></td>';
    	}
        // last one in list is special... {{{
        html += '<td><table border="0" cellspacing="0" cellpadding="0">';
        html += '  <tr>';
        html += '    <td></td>';
        html += '    <td valign="middle" bgcolor="#1d7ac9" wrap="nowrap"><span class="body_copy"><font color="white">';
        html += textArray[textArray.length - 1]['text'] + ' (' + this.counts[0] + ')';
        html += '</font></span></td>';
 	    html += '<td></td>';
        html += '</tr>';
        html += '<tr><td colspan="3" align="center"></td></tr>'
        html += '</table></td>';
        // }}}
    	html += '</tr></table>';
        // }}}
    	return html;
    },
    // }}}
    // {{{ - htmlFilterTitle(gix,fid,filterBy)
    /**
     * Generate the text for the title string based on a filter id
     */
    htmlFilterTitle: function(gid,fid,filterBy) {
        if (this.counts[fid]==1) {
            var plur = '';
            var verb = 'is';
        } else {
            var plur = 's';
            var verb = 'are';
        }
        switch (filterBy) {
            case 'undo':
            return 'Undo filter by '+this.filters[fid];
            case 'switch':
            return 'Switch view to the '+this.counts[fid]+' card'+plur+' that '+verb+' '+this.filters[fid];
            case 'view':
            if (gid==2) {
                return 'View '+this.counts[fid]+' '+this.filters[fid]+' card'+plur;
            } else {
                return 'View '+this.counts[fid]+' card'+plur+' that '+verb+' '+this.filters[fid];
            }
        }
    },
    // }}}
    // {{{ - renderNavigation()
    /**
     * Greate the filter navigation menu on the left.
     */
    renderNavigation: function(changeAd) {
    	// your location... {{{
    	PlxEcardTplSelectUI.setBreadcrumbHtml(this.htmlCurrentFilters());
        // Bug #8942 {{{
        PlxEcardTplSelectUI.setTotalNumberOfItems(this.counts[0]);
        PlxEcardTplSelectUI.refreshPaginationNavigation();
        // }}}
    	// }}}
    	var html = '';
        // Handle the special case where we must only show the occassion on
        // the first page. {{{
        //ecdbug('renderNavigation(): length='+this.currentFilters.length);
        //ecdbug('renderNavigation(): filters='+this.currentFilters);
        this.cleanFilters();
        if (this.currentFilters.toString().length>0) {
            var grouplist = {};
            for (var idx in this.groups) {
                if (idx == 2) { continue; }
                grouplist[idx] = this.groups[idx];
            }
            /*
            var grouplist = { 1:this.groups[1], //Style
                              4:this.groups[4]  //Relationship
                            };
            /* */
    	    html += '<div style="padding-top:10px;"><a href="#htmlCurrentFilters1" onclick="return EcardSelector.doFilter(0, \'crumb\');">View All Occasions</a></div>';
        } else {
            var grouplist = { 2:this.groups[2] }; //Occasion
        }
        // }}}
    	for (var gidx in grouplist) {
    		var gfound = false;
    		var group = this.groups[gidx];
            // Bad mojo. It means ajax/list_filters.php has not being processed!
            if (!group) { continue; }
            if (!group.name) { continue; }
    		var t_html = '<div class="filter_group">By '+ group.name + '&hellip;</div>'; // By XXXX... title
            // special case... check if we are horizontal navigating (already
            // filtered by this group, matching filter is horizontal_filter {{{
            var horizontal_filter = 0;
            //for (fidx in group.filters) {
            for (var fidx=0;fidx<group.filters.length;++fidx) {
                //if (fidx == '______array') { continue; } //trap json code
                for (var tidx=0;tidx<this.currentFilters.length;++tidx) {
                    if (group.filters[fidx]==this.currentFilters[tidx]) {
                        horizontal_filter = this.currentFilters[tidx];
                    }
                }
            }
            // }}}
            // first write the "All XXXX (n)" part {{{
            if (horizontal_filter) {
                t_html += '<div class="filter"><a href="#renderNavigation1" onclick="return EcardSelector.modFilter('+horizontal_filter+')" title="'+this.htmlFilterTitle(gidx,fid,'undo')+'">All ' + group.name + "s</a></div>\n";
            } else {
                t_html += '<div class="filter selected">All ' + group.name + "s</div>\n";
            }
            // }}}
    		for (var fidx in group.filters) {
    			var fid = group.filters[fidx];
    			if (this.counts[fid]) {
                    if (fid == horizontal_filter) {
        				t_html += '<div class="filter selected">' + this.filters[fid] + ' (' + this.counts[0] + ")</div>\n";
                    } else if (horizontal_filter) {
        				t_html += '<div class="filter"><a href="#renderNavigation2" onclick="return EcardSelector.modFilter('+horizontal_filter+','+fid+');" title="'+this.htmlFilterTitle(gidx,fid,'switch')+'">' + this.filters[fid] + "</a></div>\n";
        				gfound = true;
                    } else {
        				t_html += '<div class="filter"><a href="#renderNavigation3" onclick="return EcardSelector.doFilter('+fid+', \'leftnav\');" title="'+this.htmlFilterTitle(gidx,fid,'view')+'">' + this.filters[fid] + "</a></div>\n";
        				gfound = true;
                    }
    			} else if (this.filters[fid]) {
                    if (fid == horizontal_filter) {
                        // Bug #9048
                        t_html += '<div class="filter selected">'+this.filters[fid]+"</div>\n";
                    } else {
                        t_html += '<div class="filter">'+this.filters[fid]+"</div>\n";
                    }
                }
    		}
    		//t_html += '';
    		if (gfound) { html += t_html; }
    	}
    	PlxEcardTplSelectUI.setNavigationHtml(html);
    	PlxEcardTplSelectUI.updateTheme(this.currentFilters, this.filters_json, changeAd);
        PlxEcardTplSelectUI.setHeader(this.currentFilters);
        if (PlxEcardTplSelectUI.setAddPhotoFilters) {
            PlxEcardTplSelectUI.setAddPhotoFilters(this.currentFilters);
        }
    },
    // }}}
    // {{{ - renderThumbnails()
    /**
     * Update thumbnails based on current data...
     */
    renderThumbnails: function() {
        PlxEcardTplSelectUI.setTotalNumberOfItems(this.counts[0]);
        PlxEcardTplSelectUI.refreshPaginationNavigation();
        var html = '';


    	for (var tidx=0;tidx<this.thumbs.length;++tidx) {
    	    html = '';

    	    var thumb = this.thumbs[tidx];
            var filters = this.urlCurrentFilters();
            //var url = 'customize.php?imgId='+ escape(thumb.id) + '&amp;filters='+escape(this.urlCurrentFilters())+'&amp;hash='+escape(window.location.hash.substr(1));  
            var pos = parseInt(this.thumbStart) + parseInt(tidx);
    	    PlxEcardTplSelectUI.addImage(pos, thumb.location, thumb.alt, thumb.id, thumb.free, this.currentFilters[0], filters);
    	}
    	PlxEcardTplSelectUI.refreshThumbs();
    },
    // }}}
    // }}}
    // - externally called methods  {{{
    // {{{ - doThumbMove(newPos)
    /**
     * Handle moving around in thumbnails...
     * Saves action to history.
     */
    doThumbMove: function(newPos, section) {
        //alert("doThumbMove: " + newPos);
        var data = new Object;
        var action = '';
        
        if (newPos >= 0) {
    		PlxEcardTplSelectUI.setShowAllMode(0);
            this.thumbStart = newPos;
       		PlxEcardTplSelectUI.setPageStartIndex(this.thumbStart);
       		
       		// Tracking
       		data.item_index = newPos;
       		action = 'jump';

    	} else if (newPos == -1) { //go to lastpage
    		PlxEcardTplSelectUI.setShowAllMode(0);
    		this.thumbStart = this.counts[0] - (this.counts[0] % this.thumbLimit);
       		PlxEcardTplSelectUI.setPageStartIndex(this.thumbStart);
       		action = 'last_page';
        } else {
    	    PlxEcardTplSelectUI.setShowAllMode(1);
    	    action = 'show_all';
        }
        this.refreshThumbnails();
        this.recordHistory();
        
        data.page_size = PlxEcardTplSelectUI.getPageSize();
        PlxClick.send('browse', section, action, data);
    	// no follow link
    	return false;
    },
    // }}}
    // {{{ - modFilter(removeFilter,addFilter)
    /**
     * Add filterId to the list of currentFilters and refresh. If none provided
     * then clear list.  If a negative filter is provided, we pop off filters
     * until we hit the current one provided (breadcrumbs).
     */
    modFilter: function(removeFilter,addFilter) {
        //alert("modFilter: " + removeFilter+' ' + addFilter);
        this.cleanFilters();
        for (var pos=0;pos<this.currentFilters.length;++pos) {
            if (removeFilter == this.currentFilters[pos]) { break; }
        }
        this.currentFilters.splice(pos,1);
        if (addFilter) {
            return this.doFilter(addFilter);
        }
        this.refreshFilter(true);
    	// no follow link
        return false;
    },
    // }}}
    // {{{ - doFilter(filterId, section)
    /**
     * Add filterId to the list of currentFilters and refresh. If none provided
     * then clear list.  If a negative filter is provided, we pop off filters
     * until we hit the current one provided (breadcrumbs).
     */
    doFilter: function(filterId, section) {
        
        // First log the event:
        PlxClick.send('browse', section, 'do_filter', {'curr_filters':this.currentFilters.toString(), 'selected_filter':filterId});
       //ecdbug("doFilter: " + filterId);
    	if (filterId > 0) {
    		this.currentFilters.push(filterId);
    	} else if (filterId < 0) {
    	    // Keep popping until we pop this Id.
            filterId = -filterId;
    	    while ((this.currentFilters.length > 0) && (filterId != this.currentFilters.pop())) {}
    	    this.currentFilters.push(filterId);
    	} else {
    		this.currentFilters = [];
    	}
        PlxEcardTplSelectUI.setShowAllMode(0); //Bug #9048
        this.refreshFilter(true);
    	// no follow link
        return false;
    },
    // }}}
    // {{{ - refreshFilter($shouldRecord)
    /**
     * Refresh list after a filter change
     */
    refreshFilter: function(shouldRecord) {
        //ecdbug('refreshFilter('+shouldRecord+'): called');
    	// Because we're changing our filter, we need to reset some page values
    	// thumbnail start #
    	// page #
    	// total # items
    	this.thumbStart = 0;
    	PlxEcardTplSelectUI.setPageStartIndex(0); // Which item are we jumping to
        if (shouldRecord) {
        	this.refreshList(); // Let nav redraw before removing thumbnails
        }
    	// We only reset in the case of getting a new filter
    	PlxEcardTplSelectUI.resetThumbnailHtml();
        if (shouldRecord) {
        	this.refreshThumbnails(); // Already storing history with list refresh
        }
        if (shouldRecord) {
            this.recordHistory();
        }
    },
    // }}}
    // {{{ - refreshList()
    /**
     * Get counts on the filters and generate new Navigation
     */
    refreshList: function() {
        //ecdbug('refreshList(): filters='+this.currentFilters);
    	var filters = '';
        this.cleanFilters();
    	var post_obj = {filters:this.currentFilters.toString()}
	var d = new Date();
    	ajax_query(ecard_selector_process_filtercounts,'ajax/filter_counts.php?'+d.getTime(),post_obj);
    },
    // }}}
    // {{{ - refreshThumbnails()
    /**
     *
     */
    refreshThumbnails: function() {
    	this.thumbLimit = PlxEcardTplSelectUI.getPageSize();
        // Bug #10060
        var start_id = (this.thumbLimit==-1) ? 0 : this.thumbStart;
        var show_free = (this.showFree) ? 1 : 0; //don't show "free" seal to premium users
        //ecdbug('refreshThumbnails(): thumblimit='+this.thumbLimit);
        this.cleanFilters();
    	var post_obj = {
            filters: this.currentFilters.toString(),
            startId: start_id,
            limit:   this.thumbLimit,
            showFree: show_free 
        };
	var d = new Date();
	
    	ajax_query(ecard_selector_process_getthumbnails,'ajax/get_thumbnails.php?'+d.getTime(),post_obj);
    },
    // }}}
    // {{{ - recordHistory(firstTimeToken)
    /**
     * Saves the view state to the history...
     */
    recordHistory: function(firstTimeToken) {

      // Go ahead and record this in history
      if ( (typeof pageTracker != undefined) && (pageTracker._trackPageview) ) {
        var f = this.currentFilters.join('_');
        if (f != '') { f = '/' + f; }
        pageTracker._trackPageview(_plx_page_track_prefix + f);
      }
      
      var state = {
            thumbStart: this.thumbStart,
            currentFilters: this.currentFilters.toString(),
            showAll: PlxEcardTplSelectUI.getShowAllMode()
            };
        var guid = 'h,'+this.currentRevision+','+state.thumbStart+','+state.showAll+','+state.currentFilters;
        if (firstTimeToken) {
            //alert('Storing first time state');
            historyStorage.put(firstTimeToken,state);
        } else {
            dhtmlHistory.add(guid,state);
        }
    	var post_obj = {action:'record',page:'select',guid:guid}
        //ajax_query(false,'ajax/history.php',post_obj,true);
        ++EcardSelector.currentRevision;
    }
    // }}}
    // }}}
};
// {{{ ecard_selector_history_change(newLocation,historyData)
/**
 * Playback the history up to a point.
 * @param newLocation after the user has navigated to a new location
 * @param historyData optional state data associated with the event.
 */
function ecard_selector_history_change(newLocation,historyData)
{
    //ecdbug('ecard_selector_history_change: '+newLocation+', '+historyData);
    if (newLocation=='') {
        //alert('grabbing initial state');
        historyData = historyStorage.get('initial_state');
    } else if (historyStorage.hasKey(newLocation)) {
        //alert('grabbing state:'+newLocation);
        historyData = historyStorage.get(newLocation);
    }
    if (historyData) {
        // currentFilters: must do first
        // BUG #8446: remember to convert to/from string (see recordHistory())
        EcardSelector.currentFilters = eval('['+historyData.currentFilters+']');
        //ecdbug('ecard_selector_history_change2: '+typeof EcardSelector.currentFilters+', '+EcardSelector.currentFilters.length+', '+EcardSelector.currentFilters);
        EcardSelector.refreshFilter(false);
        // thumbStart
  		PlxEcardTplSelectUI.setShowAllMode(0);
        EcardSelector.thumbStart = historyData.thumbStart;
  		PlxEcardTplSelectUI.setPageStartIndex(historyData.thumbStart);
        // showAll
  		PlxEcardTplSelectUI.setShowAllMode(historyData.showAll);
    }
    //alert('filters:'+EcardSelector.currentFilters);
    EcardSelector.refreshList();
    EcardSelector.refreshThumbnails();
}
// }}}
// {{{ ecard_selector_process_filterlist(responseXml)
/**
 * Get all initial values from filter list. Called as a AJAX return from the
 * onload handler.
 */
function ecard_selector_process_filterlist(responseXml)
{
    //ecdbug('ecard_selector_process_filterlist(): called');
	var groups = responseXml.documentElement.getElementsByTagName('group');
	var idx = 0;
	var groups;
	while (group = groups.item(idx)) {
		EcardSelector.addGroup(group.getAttribute('gid'), group.getAttribute('name'));
		var fidx = 0;
		var filter;
		while (filter = group.childNodes.item(fidx)) {
		  
			EcardSelector.addFilter(
			   (filter.getAttribute('fid')) ? filter.getAttribute('fid') : null,
			   (filter.getAttribute('name')) ? filter.getAttribute('name') : null,
			   (filter.firstChild && filter.firstChild.data) ? filter.firstChild.data : null,
			   (group.getAttribute('gid')) ? group.getAttribute('gid') : null
			);
			++fidx;
		}
		++idx;
	}
    // I shouldn't need this because the filtercounts will call this however
    // the two things seem to be returning at different rates on ectest so
    // I will put this in.
  	EcardSelector.renderNavigation(); // false to not change the ad
}
// }}}
// {{{ ecard_selector_process_filtercounts(responseXml)
/**
 * Get all counts from filtercounts
 */
function ecard_selector_process_filtercounts(responseXml)
{
    //ecdbug('ecard_selector_process_filtercounts(): called');
	var counts = responseXml.documentElement.getElementsByTagName('filtercount');
	EcardSelector.flushCounts();
	var idx = 0;
	var filtercount;
	while (filtercount = counts.item(idx)) {
		EcardSelector.addCount(filtercount.getAttribute('filterId'), filtercount.getAttribute('count'));
		++idx;
	}
	EcardSelector.renderNavigation();

}
// }}}
// {{{ ecard_selector_process_getthumbnails(responseXml)
/**
 * Get all counts from filtercounts
 */
function ecard_selector_process_getthumbnails(responseXml)
{
	var thumbs = responseXml.documentElement.getElementsByTagName('thumbnail');

	EcardSelector.flushThumbs();
	var idx = 0;
	var thumb;
	while (thumb = thumbs.item(idx)) {
		EcardSelector.addThumb(thumb.getAttribute('thumbId'),
                                thumb.getAttribute('location'),
                                thumb.getAttribute('alt'),
                                thumb.getAttribute('free'));
		++idx;
	}
	EcardSelector.renderThumbnails();
}
// }}}
// {{{ ecard_selector_process_playbackhistory(responseXml)
/**
 * If we have lost the history, we need to play it back
 */
/*
function ecard_selector_process_playbackhistory(responseXml)
{
	var pages = responseXml.documentElement.getElementsByTagName('guid');

    alert('playback called');
    return;
	var idx = 0;
	var thumb;
	while (page = pages.item(idx)) {
		EcardSelector.addHistory(page);
		++idx;
	}
	//EcardSelector.renderThumbnails();
        //dhtmlHistory.add('boobah',true);
        //EcardSelector.currentRevision = 2;
}
/* */
// }}}
// {{{ ecard_handle_page_resize()
function ecard_handle_page_resize() {
    //return;
    var oldSize = PlxEcardTplSelectUI.getPageSize();
    var newSize = PlxEcardTplSelectUI.recalculatePageSize();

    //alert("old: " + oldSize + "; new: "+newSize);
    if (newSize != oldSize) {
        PlxEcardTplSelectUI.setPageSize(newSize);
        EcardSelector.refreshThumbnails();
    }
}
// }}}
window.onresize=ecard_handle_page_resize;
// }}}

// {{{ ecard_selector_onload()
function ecard_selector_onload()
{
    // initialize the DHTML history framework
    dhtmlHistory.initialize();
    // subscribe to DHTML history change events
    dhtmlHistory.addListener(ecard_selector_history_change);
    var d = new Date();
    ajax_query(ecard_selector_process_filterlist,'ajax/list_filters.php?'+d.getTime());
    // If this is the first time the page is loaded
    if (dhtmlHistory.isFirstLoad()) {
        //ecdbug('ecard_selector_onload(): First load');
        var newSize = PlxEcardTplSelectUI.recalculatePageSize();
        PlxEcardTplSelectUI.setPageSize(newSize);
        // Hashlink bookmarking support {{{
        var guid_parts = window.location.hash.split(',');
        //guid = 'h,'+this.currentRevision+','+state.thumbStart+','+state.showAll+','+state.currentFilters;
        if (guid_parts.length > 4) {
            //guid_parts[0] = 'h';
            //EcardSelector.currentRevision = guid_parts[1];
            EcardSelector.thumbStart = parseInt(guid_parts[2]);
  		    PlxEcardTplSelectUI.setPageStartIndex(guid_parts[2]);
            PlxEcardTplSelectUI.setShowAllMode(parseInt(guid_parts[3]));
            EcardSelector.currentFilters = guid_parts.slice(4);
        }
        //alert(guid_parts);
        // }}}
        EcardSelector.refreshList();
        EcardSelector.refreshThumbnails();
        EcardSelector.recordHistory('initial_state');
        //PlxEcardTplSelectUI.setTotalNumberOfItems(40);
        //PlxEcardTplSelectUI.setPageSize(3);
        //PlxEcardTplSelectUI.refreshPaginationNavigation();
    } else {
        //ecdbug('ecard_selector_onload(): reload');
        EcardSelector.refreshList();
        EcardSelector.refreshThumbnails();
        // TODO: grab the from
    	//var post_obj = {action:'playback',page:'select',from:0}
        //ajax_query(ecard_selector_process_playbackhistory,'ajax/history.php',post_obj);
    }
}
// }}}
SafeAddOnload(ecard_selector_onload);

function ecdbug(text) {
    //document.getElementById('debugTarget').innerHtml += '<pre>'+text+'</pre>';
    //alert(text);
    //setInnerHtml('debugTarget',getInnerHtml('debugTarget')+text+"\n");
    setInnerHtml('debugTarget',getInnerHtml('debugTarget')+"<pre>"+text+"</pre>");
}
