/*
    javascript code for all pages of freshfaves.com
 
*/


// change this line to suit your account, if you are setting up a new account
//
var dbUrl = "http://www.rdbhost.com/db/p0000000849";


//  hovering object
//
function hoverthing(subj,delay) {
    
    var hoverer = this; // save object 'this'
    var hoverct = 0;
    var timeout = '';
    if (!delay) delay = 1250;
    this.popupdelay = function(e) {
        hoverct = hoverct+1;
        timeout = window.setTimeout(function(){
            hoverct = hoverct-1;
            hoverer.popupmenu(e);
        },delay);
    }; 
    this.popupmenu = function(e) {
        hoverct = hoverct+1;
        if (hoverct>0) {
            $(subj).show();
            $(subj).hover(hoverer.popupmenu,hoverer.nopopup);
        };
    }
    this.nopopup = function() {
        window.clearTimeout(timeout);
        hoverct = hoverct-1;
        if (hoverct <= 0) {
            $(subj).hide();
        }
    }
    this.bindhover = function(tag,prefunc) {
        $(tag).hover( function(e) {
                        if (hoverct == 0) {
                            prefunc(e);
                            hoverer.popupdelay(e);
                        };
                      },
                      hoverer.nopopup
        );
    };
}

// utility functions

function delete_entry(fid,key) {
    var params = {kw: 'deletefave', format: 'jsonp-easy',
                  arg000: fid, arg001: key };
    $.ajax({url: dbUrlCB,
            type: 'GET',
            data: params,
            dataType: "jsonp",
            success: function (d) {
               fill_list_display(id,true);
            }
    });
    return false;
};


// functions for list page
//
var dbUrlCB = dbUrl+"?callback=?";
var id = '';

function prepare_menu(e) {
    var lid = $(e.target).parent().siblings(':first').html();
    var key = $.cookie('freshfaveskey');
    $('#atcursor').css({left:e.pageX-15,
                        top:e.pageY-15 });
    $('#acdelete').unbind('click').click(function(e){
        var ok = confirm('are you sure?');
        if (ok) {
            return delete_entry(lid,key);
        }
        return false;
    });
    $('#acedit').attr('href','/edit.html?id='+lid);
};

function prepare_copyto(e) {
    // get url and title from list display table (other columns)
    var url = $(e.target).parent().find('.link').attr('href');
    var tit = $(e.target).parent().next().find('.linkname').html();
    // set position of copyto display div/table
    $('#copyto').css({left:e.pageX-15,
                        top:e.pageY-15 });
    // create and bind off-site bookmarklets
    var delurl = "javascript:(function(){var f='http://delicious.com/save?url='+encodeURIComponent(\'~~u~\')+'&title='+encodeURIComponent(\'~~t~\')+'&v=5&';var a=function(){if(!window.open(f+'noui=1&jump=doclose','deliciousuiv5','location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550'))location.href=f+'jump=yes'};if(/Firefox/.test(navigator.userAgent)){setTimeout(a,0)}else{a()}})()";
    delurl = delurl.replace('~~u~',url).replace('~~t~',tit);
    $('#copyto #delicious').attr('href',delurl);
    var googurl = 'javascript:(function(){var a=window,b=document,c=encodeURIComponent,d=a.open("http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk="+c(\'~~u~\')+"&title="+c(\'~~t~\'),"bkmk_popup","left="+((a.screenX||a.screenLeft)+10)+",top="+((a.screenY||a.screenTop)+10)+",height=420px,width=550px,resizable=1,alwaysRaised=1");a.setTimeout(function(){d.focus()},300)})()';
    googurl = googurl.replace('~~u~',url).replace('~~t~',tit);
    $('#copyto #googlebm').attr('href',googurl);
    var suurl = 'http://www.stumbleupon.com/submit?url=~~u~';
    suurl = suurl.replace('~~u~',encodeURIComponent(url));
    $('#copyto #stumble').attr('href',suurl);    
    var diggurl = "http://digg.com/submit?url=~~u~&title=~~t~";
    diggurl = diggurl.replace('~~u~',encodeURIComponent(url)).replace('~~t~',encodeURIComponent(tit));
    $('#copyto #digg').attr('href',diggurl);    
    var sdurl = "http://slashdot.org/bookmark.pl?url=~~u~&title=~~t~"; 
    sdurl = sdurl.replace('~~u~',encodeURIComponent(url)).replace('~~t~',encodeURIComponent(tit));
    $('#copyto #slashdot').attr('href',sdurl); 
    var yahoourl = "http://myweb2.search.yahoo.com/myresults/bookmarklet?u=~~u~&t=~~t~";
    yahoourl = yahoourl.replace('~~u~',encodeURIComponent(url)).replace('~~t~',encodeURIComponent(tit));
    $('#copyto #yahoo').attr('href',yahoourl);    
    var fburl = "http://www.facebook.com/sharer.php?u=~~u~"
    fburl = fburl.replace('~~u~',encodeURIComponent(url));
    $('#copyto #facebook').attr('href',fburl);    
};

function linkclicked(ev) {
    // update clicked timestamp (to now) on bookmark
    // var id = parseInt($(ev.target).parent().siblings(':first').html());
    var linkval = ev.target.href.replace(/\/$/,'');  
    var params = {kw: 'click', 
                  format: 'jsonp-easy',
                  arg000: linkval,
                  arg001: id };
    $.ajax({url: dbUrlCB,
            type: 'GET',
            //async: false,
            data: params,
            dataType: "jsonp",
            success: function (d) {
              window.location = ev.target
            }
    });
    return false;
};

function fill_list_display(uid,isowner) {
    // get list from server, display as table;
    // var id = uid, dsplnk;
    id = uid;
    $.getJSON(dbUrlCB,
        {kw:'list', arg000:id, format:'jsonp-easy'},
        function(d) {
            $('#listtab').empty();
            var row = ''; var link; var titl;
            for (r in d['records']['rows']) {
                dr = d['records']['rows'][r];
                row = $('<tr class="row0"></tr>');
                row.append($('<td rowspan=3 style="display:none"></td>').html(dr["id"]));
                titl = dr["title"] || dr["link"];
                if (titl.length > 75) titl = titl.substring(0,75);
                dsplnk = dr["link"];
                if (dsplnk.length > 85) dsplnk = dsplnk.substring(0,85);
                link = '<a class="link" href="'+dr["link"]+'">'+(titl)+'</a>';
                row.append($('<td></td>').html(link));
                row.append($('<td rowspan=3 class="copyto"></td>').html('<a href="#">copy to</a>'));
                row.append($('<td rowspan=3 class="cdate"></td>').html(dr["added"]));
                row.append($('<td rowspan=3 class="rdate"></td>').html(dr["clicked"]));
                $("#listtab").append(row);
                row = $("<tr></tr>");
                row.append($('<td class="linkname"></td>').html(dsplnk));
                $("#listtab").append(row);
                row = $("<tr></tr>");
                row.append($('<td class="notes"></td>').html(dr["notes"] || ''));
                $("#listtab").append(row);
            };
            $('.link').click(linkclicked);
            if (isowner) {
                var hoverer = new hoverthing('#atcursor',1250);
                hoverer.bindhover('.link',prepare_menu);
            }
            var hoverc2 = new hoverthing('#copyto',500);
            hoverc2.bindhover('.copyto',prepare_copyto);
        }
    );
};

/*
 
   functions for newfave page
   
*/

function addacct(key,tolist) {
    // create a new acct, then add fave for account
    $.getJSON(dbUrlCB,
            {kw:'addaccount', arg000: key, format:'jsonp-easy'},
            function(d) {
                if (d['status'][0] == 'error') {
                    alert('err: '+d['error'][0]+' '+d['error'][1])
                } else {
                    // if acct added, add fave
                    addfave(tolist);
                }
            }
    );        
};

function act_on_id(key,dothis) {
    // get id for user from db, then 'dothis' with it
    var id = '';
    $.getJSON(dbUrlCB,
            {kw:'getid', arg000: key, format:'jsonp-easy'},
            function(d) {
                if (d['status'][0] == 'error') {
                    alert('err: '+d['error'][0]+' '+d['error'][1])
                    return;
                } else if (!d['records']['rows']) {
                    //alert();
                    alert('You do not have a favelist, yet.\n'+
                          'Add a page to create the list');
                    return;
                } else {
                    //alert('locate: '+window.location);
                    id = d['records']['rows'][0]['id'];
                    //window.location = '/list.html?id='+id;
                    dothis(id);
                }
            }
    );
    return;
};
function showlist(key) {
    // get id for user from db, then redirect to page
    act_on_id(key,
              function(id) {
                var target = '/list.html?id='+id;
                window.location = target;
              }
    );
    return;
};


function addfave(tolist) {
    // add the fave to the db, and jump to page or to list
    // depending on param 'tolist'
    if (ct > 2) return; ct += 1;
    var key = $('#key').val();
    var link = $('#url').val();
    link = link.replace(/\/$/,'');  // remove end '/'
    var title = $('#title').val();
    var notes = $('#notes').val();
    $.getJSON(dbUrlCB,
            {  kw:'addfave',
               arg000: link, arg001: title,
               arg002: notes, arg003: key,
               format:'jsonp-easy' },
            function(d) {
                if (d['status'][1] == 'OK') {
                    if (d['row_count'][0] == 0) {
                        // addacct will call addfave after adding acct
                        addacct(key,tolist);
                    } else if (tolist) {
                        showlist(key);
                    } else {
                        window.location = link;
                    }
                }
                else if (d['status'][0] == 'error' && d['status'][1] == 'IntegrityError') {
                    alert('this link apparently already in your faves list');
                    showlist(key);
                }
                else {
                    alert('link was not added. error: '+d['status'][1]);
                }
            }
    );
    // purge old records for all users. ignore result returned.
    $.getJSON(dbUrlCB, {kw: 'clean', format:'jsonp-easy'}, function(d) {} );
    return;
};


/*
  
  for sharing.html
  
*/

function setviewurl(key) {
    // create list-view url, and insert in page
    act_on_id(key,
              function(id) {
                if (d['status'][0] == 'error') {
                    alert('err: '+d['error'][0]+' '+d['error'][1]);
                    return;
                } else {
                    id = d['records']['rows'][0]['id'];
                    $('#readurl').attr('href','/list.html?id='+id)
                        .html('http://www.freshfaves.com/list.html?id='+id);
                }
              }
    );
    return id;
};


/*
  
  for edit.html
  
*/

function fill_edit_display(faveid) {
    // get one record from database, show in edit form
    $.getJSON(dbUrlCB,
        {kw: 'onefave', arg000: faveid, format: 'jsonp-easy'},
        function(d) {
            var row = '', link, titl, notes, dr, r; 
            dr = d['records']['rows'][0];
            link = dr['link'];
            titl = dr['title'];
            notes = dr['notes'];
            $('#title').val(titl);
            $('#url').val(link);
            $('#notes').val(notes);
            $('#faveid').val(faveid);
        }
    );
};

function updatefave(key) {
    // add the fave to the db, and jump to page or to list
    // depending on param 'tolist'
    var link = $('#url').val();
    link = link.replace(/\/$/,'');  // remove end '/'
    var title = $('#title').val();
    var notes = $('#notes').val();
    var faveid = $('#faveid').val();
    if (!faveid) {
        alert('problem! no faveid provided.');
        return;
    }
    //alert('addfave: '+key);
    $.getJSON(dbUrlCB,
            {  kw:'editfave',
               arg000: link, arg001: title, arg002: notes,
               arg003: faveid, arg004: key,
               format:'jsonp-easy' },
            function(d) {
                if (d['status'][1] == 'OK') {
                    showlist(key);
                } else {
                    alert('bookmark was not updated. error: '+d['status'][1]);
                }
            }
    );
    return;
};



