// Copyright (c) 2009 by Jeff Weisberg
// Author: Jeff Weisberg <jaw @ tcp4me.com>
// Created: 2009-Feb-25 18:20 (EST)
// Function: misc js
//
// $Id: lib.js,v 1.22 2011/03/28 16:24:22 jcap Exp $

var ac_debug = false;
var ac_spin_count = 0;

function ac_dump_obj(name, o){
    var txt = name + ":\n";
    var k;
    for (k in o){
        txt = txt + '  ' + k + ' => ';
        if( o[k] == undefined ){
            txt = txt + '#undef';
        }else if( typeof(o[k]) == 'function' ){
            txt = txt + 'function()';
        }else if( typeof(o[k]) == 'object' ){
            txt = txt + '{object}';
        }else{
            txt = txt + o[k];
        }
        txt = txt + "\n";
    }
    console.log( txt );
}

function ac_escape_text(t){
    if(!t) return t;
    t = t.replace(/&/g, '&amp;');
    t = t.replace(/</g, '&lt;');
    t = t.replace(/>/g, '&gt;');
    return t;
}



function ac_ajax_spinner(ep){
    var im = dojo.byId('ajaxspinner');
    if(!im) return;

    if(ep){
        im.style.display = 'inline';
    }else{
        im.style.display = 'none';
    }
}

function ac_ajax_error(res){
    var sp = dojo.byId('ajaxmessage');
    var msg;
    var loc;

    if( res && (typeof(res) == 'object') ){
        if( ac_debug ) ac_dump_obj('error obj', res);
        msg = res.error_message;
        loc = res.redirect;
        if( !msg ) msg = res;
    }else{
        msg = res;
    }

    if( /Unable to load .* status:0/.test(msg) ) return;

    if( !sp ){
        if(msg) alert('ERROR: ' + msg);
        return;
    }
    if(msg){
        sp.innerHTML = msg;
        sp.style.display = 'inline';
    }else{
        sp.style.display = 'none';
    }

    if(loc) document.location = loc;
}

function ac_ajax_post(url, data, onComplete, onError){

    ac_ajax_error(false);
    ac_ajax_spinner(true);

    if( ! data.fmt ) data.fmt = 'json';

    if( ac_debug ){
        console.log('ac_ajax_post to ' + url);
        ac_dump_obj('post', data);
    }

    dojo.xhrPost({
        url:            url,
        content:        data,
        handleAs:       'json',
        error:   function(result){
            if( ac_debug ) console.log('ac_ajax_post error ' + result);
            ac_ajax_spinner(false);
            onError(result);
        },
        load:    function(result){
            if( ac_debug ){
                console.log('ac_ajax_post ok');
                ac_dump_obj('result', result);
            }
            ac_ajax_spinner(false);
            if(result && ! result.error ){
                onComplete(result);
            }else{
                onError(result);
            }
        }
    });
}

function ac_ajax_get(url, data, onComplete, onError){
    var ret;

    ac_ajax_error(false);
    ac_ajax_spinner(true);

//    if( ! data.fmt ) data.fmt = 'json';

    if( ac_debug ){
        console.log('ac_ajax_get to ' + url);
        ac_dump_obj('args', data);
    }

    dojo.xhrGet({
        url:            url,
        content:        data,
        handleAs:       'json',
        error:   function(result){
            if( ac_debug ) console.log('ac_ajax_get error ' + result);
            ac_ajax_spinner(false);
            onError(result);
        },
        load:    function(result){
            if( ac_debug ){
                console.log('ac_ajax_get ok');
                ac_dump_obj('result', result);
            }
            ac_ajax_spinner(false);
            if(result && ! result.error ){
                onComplete(result);
            }else{
                onError(result);
            }
        }
    });
}

function ac_sync_get(url, data, onError){
    var ret;

    ac_ajax_error(false);
    ac_ajax_spinner(true);

    if( ! data.fmt ) data.fmt = 'json';

    if( ac_debug ){
        console.log('ac_sync_get to ' + url);
        ac_dump_obj('post', data);
    }

    dojo.xhrGet({

        url:        url,
        content:    data,
        sync:       true,
        handleAs:   'json',
        error:   function(result){
            if( ac_debug ) console.log('ac_sync_get error ' + result);
            ac_ajax_spinner(false);
            onError(result);
        },
        load:   function(result){
            if( ac_debug ){
                console.log('ac_sync_get ok');
                ac_dump_obj('result', result);
            }
            ac_ajax_spinner(false);
            if(result && ! result.error ){
                ret = result;
            }else{
                onError(result);
            }
        }
    });

    return ret;
}

function ac_check_passwd(val){
    var msg;

    if( val.length < 6 ){
        msg = 'please choose a longer password';
    }
    if( val == 'password' || val == 'abc123' || val == '123abc' || val == '123456' ){
        msg = 'please choose a more secure password';
    }

    return msg;
}


function ac_regexp_domainname() {
  // host can't start or end with - 
  var label_re = '[A-Za-z0-9](?:[A-Za-z0-9\\-]*[A-Za-z0-9])?';
  var tld_re = '(?:[A-Za-z]{2}|com|org|net|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|pro|tel|travel|xxx)';

  //          at least one label .    tld
  return '(?:' + label_re + '\\.)+' + tld_re;
}


function ac_regexp_emailaddress() {
  // rfc 5322
  var atext    = "[A-Za-z0-9!#$%&'*+\\/=?^_`{|}~\\-]";
  var local_re = atext + '+(?:\\.' + atext + '+)*';
  
  return local_re + '@' + ac_regexp_domainname();
}

function ac_validate_emailaddress(email) {
  if( ! email ) return 1;
  var reg   = "^" + ac_regexp_emailaddress() + "$";    

  // catch common misspellings and general email pattern
  if (!  email.toLowerCase().match('(gmail|yahoo|hotmail).c[om]$') && email.toLowerCase().match(reg)) {
    return 1;
  }

  return 0;
}

function ac_iso_date(date_obj) {
    var month = date_obj.getMonth()+1;
    if (month < 10) month = "0" + month;
    var day = date_obj.getDate();
    if (day < 10) day = "0" + day;
    return date_obj.getFullYear() + '-' + month + '-' + day;
}

// SEE ALSO THE COMPANION MASON COMP IN htdocs/portal/sys/normalized-ttr
function ac_normalized_ttr(solved, ver_served, a, N, bucket) {
    // ver_served == served - expired 
    if (bucket) {
        bucket = 86400 / bucket;
    } else {
        bucket = 1;
    }

    return ((bucket * solved) + (a * N))   /   ((bucket * ver_served) + N);
}

