// betadisply.js
//
// -- mgibberman
//
// This file contains javascript specific to the various agbeta display pages.
// 

// Page global vars
//  Sure global vars are bad, but they solve a problem
var g_mapinitdata;
var g_userrated=false;
var g_custcommented=false;
var g_ajax_error = false;
var thingid=null; 
var undefined; // Never define this! Used for comparison throughout

dojo.addOnLoad(function(){dojo.require("dojo.crypto.*");});

///////////////////////////////////////////////////////////////
// Beta Display - specific vars:
//   Used for contolling tabs ui on display page
var comments_on  = {'off':[ 'show_recently','recently',
                            'show_recommend','recommend' ],
                     'on':[ 'show_comments','comment' ]};
var recently_on  = {'off':[ 'show_comments','comment',
                            'show_recommend','recommend' ],
                     'on':[ 'show_recently','recently' ]};
var recommend_on = {'off':[ 'show_recently','recently',
                            'show_comments','comment' ],
                     'on':[ 'show_recommend','recommend' ]};
///////////////////////////////////////////////////////////////


// submit_request - Centralized AJAX-request function.
function submit_request(bindargs) {
    // Reset global here as it is the central ajax request point.
    g_ajax_error = false;
    // Define default 'load' and 'error' handlers
    var on_success = function (type, data, evt) {
        g_ajax_error = false;
        loadCRTData();
    };
    var on_error = function (type, errObj) {
        var es = "";
        for (var v in errObj) { es += v + ": " + errObj[ v ] + " "; }
        dojo.debug(es);
        g_ajax_error = true;
    };
    
    // Define default vals for AJAX request
    var dflt_bind = {
                      sync: false,
                      load: on_success,
                      error: on_error,
                      mimetype:"text/json",
                      method: 'POST',
                      url: khost + '/share/crt/crtnocache.pd'
                    };

    // Check if bind dictionary contains the request content, if not, error out.
    if ((bindargs['content']===undefined) || (bindargs['content']===null)) {
        throw new Error('"content" missing from AJAX request.');
    }
    // Put default vals in for any bind param that is missing from dict.
    for (key in dflt_bind) {
        key = key.toString();
        if ((bindargs[key]===undefined) || (bindargs[key]===null)) {
            bindargs[key] = dflt_bind[key];
        }
    }
    // Make request.
    dojo.io.bind(bindargs);
}


function onStartEditText(){
    if(document.forms.customForm.blnstartedit){
        document.forms.customForm.blnstartedit.value = 1;
    }
}

function onEditText(){
    if(document.forms.customForm.blnedittext){
        document.forms.customForm.blnedittext.value = 1;
    }
}

function initCRTData(mapinitdata) {
    var required_vectors = [ 'clientnamespaceid','prodnum','custnum','sitegroup','site'];
    // Check that we have all we require...
    //for (var vector in required_vectors) {
    for (var i=0; i<required_vectors.length; i++) {
        var vector = required_vectors[i];
        //alert(vector);
        if (mapinitdata[vector] === undefined) {
            //alert("I'm going to error out now because of " + vector);
            throw new Error('function initCRTData called with invalid ' +
                            'argument map. Vector ' + vector + 'missing.');
        }
    }
    // Do defaults...
    if (mapinitdata['starsize'] === undefined) { mapinitdata['starsize'] = 20; }
    if (mapinitdata['numstars'] === undefined) { mapinitdata['numstars'] = 5; }
    if (mapinitdata['username'] === undefined) { mapinitdata['username'] = ''; }
    if (mapinitdata['comments'] === undefined) { mapinitdata['comments'] = 1; }
    if (mapinitdata['ratings']  === undefined) { mapinitdata['ratings']  = 1; }
    if (mapinitdata['abusethreshold'] === undefined) { mapinitdata['abusethreshold'] = 1; }
 
    g_mapinitdata = mapinitdata;
    try {loadCRTData();}
    catch(e) { dojo.debug(e.name + ': ' + e.message); }
}

function loadCRTData(onsuccess,onerror) {
    if (onsuccess === undefined) {onsuccess = gotCRTData;}
    if (onerror   === undefined) {onerror = dontGotCRTData;}
    
    try {
        var crtdata = {
                       'customernumber': g_mapinitdata['custnum'],
                       'sitegroup': g_mapinitdata['sitegroup'],
                       'comments': g_mapinitdata['comments'],
                       'ratings': g_mapinitdata['ratings'],
                       'tags': 0,
                       'thingtypeid': 1,
                       'thingname': g_mapinitdata['prodnum'],
                       'clientnamespaceid': g_mapinitdata['clientnamespaceid']
                      };
    
        dojo.debug('hmac_inputs: ' + dojo.io.argsFromMap(crtdata));
        var hmac_sig = dojo.crypto.MD5.getHMAC(dojo.io.argsFromMap(crtdata), "crt", dojo.crypto.outputTypes.Hex);
        dojo.debug('hmac_sig: ' + hmac_sig);
    
        crtdata['as_format'] = 'as_json';
        crtdata['f']         = 'GetThingData';
        crtdata['hmac']      = hmac_sig;
        
        var bind = {'content':crtdata,'load':onsuccess,'error':onerror};
        // Don't submit the AJAX request if we don't want ANY data.
        if ((crtdata.comments + crtdata.ratings) > 0) { submit_request(bind); }
    } catch(e) { dojo.debug('ERROR: loadCRTData | ' + e.message); }
}

/////////////////////////////////////////////////////////////
function gotRData(type, data, evt) {
    var ratingscore = 0;
    var ratingnum = 0;
    var userrating = 0;
    thingid  = data.thing.THINGID;
    dojo.debug('ThingID: ' + thingid);
    try {
        ratingscore = data.ratings[ 0 ][ 'TAG_SCORE' ];
        ratingnum   = data.ratings[ 0 ][ 'NUMRATED' ];
    } catch(e) {
        dojo.debug('ratings: ' + e.message);
    }
    // Update display here even if error above
    // will update with defaults
    UpdateRatingDisplay('users-rating',ratingnum,false);
    UpdateRatingDisplay('avg-rating',ratingscore,true);
    dojo.debug('RatingScore: ' + ratingscore);
    dojo.debug('RatingNum: ' + ratingnum);

    try {
        g_userrated=false;
        userrating  = data.userratings[ 0 ][ 'RATINGSCORE' ];
        if (userrating!==undefined && userrating!==null) {g_userrated=true;}
        dojo.debug('UserRating: ' + userrating);
    } catch (e) {
        dojo.debug('userratings: ' + e.message);
    }
    // Update display here even if error above
    // will update with defaults
    UpdateRatingDisplay('my-rating',userrating,true);
}
/*
 date_sort - sorts list of map objects (specifically comments)
            by 'CREATEDDATE'. Per Ticket #82409
*/
function date_sort(x,y) {
    if (x.CREATEDDATE < y.CREATEDDATE) return -1;
    if (x.CREATEDDATE == y.CREATEDDATE) return 0;
    if (x.CREATEDDATE > y.CREATEDDATE) return 1;
}

function gotCData(type, data, evt) {
    try {
        var comments         = data.comments;
        var comment_len      = comments.length;
        var comment_html     = '';
        thingid  = data.thing.THINGID;        
        // Comments to be listed in descending date order.
        comments = comments.sort(date_sort);
        var has_user_comment = new Boolean(false);
        dojo.debug("#Comments: " + comment_len);
        if (comment_len > 0) {
            UpdateCommentDisplay('commentlist', null);
            for (var i=0;i<comment_len;i++) {
                var comment = comments[ i ];
                dojo.debug("comment: " + comment.COMMENTS);
                comment_html += make_comment_html(comment);
                if ( comment.CUSTOMERNUMBER == g_mapinitdata[ 'custnum' ]) {
                    has_user_comment = true;
                }
            }
            var comment_nodes = dojo.html.createNodesFromText(comment_html);
            for (var j=0;j<comment_nodes.length;j++) {
                UpdateCommentDisplay('commentlist', comment_nodes[j]);
            }

            dojo.debug('has_user_comment: '+has_user_comment);
            if (has_user_comment===true) {
                dojo.html.hide('addcommentform');dojo.html.hide('yourcomment');
            } else {
                dojo.html.show('yourcomment');
            }
        } else { // if signed in
            dojo.html.show('befirst');
        }
    } catch (e) {
        dojo.debug('gotCData: ' + e.message);
    }           
}

// Rating a Comment
function gotRCData(type, data, evt) {
    try {
        dojo.debug('data: ' + data.toString());
        if (data.error !== undefined) {
            g_ajax_error = true;
            var es = data.error.toLowerCase();
            dojo.debug('es: ' + es);
            if (dojo.string.has(es,'unique constraint')) {
                UpdateCommentStatus('You appear to have already posted a rating for this comment.', true);
            } else {
                UpdateCommentStatus('An error occurred while attempting to rate this comment.', true);
            }
            UpdateCommentStatus('<!-- '+es+' -->', true, true);
        } else {
            UpdateCommentStatus('Thank you.', true);
        }
    } catch(e) {
        dojo.debug(e.name + ': ' + e.message);
        UpdateCommentStatus('Thank you.', true);
    }
}

function gotCRTData(type, data, evt) {
    if (data.ratings)  { gotRData(type, data, evt); }
    if (data.comments) { gotCData(type, data, evt); }
}

function dontGotCRTData(type, errObj) {
    var es = "";
    var retval = {};
    for (var v in errObj) {
        es += v + ": " + errObj[ v ] + " ";
    }
    retval[ 'ratingscore' ] = null; //ratingscore;
    retval[ 'ratingnum' ]   = null; //ratingnum;
    retval[ 'errmsg' ]      = es;
    dojo.debug('Failed to Save Rating 1: ' + es);
}
/////////////////////////////////////////////////////////////

function UpdateRatingDisplay(name,value,show) {
    dojo.debug("UpdateRatingDisplay: " + name + '/' + value);
    var elem;
    if (show) {
        try {
            var w = Math.round(value * g_mapinitdata[ 'starsize' ]) + 'px';
            dojo.debug("width: " + w);
            elem = dojo.byId('current-'+name);
            elem.style.width = w;
        } catch(e) {
            dojo.debug("Error Setting Style: " + e.message);
        }
        var clear_node = dojo.byId('clear-my-rating');
        if (g_userrated===true) { dojo.html.show(clear_node); }
        else { dojo.html.hide(clear_node); }
    } else {
        try {
            elem = dojo.byId(name);
            elem.innerHTML = value.toString();
        } catch(e) {
            dojo.debug("Error Setting Val: " + e.message);
        }
    }
}

function showRateVal(value) {
    UpdateRatingDisplay('my-rating',value,false);
}

function clearRating(rtid) {
    UnrateContent(rtid);    
}

function UpdateCommentDisplay(name,node) {
    dojo.debug("UpdateCommentDisplay: " + name + '/' + node);
    var elem;
    elem = dojo.byId(name);
    if (node !== null) { //elem.appendChild(node); }
        var c1 = elem.firstChild;
        elem.insertBefore(node,c1); // just appends if c1===null;
    } else { // remove all children
        var child = elem.lastChild;
        while (child !== null) {
            elem.removeChild(child);
            child = elem.lastChild;
        }
    }
}

function UpdateCommentStatus(value,on,add) {
    var name = 'commentstatus';
    var elem;
    dojo.debug("UpdateCommentStatus: " + name + '/' + value);
    elem = dojo.byId(name);
    
    if (add) { elem.innerHTML += value.toString(); }
    else     { elem.innerHTML = value.toString(); }
    
    var toggle;
    if (on) { toggle = 'block'; }
    else    { toggle = 'none'; }
    dojo.html.setDisplay(elem,toggle);
}

function clearComment() {
    dojo.byId('commenttext').value = '';
}

function ffCommentFixup(cmt_text){
    var arr_text = new Array();
    if (dojo.render.html.ie !== true) {
        var slen = cmt_text.length;
        var n = Math.ceil(slen/80);
        dojo.debug('slen: ' + slen + ' n: ' + n);
        for (var i=0;i<n;i++) { arr_text[i] = cmt_text.slice(i*80,((i+1)*80)-1); }
        return arr_text.join("<wbr/>");
    } else {
        return cmt_text;
    }
    return tmp_text;
}
    
function make_comment_html(comment) {
    var comment_html='';
    var ucid = comment.USERCOMMENTID;
    var ucid_name = "'ucid'"; //Another kluge. To get around the representation of strings within strings
    var score = 0;
    dojo.debug(comment.COMMENTS + ' by ' + comment.USERNAME);
    try { score = comment.COMMENTRATINGS[0].TOT_SCORE; }
    catch (e) { score = 0; }
    comment_html += '<div class="agi-comment"><h2>' + comment.USERNAME + '&nbsp;<span>said ';
    var timestamp = comment.MODIFIEDDATE;
    if ((timestamp !== undefined)&&(timestamp !== null)&&(timestamp !== '')) {
        comment_html += 'on '+ make_timestamp(timestamp);
    }
    comment_html += '</span></h2>';
    fixed_comment = ffCommentFixup(comment.COMMENTS);
    comment_html += '<p>' + fixed_comment + '</p>';
    comment_html += '<p class="agi-instr">' + score + ' people found this useful</p>';
    comment_html += '<p class="agi-commentlinks"><a href="Javascript:cmtRating(' + ucid + ',1)" class="agi-hilink">recommend&raquo;</a>';
    comment_html += '<a href="Javascript:confirm_abuse('+ucid_name+','+ucid+');" class="agi-hilink">report abuse&raquo;</a></p></div>';

    return comment_html;
}

function make_timestamp(ts) {
    var redate = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})(\s)*([0-9]{2}):([0-9]{2})/;
    var d  = ts.match(redate);
    
    var mm = d[1]; var dd = d[2];
    var yy = d[3]; var hh = d[5];
    var mi = d[6]; var ap = 'am';
    if (hh > 12) {
        hh -= 12;
        ap = 'pm';
    }
    var date_time = mm+'/'+dd+'/'+yy+' at '+hh+':'+mi+ap;
    return date_time;
}

function Register(rv,rtid) {
    alert('You must be a signed in registered user to rate eCards.');
}    

function RateContent(rv,rtid) {
    dojo.debug("RateContent(" + rv + ")");
    //Build the Content
    var ratingdata = {
                  'clientnamespaceid': g_mapinitdata[ 'clientnamespaceid' ],
                  'value': rv,
                  'ratingtypeid': rtid,
                  'thingid': thingid,
                  'customernumber': g_mapinitdata[ 'custnum' ],
                  'sitegroup': g_mapinitdata[ 'sitegroup' ]
                  };

    hmac_sig_qs = unescape(dojo.io.argsFromMap(ratingdata));
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    dojo.debug("hmac_sig: ", hmac_sig);

    ratingdata['hmac'] = hmac_sig;
    ratingdata['f']    = 'RateThing';
    if (g_userrated === true) { ratingdata['f'] = 'UpdateThingRating'; }

    var bind = {'content':ratingdata,'load':ratingLoad,'error':crtErr};
    var retval = submit_request(bind);
}

function UnrateContent(rtid) {
    dojo.debug("UnrateContent(" + rtid + ")");
    //Build the Content
    var ratingdata = {
                  'clientnamespaceid': g_mapinitdata[ 'clientnamespaceid' ],
                  'ratingtypeid': rtid,
                  'thingid': thingid,
                  'customernumber': g_mapinitdata[ 'custnum' ],
                  'sitegroup': g_mapinitdata[ 'sitegroup' ]
                  };

    hmac_sig_qs = unescape(dojo.io.argsFromMap(ratingdata));
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    dojo.debug("hmac_sig: ", hmac_sig);

    ratingdata['hmac']      = hmac_sig;
    //ratingdata['pd_nogzip'] = 1;
    ratingdata['f']         = 'UnrateThing';

    var bind = {'content':ratingdata,'load':ratingLoad,'error':crtErr};
    submit_request(bind);
}

function UpdateContentRating(rv,rtid) {
    dojo.debug("UpdateThingRating(" + rv + ")");
    //Build the Content
    var ratingdata = {
                  'clientnamespaceid': g_mapinitdata[ 'clientnamespaceid' ],
                  'value': rv,
                  'ratingtypeid': rtid,
                  'thingid': thingid,
                  'customernumber': g_mapinitdata[ 'custnum' ],
                  'sitegroup': g_mapinitdata[ 'sitegroup' ]
                   };

    hmac_sig_qs = unescape(dojo.io.argsFromMap(ratingdata));
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    dojo.debug("hmac_sig: ", hmac_sig);

    ratingdata['hmac'] = hmac_sig;
    ratingdata['f']    = 'UpdateThingRating';

    submit_request({'content':ratingdata});
}

function RateComment(ucid,rv,ac) {
    // @ucid -- UserCommentID from database
    // @rv   -- Rating value (currently only 1 or 0)
    // @ac   -- Abuse Count (optional)
    //Build the Content
    var ratingdata = {
                  'value': rv,
                  'ratingtypeid':3,
                  'commentid': ucid,
                  'customernumber': g_mapinitdata[ 'custnum' ],
                  'sitegroup': g_mapinitdata[ 'sitegroup' ]
                  };

    hmac_sig_qs = unescape(dojo.io.argsFromMap(ratingdata));
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    dojo.debug("hmac_sig: ", hmac_sig);

    ratingdata['hmac'] = hmac_sig;
    ratingdata['f']    = 'RateComment';

    var bind = {'content':ratingdata,'load':gotRCData,'error':crtErr,'sync':true};
    submit_request(bind);
    if ((rv === 0) && (g_ajax_error === false)) {
        _report_abuse(ratingdata);
        UpdateCommentDisplay('commentlist',null);
        loadCRTData();
    }
}

function _report_abuse(ratingdata) {
    dojo.debug('Start _report_abuse');
    var emaildata = {
                      'site'          : g_mapinitdata['site'],
                      'prodnum'       : g_mapinitdata['prodnum'],
                      'ratingtypeid'  : ratingdata['ratingtypeid'],
                      'commentid'     : ratingdata['commentid'],
                      'customernumber': ratingdata['customernumber'],
                      'sitegroup'     : ratingdata['sitegroup']
                    };
    hmac_sig_qs = unescape(dojo.io.argsFromMap(emaildata));
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    
    emaildata['hmac'] = hmac_sig;
    emaildata['f'] = 'report_abuse';

    var bind = {'content':emaildata,
                'load':gotRCData,
                'error':crtErr,
                'url':'/share/crt/crtnc4beta.pd',
                'sync':true};
    submit_request(bind);
}

function TagContent(tv) {
    //Build the Content
    taggingdata = {
                  'sitegroup': g_mapinitdata[ 'sitegroup' ],
                  'customernumber': g_mapinitdata[ 'custnum' ],
                  'thingid': thingid,
                  'tagname': tv,
                  'clientnamespaceid': g_mapinitdata[ 'clientnamespaceid' ]
                  };

    hmac_sig_qs = unescape(dojo.io.argsFromMap(taggingdata));
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    dojo.debug("hmac_sig: ", hmac_sig);

    taggingdata[ 'hmac' ] = hmac_sig;
    taggingdata[ 'f' ]    = 'Tag';

    submit_request({'content':taggingdata});
}

function CreateComment() {
    UpdateCommentStatus('',false);
    rv = dojo.byId('commenttext').value;
    un = dojo.byId('commentname').value;
    if (un === '') {
        UpdateCommentStatus('Your comment could not be posted for the following reason:', true);
        UpdateCommentStatus('<br>You did not enter a name',true,true);
        return;
    }
    if (rv === '') {
        UpdateCommentStatus('Your comment could not be posted for the following reason:', true);
        UpdateCommentStatus('<br>You did not enter a comment',true,true);
        return;
    }
    //Build the Content
    var commentdata;
    commentdata = {
                  'username': un,
                  'comments': rv,
                  'thingid': thingid,
                  'clientnamespaceid': g_mapinitdata[ 'clientnamespaceid' ],
                  'customernumber': g_mapinitdata[ 'custnum' ],
                  'sitegroup': g_mapinitdata[ 'sitegroup' ]
                  };

    // The following is a kluge to handle the difference in the calcs for hmac
    hmac_sig_qs = dojo.io.argsFromMap(commentdata);
    hmac_sig_qs = unescape(hmac_sig_qs);
    dojo.debug('hmac_sig_qs: ' + hmac_sig_qs);
    hmac_sig = dojo.crypto.MD5.getHMAC(hmac_sig_qs, "crt", dojo.crypto.outputTypes.Hex);
    dojo.debug("hmac_sig: ", hmac_sig);

    commentdata['hmac'] = hmac_sig;
    //commentdata['pd_nogzip'] = 1;
    commentdata['f'] = 'Comment';

    var bind = {'content':commentdata,'load':commentLoad,'error':crtErr};
    submit_request(bind);
}

function ratingLoad(type, data, evt) {
    try {
        loadCRTData(gotRData,crtErr);
    } catch(e) {
        dojo.debug(e.name + ': ' + e.message);
    }
}

function commentLoad(type, data, evt) {
    try {
        dojo.debug('data: ' + data.toString());
        if (data.error !== undefined) {
            var es = data.error.toLowerCase();
            dojo.debug('es: ' + es);
            UpdateCommentStatus('Your comment could not be posted for the following reason:', true);
            if (dojo.string.has(es,'words')) {
                UpdateCommentStatus('<br>Inappropriate Language', true,true);
            } else if (dojo.string.has(es,'chars')) {
                UpdateCommentStatus('<br>Disallowed Characters&nbsp;&nbsp;<i>@ # $ % ^ & * ( ) < > +</i>', true,true);
            } else if (dojo.string.has(es,'urls')) {
                UpdateCommentStatus('<br>Hyperlinks/Internet Addresses are not allowed.', true,true);
            } else if (dojo.string.has(es,'unique constraint')) {
                UpdateCommentStatus('You appear to have already posted a comment for this product.', true);
            }
        } else {
            var new_comment = new Object();
            new_comment.USERCOMMENTID = data.valueOf();
            new_comment.COMMENTS = dojo.byId('commenttext').value;
            new_comment.USERNAME = dojo.byId('commentname').value;
            var cmt_nodes = dojo.html.createNodesFromText(make_comment_html(new_comment));
            UpdateCommentDisplay('commentlist', cmt_nodes[0]);
            dojo.byId('commenttext').value = '';
            switchArrayOff([ 'agi-commentform','befirst','yourcomment' ]);
        }
    } catch(e) {
        dojo.debug(e.name + ': ' + e.message);
    }
}

function crtErr(type, errObj) {
    var es = "";
    for (var v in errObj) {
        es += v + ": " + errObj[ v ] + " ";
    }
    UpdateCommentStatus('An error occurred attempting to record your comment/rating.', true);
    g_ajax_error = true;
    dojo.debug('CRT Error: ' + es);  
}

function displayTabs(tab_map) {
    var node;
    // Look for name of Node to show
    var show_nodes = tab_map[ 'on' ];
    dojo.debug('show_nodes: ' + show_nodes.toString());
    if (show_nodes instanceof Array) {
        // Look for array of names of Nodes to hide
        var hide_nodes = tab_map[ 'off' ];
        dojo.debug('hide_nodes: ' + hide_nodes.toString());
        if (hide_nodes instanceof Array) {
            for (var i=0;i<show_nodes.length;i++) {
                node_name = show_nodes[ i ];
                dojo.html.show(node_name);
            }
            for (var j=0;j<hide_nodes.length;j++) {
                node_name = hide_nodes[ j ];
                dojo.html.hide(node_name);
            }
        }
    }
}

function is_over_abuse_threshold(comment) {
    dojo.debug('Checking is_over_abuse_threshold...');
    var diff = 0;
    var cmt_ratings;
    var cmt_ucid = comment.USERCOMMENTSTATUSID;
    if (comment.COMMENTRATINGS !== null) { cmt_ratings = comment.COMMENTRATINGS; }
    if (cmt_ratings !== null) {
        for (var i=0;i<cmt_ratings.length;i++) {
            if ((cmt_ratings[i].RATINGTYPEID == 3) &&
                    ((cmt_ucid == 1) || (cmt_ucid == 5)) ){
                diff = (cmt_ratings[i].NUM_RATINGS - cmt_ratings[i].TOT_SCORE);
                dojo.debug('Diff: ' + diff);
                break;
            }
        }
    }
    var over = _is_abusive(diff, comment.USERCOMMENTSTATUSID);
    dojo.debug('is_over_abuse_threshold: ' + over);
    return over;
}

function _is_abusive(count, status) {
    var result = Boolean(false);
    if ((count >= g_mapinitdata['abusethreshold'])&&(status==1)){result=true; }
    else if ((count>=(2*g_mapinitdata['abusethreshold']))&&(status==5)){result=true;}
    else {result = false;}
    dojo.debug('_is_abusive('+count+','+status+')='+result);
    return result;
}    

function grab_history(curr_prod,memnum,show,url_ajax){
    var request = new Object();
    // See if an overriding ajax url is passed in.
    if (!url_ajax) { url_ajax = khost + '/productinfo.pd'; }
    if (!show) { show = false; } // Just making it rigorously correct
    dojo.debug("curr_prod: " + curr_prod + " | custnum: " + memnum + "| show: " + show);
    if ((memnum !== null) && (memnum > 0) && (show===true)) {
        request[ "current" ]   = curr_prod;
        request[ "custnum" ]   = memnum;
        dojo.debug("request: " + dojo.io.argsFromMap(request));
    
        var bind = {'content': request, 'load': historyHandler, 'url': url_ajax};
        submit_request(bind);
    } else {
        var msg = {'lstOrderUsage': [{'RECIPIENT':'Temporarily Unavailable','DELIVDATE':''}]};
        write_history(msg);
    }
}

// writeHistory is just an event handler wrapper for write_history
function historyHandler(type, data, evt){
    write_history(data);
}
    
function write_history(data) {
    var histlist;
    histlist = data.lstOrderUsage;
    histlist = histlist.slice(0,3); //Max 3 sent history shown.
    var histlen = histlist.length;
    dojo.debug("starting writeHistory");
    if ((histlist !== 'undefined') && (histlen > 0)) {
        dojo.debug("HistList: " + histlen);
        var html = '';
        var root = dojo.byId('agi-display-sent');
        var unter_root = dojo.byId('to-outbox');

        if ((root !== null) && (root !== 'undefined')) {
            for (var i=0;i<histlen;i++) {
                var name = histlist[i].RECIPIENT;
                dojo.debug("name: " + name);
                var date = histlist[i].DELIVDATE;
                dojo.debug("date: " + date);
                var sep  = '';
                if (date) { if (date.length > 0) { sep = ':'; } }
                html += '<li><strong>' + name + sep + '</strong> ' + date + '</li>';
            }
            html = '<ul id="display-sent">' + html + '</ul>';

            var arr_nodes = dojo.html.createNodesFromText(html);
            var nodelen = arr_nodes.length;
            if (nodelen > 0) {
                var myhist = root.insertBefore(arr_nodes[0],unter_root);
            }
        }
    }
}

function limitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum-1);
        alert('Comments are limited to ' + limitNum + ' characters.');
	} 
}

function ConfirmTrigger(url, attr) {
  var loc = '/ecards/formconfirm.pd';
  var attrs = {'width':440,'height':300,'hideloading':true};
  if(url) loc = url;
  if(attr) attrs = attr;

  var ftrigger = this;
  this.show = function(name,val) {
    var url = loc;
    if (name && val) {
        url += '?'+name.toString()+'='+escape(val);
    }
    lightbox(url, attrs);
  };
  this.hide = function() {
    hideLightbox();
  };
}

function contentIsMature(){
    //for now, a rinky-dink global var
    return is_mature;
}

/**
* Should this user see mature content without verification?
* returns true or false
*/
function userMayViewMature(){
    //check for the temporary, single-use magic cookie
    if( MagicCookie.getCookieValue('mature') == '1'){
        MagicCookie.setCookieValue('mature', '');
        return true;
    }

    //check for the customer cookie setting
    mature = AGCookie.getCookieValue('customer','mature');  
    if(mature == '1'){
        return true;
    }
    else{
        return false;
    }
}

/**
* If the content is mature, and the user has opted to filter it out,
* hide the card display area and prompt the user for confirmation
*/
function init_mature_filter(){
    if (contentIsMature() && !userMayViewMature()){
       hide_card();
       show_mature_form();
    }
}

/**
* Show the (modal) dialog to ask the user to confirm
* seeing mature content.
*
*/
function show_mature_form(){
    var card_node = document.getElementById('agi-ecard');
    var params = {'hideloading':true, 'callingObj':card_node,'top':0, 'left':0,'position':'relative'};
    url = khost + "/mature_form";
    if (!AGCookie.getCookieValue('customer','memnum') ){
        url += '_nonmember'; 
    }
    url += ".pd";
    lightbox(url ,params ,'',false);
}

/**
* A signed in user has asked to remember their "allow" setting for mature
*
*/
function allow_mature(){
    var customernumber = AGCookie.getCookieValue('customer','memnum');
    var remember_check = document.getElementById('remember');
    url = ahost + '/setmature.pd?value=Y';
    if (customernumber !== null  && customernumber !== '0' && remember_check.checked ){
        //signed in and checked "remember my setting"
        dojo.io.bind( {url:url, load:saved_mature, mimetype:"text/plain"});
    }
    else{
        //not signed in or didn't check "remember" give a 1-shot cookie & reload
        MagicCookie.setCookieValue('mature','1');
        location.reload();
    }
}

/**
* the async call to update user info is done.
* reload the page with new and improved cookies
*/
function saved_mature(){
    location.reload();
}

/**
* Hide the product html on the page
*/
function hide_card(){
    card_node = document.getElementById('agi-ecard');
    card_node.innerHTML = "<div style='height:440px; width:575px; background:gray;'>&nbsp;</div>";
}

var confirm_trigger = new ConfirmTrigger();
confirm_abuse = function (name,val) { confirm_trigger.show(name,val); };

