/**
 *
 *  Our (very small) collection of globals:
 *
 */

// root Wellspring object -- everything else builds on this
WS = {};
/**
 *
 *  End of globals
 *
 */


(function($){

// core namespaces
WS.app = {};
WS.dom = {};
WS.util = {};
WS.locale = {};
WS.form = {};
WS.ajax = {};
WS.gui  = {};
WS.page = {}; // namespace for 1-off, per page functions and vars.

WS.util.ident = function () { return arguments;}

// Firebug support
if (typeof console == 'undefined') {
    console = {};
}
var console_support = [
    'log', 'debug', 'dir', 'dirxml', 'count',
    'info', 'warning', 'error',
    'assert',
    'time', 'timeEnd',
    'profile', 'profileEnd', 'trace'];
for(var i in console_support) {
    if (typeof console[console_support[i]] == 'function') {
        WS.util[console_support[i]] = console[console_support[i]];
    } else {
        WS.util[console_support[i]] = WS.util.ident;
    }
}
delete console_support;
WS.log = WS.util.log ;

/**
 * Initialize the dynamic WS variables like locale and baseURL
 */

$(document).ready(function() {
    var body = $('body');
    // set up app and locale values
    WS.app.base_url = body.attr('data-application-base-url');
    WS.locale.decimal_separator = body.attr('data-locale-decimal-separator');
    WS.locale.thousands_separator = body.attr('data-locale-thousands-separator');
    WS.locale.currency_symbol = body.attr('data-locale-currency-symbol');

    // set up auto-hilite
    var hiliteOn = function() {
        $(this).addClass('highlight');
    };
    var hiliteOff = function() {
        $(this).removeClass('highlight');
    };
    $('.highlight_row tr').hover(hiliteOn, hiliteOff);
    $('div#content').hover(hiliteOff,hiliteOff);

   // set up qtip/helptip
   $('.ui-qtip').each(function(i, qt) {
       var $qt = $(qt);
       var msg = $qt.attr('data-qtip-msg');
       var opts = {
               background: '#E8E7F0',
               border: {
                   width: '1px',
                   color: '#E8E7F0'
               }
       }
       if(!$.browser.msie) opts.border.radius = 8;
       $qt.qtip({
           content: msg,
           show: 'focus',
           hide: 'unfocus',
           style: opts
       });
   });
   $('.ui-qtip-json').each(function(i, qt) {
       $qt = $(qt);
       var msg = $qt.attr('data-qtip-msg');
       var url = $qt.attr('data-qtip-url');
       $qt.qtip({
            msg: msg,
            content: {
                url: url,
                msg: msg
            },
            show: 'click',
            hide: 'unfocus',
            style: {
                background: '#E8E7F0',
                border: {
                    width: '1px',
                    radius: 8,
                    color: '#E8E7F0'
                }
            }
       });
   });
});

/**
 * Common utility functions
 */

/**
 * parse string values to numbers, locale-aware (and ignoring invalid symbols, if any)
 *
 * @param String amount to parse
 * @param float (optional) amount to use if parsed value isNaN
 * @return int|float if parsed correctly or ifNaN is specified, NaN otherwise
 */
WS.util.parseFloatLocale = function(amount, ifNaN ) {

    var re = new RegExp("[^-+0-9" + WS.locale.decimal_separator + "]", "g");
    amount = amount.replace(re, "");
    if(WS.locale.decimal_separator != '.') {
        amount = amount.replace(WS.locale.decimal_separator, ".");
    }

    var flt = parseFloat(amount);
        if( isNaN(flt) && (typeof ifNaN != 'undefined' )) {
            return ifNaN;
        }

        return flt;
}

// format number as locale-aware string
WS.util.formatFloatLocale = function(amount, decimalPlaces) {
    var re = new RegExp("(\\d)(\\d{3})(\\" + WS.locale.thousands_separator + "|$)");
    var remaining = amount;
    if(decimalPlaces == undefined) {
        decimalPlaces = 2;
    }
    amount = amount.toFixed(decimalPlaces);
    var decimal = amount.lastIndexOf(".");
    var wholePart = amount.substr(0, decimal);
    var fractionalPart = amount.substr(decimal + 1);
    while(remaining >= 1000.0) {
        wholePart = wholePart.replace(re, "$1" + WS.locale.thousands_separator + "$2$3");
        remaining = remaining / 1000.0;
    }
    return wholePart + WS.locale.decimal_separator + fractionalPart;
}

WS.util.toCurrency = function(amt) {
    return parseFloatLocale(form.amount.value).toFixed(2);
};

/**
 * Shared functions, included here for convenience
 */

// used by querybuilder alerts and by form letters
WS.util.insertText = function(formId, selector, value) {
    // private inner function
    var insertAtCursor = function(myField, myValue) {
       //IE support
       if (document.selection) {
          myField.focus();
          sel = document.selection.createRange();
          sel.text = myValue;
       }
       //MOZILLA/NETSCAPE support
       else if (myField.selectionStart || myField.selectionStart == '0') {
           var startPos = myField.selectionStart;
           var endPos = myField.selectionEnd;
           myField.value = myField.value.substring(0, startPos)
             + myValue
             + myField.value.substring(endPos, myField.value.length);
           myField.selectionEnd = endPos + myValue.length;
           myField.focus();
       } else {
          myField.val(myField.val() + myValue);
       }
    };

    var form = $('form#' + formId);
    var txtElem = form.find(selector);
    insertAtCursor(txtElem, "%(" + value + ")");
    txtElem.focus();
};

})(jQuery);