﻿
var utilities = {

    exceptions: {
        sessionEnded: 'Utilities.SessionEndedException',
        limitReached: 'Utilities.LimitReachedException',
        argumentInvalid: 'Utilities.ArgumentInvalidException',
        processAborting: 'Utilities.ProcessAbortingException',
        webException: 'System.Net.WebException'
    },

    wsPost: function(method, data, success, complete, error) {
        $.ajax({
            type: "POST",
            url: master.serviceUrl + method,
            data: (typeof data === 'undefined' || data == null) ? '{}' : $.toJSON(data),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                if (typeof success !== 'undefined' && success != null) {
                    success.call(this, data == null ? null : data.d);
                }
            },
            error: function(xhr) {
                if (typeof error !== 'undefined' && error != null) {
                    var exception = $.parseJSON(xhr.responseText);
                    if (exception.ExceptionType == utilities.exceptions.sessionEnded) {
                        window.location = '/';
                    } else {
                        if (!error.call(this, exception)) {
                            utilities.handleError(xhr);
                        }
                    }
                } else {
                    utilities.handleError(xhr);
                }
            },
            complete: function() {
                if (typeof complete !== 'undefined' && complete != null) {
                    complete.call(this);
                }
            }
        });
    },

    getView: function(page, success, complete, error) {
        $.ajax({
            type: 'GET',
            url: master.viewUrl + page + '.aspx',
            dataType: 'text',
            cache: false,
            contentType: 'text/html; charset=utf-8',
            success: function(data) {
                if (typeof success !== 'undefined' && success != null) {
                    success.call(this, data == null ? null : data);
                }
            },
            error: function(xhr) {
                if (typeof error !== 'undefined' && error != null) {
                    error.call(this, $.parseJSON(xhr.responseText).Message);
                } else {
                    utilities.handleError(xhr);
                }
            },
            complete: function() {
                if (typeof complete !== 'undefined' && complete != null) {
                    complete.call(this);
                }
            }
        });
    },

    isNumberKey: function(e) {
        var code = (e.which) ? e.which : e.keyCode;
        if (code > 31 && (code < 48 || code > 57)) {
            return false;
        }
        return true;
    },

    isNumericKey: function(e) {
        var code = (e.which) ? e.which : e.keyCode;
        if (code > 31 && (code < 48 || code > 57) && code != 44 && code != 46) {
            return false;
        }
        return true;
    },

    clearWord: function(obj, val) {
        if (obj.value == val) { obj.value = ''; }
    },

    initWord: function(obj, val) {
        if (obj.value == '') { obj.value = val; }
    },

    desaccentize: function(s) {
        return s.toLowerCase()
            .replace(/[àâ]/g, 'a')
            .replace(/[ç]/g, 'c')
            .replace(/[èéêë]/g, 'e')
            .replace(/[ïî]/g, 'i')
            .replace(/[œ]/g, 'oe')
            .replace(/[ùûü]/g, 'u');
    },

    // Calcule le mappage zoom <-> rayon sur Mappy.
    computeZoom: function(rayon) {
        var zoom = 11;
        if (rayon >= 60 && rayon < 160) zoom = 10;
        else if (rayon >= 160 && rayon < 510) zoom = 9;
        else if (rayon >= 510 && rayon < 1600) zoom = 8;
        else if (rayon >= 1600 && rayon < 4500) zoom = 7;
        else if (rayon >= 4500 && rayon < 13000) zoom = 6;
        else if (rayon >= 13000) zoom = 5;
        return zoom;
    },

    // Retourne (count) ou rien si 0.
    getCountString: function(count) {
        return (count > 0) ? ('(' + count + ')') : '';
    },

    handleError: function(xhr) {
        var text = 'statut : ' + xhr.status;
        if (xhr.status == 500) {
            text = xhr.responseText;
        } else if (xhr.status == 200) {
            //alert(text);
            //window.location.reload(true);
        } else {
            text += '\nréponse : ' + xhr.responseText;
        }
        return text;
    }
};

jQuery.expr[':'].Contains = function(a, i, m) {
    return utilities.desaccentize(a.textContent || a.innerText || "").indexOf(utilities.desaccentize(m[3])) >= 0;
};

String.prototype.beginsWith = function(t, i) {
    if (i == false) {
        return (t == this.substring(0, t.length));
    } else {
        return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
    }
}

String.prototype.template = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === "string" || typeof r === "number" ? r : a;
        }
    );
};

$.fn.serializeForm = function() {
    var obj = {};
    var array = this.serializeArray();
    $.each(array, function() {
        obj[this.name] = (this.value !== null) ? this.value : "null";
    });
    return obj;
};

$.fn.deserialize = function(d, config) {
    var data = d;
    me = this;

    if (d === undefined) {
        return me;
    }

    config = $.extend({ isPHPnaming: false,
        overwrite: false
    }, config);

    if (d.constructor == Array) {
        data = {};
        for (var i = 0; i < d.length; i++) {
            if (typeof data[d[i].name] != 'undefined') {
                if (data[d[i].name].constructor != Array) {
                    data[d[i].name] = [data[d[i].name], d[i].value];
                } else {
                    data[d[i].name].push(d[i].value);
                }
            } else {
                data[d[i].name] = d[i].value;
            }
        }
    }

    $('input,select,textarea', me)
        .each(function() {
            var p = this.name;
            var v = [];

            if (config.isPHPnaming) {
                p = p.replace(/\[\]$/, '');
            }
            if (p && data[p] != undefined) {
                v = data[p].constructor == Array ? data[p] : [data[p]];
            }

            if (config.overwrite === true || data[p]) {
                switch (this.type || this.tagName.toLowerCase()) {
                    case "radio":
                    case "checkbox":
                        this.checked = false;
                        for (var i = 0; i < v.length; i++) {
                            this.checked |= (this.value != '' && v[i] == this.value);
                        }
                        break;
                    case "select-multiple" || "select":
                        for (i = 0; i < this.options.length; i++) {
                            this.options[i].selected = false;
                            for (var j = 0; j < v.length; j++) {
                                this.options[i].selected |= (this.options[i].value != '' && this.options[i].value == v[j]);
                            }
                        }
                        break;
                    case "button":
                    case "submit":
                        this.value = v.length > 0 ? v.join(',') : this.value;
                        break;
                    default:
                        this.value = v.join(',');
                }
            }
        }
	);
    return me;
};


$.extend({
    URLEncode: function(c) {
        var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
        while (x < c.length) {
            var m = r.exec(c.substr(x));
            if (m != null && m.length > 1 && m[1] != '') {
                o += m[1]; x += m[1].length;
            } else {
                if (c[x] == ' ') o += '+'; else {
                    var d = c.charCodeAt(x); var h = d.toString(16);
                    o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
                } x++;
            }
        } return o;
    },
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});


$.extend({
    getQueryItem: function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        return (results == null) ? "" : $.URLDecode(results[1]);
    }
});

