﻿if (!Networker)
    var Networker = function() { };

Networker.Customization = {
    brightness: function(color) {
        var colorValue = this.parseCssColor(color);
        return (
            ((colorValue[0] / 255.0) * 299) + // R
            ((colorValue[1] / 255.0) * 587) + // G
            ((colorValue[2] / 255.0) * 114)   // B
        ) / 1000;
    },

    colorDifference: function(color1, color2) {
        var color1Value = this.parseCssColor(color1);
        var color2Value = this.parseCssColor(color2);
        return (Math.max(parseInt(color1Value[0]), parseInt(color2Value[0])) - Math.min(parseInt(color1Value[0]), parseInt(color2Value[0]))) +
            (Math.max(parseInt(color1Value[1]), parseInt(color2Value[1])) - Math.min(parseInt(color1Value[1]), parseInt(color2Value[1]))) +
            (Math.max(parseInt(color1Value[2]), parseInt(color2Value[2])) - Math.min(parseInt(color1Value[2]), parseInt(color2Value[2])));
    },

    contrast: function(color1, color2) {
        return Math.abs(
            this.brightness(color1) -
            this.brightness(color2));
    },

    // Based on http://www.w3.org/TR/2000/WD-AERT-20000426#color-contrast
    checkReadability: function(color1, color2) {
        return this.contrast(color1, color2) > 0.885 &&
                this.colorDifference(color1, color2) > 500;
    },

    checkElementReadability: function(element) {
        return this.checkReadability(
                element.css("background-color"),
                element.css("color"));
    },

    parseCssColor: function(color) {
        color = color.toString();
        if (color.indexOf("rgb") != -1) {
            return color.replace("rgb(", "").replace(")", "").replace(" ", "").replace(" ", "").split(',');
        } else {
            var colorValue = parseInt(color.substr(1), 16);
            return [colorValue >>> 16, ((colorValue >>> 8) & 0x00ff), (colorValue & 0x0000ff)];
        }
    },

    toRgbString: function(color) {
        return color[0] + "," + color[1] + "," + color[2];
    },

    updateBackground: function() {
        var background = 
            "url(/Profiles/Customization/Background.ashx?Pattern=" + this.pattern + 
            "&Scale=" + this.scale + 
            "&BackgroundColor=" + this.toRgbString(this.parseCssColor(this.backgroundColor)) + 
            "&ForegroundColor=" + this.toRgbString(this.parseCssColor(this.foregroundColor)) + 
            "&Surface=" + this.surface +
            "&Cache=" + Math.random() + ")";
        
        $("#BackgroundPreview, body").css("background-image", background);
    },

    scale: Number(0),
    pattern: Number(1),
    surface: Number(1),
    backgroundColor: String,
    foregroundColor: String

}