/**
 * Created by laurent-heneman on 13/01/16.
 */
var exercice = exercice || {}; // exercice namespace
exercice.Utils = (function () {


    function  join  (separator /*, strings */) {
        var argsLength = arguments.length,
            strings = [];
        // Iterate through the arguments object skipping separator arg
        for (var i = 1, j = 0; i < argsLength; ++i) {
            var arg = arguments[i];

            // Filter undefineds, nulls, empty strings, 0s
            if (arg) {
                strings[j++] = arg;
            }
        }

        return strings.join(separator);
    }
    function removeItemInArray(array,item){
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === item) {
                array.splice(i, 1);
            }
        }
    }
    var toReplace = ["Ã€", "Ã", "Ã‚", "Ãƒ", "Ã„", "Ã…", "Ã†", "Ã‡", "Ãˆ", "Ã‰", "ÃŠ", "Ã‹", "ÃŒ", "Ã", "ÃŽ", "Ã", "Ã", "Ã‘", "Ã’", "Ã“", "Ã”", "Ã•", "Ã–", "Ã—", "Ã˜", "Ã™", "Ãš", "Ã›", "Ãœ", "Ã", "Ãž", "ÃŸ", "Ã", "Ã¡", "Ã¢", "Ã£", "Ã¤", "Ã¥", "Ã¦", "Ã§", "Ã¨", "Ã©", "Ãª", "Ã«", "Ã¬", "Ã­", "Ã®", "Ã¯", "Ã°", "Ã±", "Ã´", "Ãµ", "Ã¶", "Ã·", "Ã¸", "Ã¹", "Ãº", "Ã»", "Ã¼", "Ã½", "Ã¾", "Ã¿","âŠ—","Â²","â€‹","Â°","Ã³","â€¢","â—","â€“","â€™"];
    var replaceWith = ["À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ","⊗","²","","°","³","-","-","-","'"];

    var map = {};
    for (var i=0; i<toReplace.length; i++) {
        map[toReplace[i]] = replaceWith[i];
    }

    toReplace.sort(function(a,b){
        return b.length - a.length;
    });

    var expression = new RegExp(toReplace.join("|"), "g");

    function doReplace(source) {
        if(source===undefined) {
            return;
        }
        return source.replace(expression, function(m) {
            return map[m] || "";
        });
    }
    function appEvents () {
        var _AppEvents = {
            'startLink': isTablet() ? 'touchstart.link' : 'mousedown.link',
            'drawLink': isTablet() ? 'touchmove.link' : 'mousemove.link',
            'endLink': isTablet() ? 'touchend.link' : 'mouseup.link',
            'deleteLink': isTablet() ? 'tap.link' : 'click.link'

        };
        var _GlobalEvents = {
            'mousedown': isTablet() ? 'touchstart' : 'mousedown',
            'mousemove': isTablet() ? 'touchmove' : 'mousemove',
            'mouseleave': isTablet() ? 'touchend' : 'mouseleave',
            'mouseup': isTablet() ? 'touchend' : 'mouseup',
            'click': isTablet() ? 'tap' : 'click'

        };

        return {globalEvents :_GlobalEvents,linkEvents : _AppEvents}
    }
    function isTablet() {
        if( navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)
        ){
            return true;
        }
        else {
            return false;
        }
    }
    function generateUUID() {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random()*16)%16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });
        return uuid;
    }
    function uploadFile(selector,auto,file,complete,error) {


        $(selector).uploadifive({

            'auto': true,
            'fileType'     : file,
            'folder': 'uploads',
            'removeTimeout': 9999999,
            'uploadScript': 'uploadifive.php',
            'formData': {
                'token': "pop"

            },
            onUploadStart: function (file) {
                alert('Start');
            },
            onInit: function (file) {

            },
            onUploadComplete: function (file, data,p) {
               console.log('onUploadComplete',file, data,p);
                console.log(file.name, p);
               complete();
             // $(".audioControl").hide();
               //

                // exercice.Utils.render("uploads/" + file.name, "draw_img_qcm")
                // $('.screen_image').append('<img id="i" />')
                //$('#i').attr('src', "uploads/"+file.name);
            },
            'onError'      : function(errorType) {

                error()
                alert('The error was: ' + errorType);
            },
            onDelete: function (file) {
                alert("delete")

                //console.log(file);
            }
        });

    }
    function clearCanvas(id){
        var canvas = document.getElementById(id);
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
    function render(src,id){
        var image = new Image();
        image.onload = function(){
            var canvas = document.getElementById(id);
            var imageObj = image;
            //if(image.width > MAX_WIDTH) {
               // image.height *= MAX_WIDTH / image.width;
               // image.width = MAX_WIDTH ;
          //  }

            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            var imageAspectRatio = imageObj.width / imageObj.height;
            var canvasAspectRatio = canvas.width / canvas.height;
            var renderableHeight, renderableWidth, xStart, yStart;

            // If image's aspect ratio is less than canvas's we fit on height
            // and place the image centrally along width
            if(imageAspectRatio < canvasAspectRatio) {
                renderableHeight = canvas.height;
                renderableWidth = imageObj.width * (renderableHeight / imageObj.height);
                xStart = (canvas.width - renderableWidth) / 2;
                yStart = 0;
            }

            // If image's aspect ratio is greater than canvas's we fit on width
            // and place the image centrally along height
            else if(imageAspectRatio > canvasAspectRatio) {
                renderableWidth = canvas.width;
                renderableHeight = imageObj.height * (renderableWidth / imageObj.width);
                xStart = 0;
                yStart = (canvas.height - renderableHeight) / 2;
            }

            // Happy path - keep aspect ratio
            else {
                renderableHeight = canvas.height;
                renderableWidth = canvas.width;
                xStart = 0;
                yStart = 0;
            }
            ctx.drawImage(imageObj, xStart, yStart, renderableWidth, renderableHeight);
       

            //canvas.width = image.width;
            //canvas.height = image.height;
           //console.log("ctx.drawImage",image.width, image.height)
            //ctx.drawImage(image, 0, 0, image.width, image.height);
        };
        image.src = src;
    }
    function resizeImg(imgId) {
        var img = document.getElementById(imgId);
        var w = img.width, h = img.height;
        w /= 2; h /= 2;
        img.width = w; img.height = h;
    }
    function getRandomColor () {
        var _color ="#"+((1<<24)*Math.random()|0).toString(16)
       return _color
    }
    function rgb2hex(rgb){
        rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
        return (rgb && rgb.length === 4) ? "#" +
        ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
        ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
        ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
    }
    function handleResizeCanvas (){

            var w = window.innerWidth-2; // -2 accounts for the border
            var h = window.innerHeight-2;

            var ratio = 100/100; // 100 is the width and height of the circle content.
            var windowRatio = w/h;
            var scale = w/100;
            if (windowRatio > ratio) {
                scale = h/100;
            }
            // Scale up to fit width or height
            c.scaleX= c.scaleY = scale;

            // Center the shape
            c.x = w / 2;
            c.y = h / 2;

            //stage.update();
        }

    // dom utils

    // set the style properties given by the config_styles object for each element in elem_arr
    function setStyle(elem_arr, config_styles) {
        for(var style_param in config_styles) {

            if(elem_arr.length) {
                elem_arr.forEach(function fnc(elem) {
                    if(elem) {
                        elem[0].style[style_param] = config_styles[style_param];
                    }

                });
            }

        }
    }
    function getStyle(elem, prop_name) {
        return window.getComputedStyle(elem, false)[prop_name] || '';
    }
    function setHeight (elem, val) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        if (elem.style) {
            elem.style['height'] = val + ((!isNaN(val)) ? 'px' : '');
        }
    }
    /**
     *
     * @param  {[type]} jquery elem [description]
     * @param  {[type]} val  [description]
     * @return {[type]}      [description]
     */
    function setWidth(elem, val) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        if (elem.style) {
            elem.style['width'] = val + ((!isNaN(val)) ? 'px' : '');
        }
    }
    function setProperty(elem, property, value) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        elem.style.setProperty(property, value);
    }
    function removeProperty (elem, property) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        elem.style.removeProperty(property);
    }
    function getSize (elem) {
        return {'width': this.getWidth(elem), 'height': this.getHeight(elem)}
    }
    function getWidth (elem) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }

        var returnedWidth = window.getComputedStyle(elem, false)['width'];
        if (returnedWidth === 'auto') {
            returnedWidth = elem.style.width;
        }
        if (returnedWidth === '') {
            returnedWidth = elem.offsetWidth + 'px';
        }

        return returnedWidth.px2int() || 0;
    }
    function getHeight(elem) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }

        var returnedHeight = window.getComputedStyle(elem, false)['height'];
        if (returnedHeight === 'auto') {
            returnedHeight = elem.style.height;
        }
        if (returnedHeight === '') {
            returnedHeight = elem.offsetHeight + 'px';
        }

        return returnedHeight.px2int() || 0;

    }
    function getInnerWidth(elem) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        var elem_width = this.getWidth(elem), elem_innerWidth;

        elem_innerWidth = elem_width - (domUtils.getStyle(elem, 'paddingLeft').px2int() +
            getStyle(elem, 'paddingRight').px2int() +
            getStyle(elem, 'marginLeft').px2int() +
            getStyle(elem, 'marginRight').px2int() +
            getStyle(elem, 'borderLeft').px2int() +
            getStyle(elem, 'borderRight').px2int());

        return elem_innerWidth;
    }
    function getInnerHeight (elem) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        var elem_height = this.getHeight(elem), elem_innerHeight;

        elem_innerHeight = elem_height - (
           getStyle(elem, 'paddingTop').px2int() +
            getStyle(elem, 'paddingBottom').px2int() +
           getStyle(elem, 'marginTop').px2int() +
           getStyle(elem, 'marginBottom').px2int() +
          getStyle(elem, 'borderTop').px2int() +
           getStyle(elem, 'borderBottom').px2int());

        return Math.ceil(elem_innerHeight);
    }
    function getOuterWidth(elem) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        var elem_width = this.getWidth(elem), elem_outerWidth;

        elem_outerWidth = elem_width + (
           getStyle(elem, 'paddingLeft').px2int() +
            getStyle(elem, 'paddingRight').px2int() +
            getStyle(elem, 'marginLeft').px2int() +
            getStyle(elem, 'marginRight').px2int() +
            getStyle(elem, 'borderLeft').px2int() +
            getStyle(elem, 'borderRight').px2int());

        return Math.ceil(elem_outerWidth);
    }
    function getOuterHeight (elem) {
        if (elem.length) {
            elem = elem[0];
        } else if (elem.jquery && elem.context) {
            elem = elem.context;
        }
        var elem_height = this.getHeight(elem), elem_outerHeight;

        elem_outerHeight = elem_height + (
            getStyle(elem, 'paddingTop').px2int() +
            getStyle(elem, 'paddingBottom').px2int() +
            getStyle(elem, 'marginTop').px2int() +
            getStyle(elem, 'marginBottom').px2int() +
            getStyle(elem, 'borderTop').px2int() +
            getStyle(elem, 'borderBottom').px2int());

        return Math.ceil(elem_outerHeight);
    }

    function loadStylesheet  (href, opt_callback) {
        var link = document.createElement('link');
        link.setAttribute("rel","stylesheet");
        link.setAttribute('href',href);
        var done = false;

        link.onload = function () {
            if (!done) {
                done = true;

                if (opt_callback) {
                    opt_callback(null);
                }
            }
        };

        link.onerror = function () {
            if (!done) {
                done = true;

                if (opt_callback) {
                    opt_callback(new Error('Stylesheet failed to load'));
                }
            }
        };

        document.getElementsByTagName('head')[0].appendChild(link);

        return link;
    }
    function getPosition(el) {
        var xPos = 0;
        var yPos = 0;

        while (el) {
            if (el.tagName == "BODY") {
                // deal with browser quirks with body/window/document and page scroll
                var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
                var yScroll = el.scrollTop || document.documentElement.scrollTop;

                xPos += (el.offsetLeft - xScroll + el.clientLeft);
                yPos += (el.offsetTop - yScroll + el.clientTop);
            } else {
                // for all other non-BODY elements
                xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
                yPos += (el.offsetTop - el.scrollTop + el.clientTop);
            }

            el = el.offsetParent;
        }
        return {
            x: xPos,
            y: yPos
        };
    }

    return {
        uploadFile : uploadFile,
        resizeImg : resizeImg,
        render :render,
        generateUUID : generateUUID,
        isTablet : isTablet,
        clearCanvas : clearCanvas,
        getRandomColor : getRandomColor,
        rgb2hex: rgb2hex,
        handleResizeCanvas : handleResizeCanvas,
        appEvents : appEvents,
        removeItemInArray : removeItemInArray,
        join : join,
        setStyle : setStyle,
        getStyle:getStyle,
        getWidth :getWidth,
        getHeight :getHeight,
        setWidth :setWidth,
        setHeight:setHeight,
        removeProperty :removeProperty,
        setProperty:setProperty,
        loadStylesheet: loadStylesheet,
        getInnerWidth:getInnerWidth,
        getInnerHeight:getInnerHeight,
        getOuterWidth :getOuterWidth,
        getOuterHeight :getOuterHeight,
        getSize:getSize,
        getPosition:getPosition,
        doReplace : doReplace

    }
})();