/*
 * Top Level JS namespace for all hgm js code
 */
var hgm = hgm || {};
if (typeof console == 'undefined') {
    var console = {};
    console.log = function () {

    };
}

// current lib version
hgm.version = '1.0';
// use local path or CDN, can also be overriden at the getLibPath level
hgm.useCDN = false;
// define local non-CDN path
hgm.localLibPath = '/wp-content/plugins/hgm/js/';
// define CDN js domain and path
hgm.cdnLibPath = 'http://js.hgmsites.net/';
// get library path based on internal useCDN default or user pref
hgm.getLibPath = function (useLocalLibs) {
    if (!useLocalLibs && this.useCDN) {
        return this.cdnLibPath + this.version + '/';
    }
    return this.localLibPath;
}
// load dependencies
hgm.depends = function (libraries, version) {
    // check that jquery is loaded
    if (!$) {
        throw('No jQuery found! please make sure jquery is loaded before using the hgm js lib');
    }
    for(var i in libraries) {
        lib = libraries[i];
        // check if plugins already loaded
        if(typeof $.fn[lib] != 'function') {
            $.ajax({
                async: false,
                url: this.getLibPath() + 'jquery.' + lib + '.min.js',
                dataType: 'script'
            });
        }
    }
}

//hgm.form($('#form'), {version: '1.0', rules: {}, messages: {}});

/* Adding form library */
hgm.qtip = function (element, errormessage) {
    if (!element) {
        throw('element param to hgm.qtip is not optional!');
    }
    // Verify/Get dependencies
    this.depends(['qtip']);
    return $(element).qtip({
        style: {
            padding: 5,
            background: '#FE511C',
            color: 'white',
            textAlign: 'center',
            border: {
                width: 5,
                radius: 10,
                color: '#FE511C'
            },
            tip: true,
            name: 'dark' // Inherit the rest of the attributes from the preset dark style
        },
        content: errormessage,
        position: {
            corner: {
                tooltip: 'topMiddle',
                target: 'bottomMiddle'
            }
        },
        show: {
            when: false,
            ready: true
        },
        hide: 'blur'
    });
};

hgm.form = function (jqObj, options) {
    if (!jqObj) {
        throw('jQObj param to hgm.form is not optional!');
    }
    // Verify/Get dependencies
    this.depends(['form', 'validate', 'qtip']);
    // Returns the validation rules from the user plus any defaults
    function getRules(options) {
        if (options && options.rules) {
            return options.rules;
        } else {
            return {};
        }
    }
    // Returns the validation messages from the user merged with any defaults
    function getMessages(options) {
        if (options && options.messages) {
            return options.messages;
        } else {
            return {};
        }
    }
    // Setup the validator/hint/submit handler
    var validator = jqObj.validate({
        submitHandler: function(form) {
            if(_gaq) {
                _gaq.push(['_trackEvent',jqObj.attr('id'), 'Form Submitted']);
            }
            $(form).ajaxSubmit({
                dataType: 'json',
                success: function(data) {
                    if (options && typeof options.submitHandler == 'function') {
                        options.submitHandler(data);
                    }
                }
            });
            return false;
        },
        errorClass: 'error',
        validClass: 'valid',
        onkeyup: false,
        highlight: function(element, errorClass, validClass) {
            $(element).parent().addClass(errorClass);
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parent().removeClass(errorClass);
            $(element).parent().find('ul.errors').remove();
        },
        rules: getRules(options),
        messages: getMessages(options),
        showErrors: function(errorMap, errorList) {
            // reset errors
            validator.validElements().removeClass('error');
            validator.validElements().addClass('valid');
            $('div.qtip').remove();
            var gotOneQtip = false;
            $.each(errorList, function (index, error) {
                if(_gaq) {
                    _gaq.push([
                        '_trackEvent',
                        "Pricequote",
                        $(error.element).attr('name') + ' Failed:' + $(error.element).val()
                    ]);
                }
                $(error.element).addClass('error');
                $(error.element).parent().addClass('error');
                $(error.element).removeClass('valid');
                if (!gotOneQtip) {
                    hgm.qtip(error.element, error.message);
                    $(error.element).qtip("show");
                    gotOneQtip = true;
                }
            });
        }
    });

    return validator;
};

