<commit_before>"use strict";
/* SISTEMA FEITO POR PAULAO */
/* SISTEMA KHAN */

class Khan {

    /* CONTRUTOR E JA SETA AS FUNCOES DE VERIFICACAO */
    constructor($app) {
        this.Addons();
        this.ImgLoaded();
        this.app = $app;
        this.Services = {};
        this.uriHome();
        this.ifModelBind();
        this.ifTextAnimate();
        this.Works = {};
        window.exports = {};
        window.modulesCached = {};
    }

    converteFunction(fun){
        var funncs, funnsName, funnsBody, parray = [], retorno = {};
        funnsName = Object.keys(fun).map((v) => {
            return v;
        });
        funnsBody = Object.values(fun).map((v) => {
            var indx = v.indexOf('{') + 1;
            v = v.substr(indx, v.length);
            v = v.substr(0, v.length);
            console.log(v);
            return v;
        });
        var params = Object.values(fun).map((v) => {
        var x = v.split('('),
            v = x[1].split(')');
            parray.push(v[0].split(','));
            funncs = v[1].split('{');
        });
        params = parray.map((v) => {
            return v.map((v) => {
              return v.replace(' ','');
            })
        });
        funnsName = funnsName.map((v, i) => {
            retorno[v] = new Function(...params[i], funnsBody[i]);
        });
        return retorno;
    }

    requireModule(module){
        var cache = (sessionStorage.getItem(module) == null) ? false : true;
        this.Work({
            name: 'Modules',
            url: 'works/KhanWorkModules.js'
        },function(Work){
            Work.postMessage(module);
            Work.onmessage = function(e){
                    var dtt = JSON.stringify(e.data);
                    if(cache){
                        sessionStorage.removeItem(module);
                        sessionStorage.setItem(module, dtt);
                    }else{
                        sessionStorage.setItem(module, dtt);
                        location.reload();
                    }
            };
        });
        cache = this.converteFunction(JSON.parse(sessionStorage.getItem(module)));
        return cache;
    }

    /* CARREGA AS IMAGENS ASSINCRONAMENTE */
    ImgLoaded() {
        setTimeout(() => {
            if (document.querySelectorAll('[khan-img-src]').length != 0) {
                document.querySelectorAll('[khan-img-src]').forEach((v, i) => {
                    this.Encrypt(v.getAttribute('khan-img-src')).then((va) => {
                        va = va.substr(0, va.length / 2.5);
                        v.setAttribute('hash', va);
                    });
                    v.setAttribute('khan-img-src', window.btoa(v.getAttribute('khan-img-src')));
                    v.setAttribute('class', 'khan-img-' + i);
                    if (sessionStorage.getItem('khan-img-' + i) != null) {
                        v.src = sessionStorage.getItem('khan-img-' + i);
                    } else {
                        var req = new Request(window.atob(v.getAttribute('khan-img-src')));
                        fetch(req).then(function(response) {
                            return response.blob();
                        }).then(function(myBlob) {
                            var objectURL = URL.createObjectURL(myBlob);
                            v.src = objectURL;
                            sessionStorage.setItem('khan-img-' + i, objectURL);
                        });
                    }
                });

            }
        }, 0.2);
    }

    /* GERADOR DE WORKS MACHINE */
    Work(ob, callback) {
        this.Works[ob.name] = new Worker(ob.url);
        callback(this.Works[ob.name]);
    }

    /* CONTAINERS */

    Containers(data) {
        var channel = data.channel;
        this.Work({
                name: 'Jskhan',
                url: 'works/KhanWork.js'
            },
            function(Work) {
                Work.postMessage({
                    name: data.channel,
                    fu: data.funcao.toString(),
                    action: 'setContainer'
                });
            });
        return {
            setContainer: function(data){
                data["Work"].postMessage({
                    name: data.channel,
                    fu: data.funcao.toString(),
                    action: 'setContainer'
                });
            },
            getContainer: function(data) {
                data.scope.postMessage({
                    name: data.channel,
                    action: 'getContainer'
                });
            },
            getRunService: function(data) {
                data.scope.postMessage({
                    name: data.channel,
                    action: 'getRunService'
                });
            },
            GetCanal: function() {
                return channel;
            },
            setRunService: function(data) {
                if (data.data.length == 0) {
                    data.scope.postMessage({
                        name: data.channel,
                        action: 'setRunService'
                    });
                } else {
                    data.scope.postMessage({
                        name: data.channel,
                        parame: data.data,
                        action: 'setRunService'
                    });
                }
            }
        };
    }

    /* FUNCOES EXTRAS Each e Memorize de Cache */

    Addons() {
        window["CacheModules"] = function(module){
            sessionStorage.removeItem(module);
            document.location.reload();
        },
        Object.prototype.Each = function(cb) {
            const Keys = Object.keys(this),
                Values = Object.values(this);
            cb(Values, Keys);
        };
        Function.prototype.Memorize = function() {
            const scope = this;
            let cache = new Object(),
                key;
            return (...args) => {
                key = JSON.stringify(args);
                return cache[key] || (cache[key] = scope.call(null, ...args));
            }
        };
    }

    /* CRIPTOGRAFADOR DE STRINGS */
    Encrypt(str) {

        return new Promise(function(resolve, reject) {

            var hash = CryptoJS.SHA256(str);
            const cryptado = hash.toString(CryptoJS.enc.Base64);
            resolve(cryptado);

        });

    }

    /* TEXTO ESCREVE NA TELA*/
    ifTextAnimate() {
        setTimeout(() => {

            if (document.querySelectorAll('[khan-txt-animate]').length != 0) {
                this.getTextAnimate();
            }

        }, 2000);

    }

    getTextAnimate() {

        var caixas = document.querySelectorAll('[khan-txt-animate]');

        caixas.forEach((v, i) => {
            var txt = v.innerHTML.split(''),
                t = document.createElement('p'),
                m = document.createElement('p');
            t.setAttribute('class', 'khan-txt-animate-' + i);
            m.setAttribute('class', 'khan-txt-animate-mark')
            m.innerHTML = ' |';
            v.innerHTML = '';
            v.appendChild(t);
            v.appendChild(m);
            var tAtual = document.querySelector('.khan-txt-animate-' + i);
            this.setTextAnimate(txt, tAtual);
        });

    }

    setTextAnimate(txt, tAtual) {

        txt.forEach((val, ind) => {
            setTimeout(() => {
                tAtual.innerHTML += val;
                if ((txt.length - 1) == ind) {
                    setTimeout(() => {
                        tAtual.innerHTML = '';
                        this.setTextAnimate(txt, tAtual);
                    }, 1500);
                }
            }, ind * 300);
        });

    }

    /* FUNCAO PARA PEGAR URL */
    uriHome() {

        if (location.hash.length == 0) {
            location.href = '#/index';
        }

    }

    /* INPUT QUE ESCREVE EM OUTRO ELEMENTO */
    ifModelBind() {

        setTimeout(() => {
            if (document.querySelectorAll('[khan-model]').length > 0) {
                this.ModelBind();
            }
        }, 10);

    }

    ModelBind() {
        document.querySelectorAll('[khan-model]').forEach((v, i) => {
            v.onkeyup = function() {
                new Khan().ViewBind(this);
            };
        });
    }

    ViewBind($bind) {
        if (document.querySelector('[khan-view="' + $bind.getAttribute('khan-model') + '"]').nodeName == 'INPUT') {
            document.querySelector('[khan-view="' + $bind.getAttribute('khan-model') + '"]').
            value = $bind.value
        } else {
            document.querySelector('[khan-view="' + $bind.getAttribute('khan-model') + '"]').
            innerHTML = $bind.value;
        }
    }

    /* PEGA VIEW DO PROJETO */
    GetView() {
        return document.querySelector('[khan-app]').getAttribute('khan-app');
    }

    /* FETCH JSON REQUEST PROMISE */
    fetchJSON(ob) {
        return new Promise(function(resolve, reject) {

            fetch(ob.url, {
                method: ob.method // opcional
            }).then(function(response) {
                response.text().then(function(result) {
                    resolve(result);
                });
            }).catch(function(err) {
                reject("Ocorreu um erro");
            });

        });
    }

    /* REQUESTS */
    Request($page, $d, $callback = function() {}) {
        var $request = new XMLHttpRequest();
        var $posts = '';
        var $dataKeys = Object.keys($d),
            $dataValues = Object.values($d),
            $dataPostArr = '';
        $dataKeys.forEach((val, index) => {
            if ((index + 1) < $dataKeys.length) {
                $dataPostArr += val + '=' + $dataValues[index] + '&';
            } else if ((index + 1) == $dataKeys.length) {
                $dataPostArr += val + '=' + $dataValues[index];
            }
        });
        $request.onreadystatechange = () => {
            if (this.readyState == 4 && this.status == 200) {
                $callback(this.textReponse);
            }
        }
        $request.open("POST", $page, true);
        $request.send($dataPostArr);
    }

    /* SISTEM ROUTES */

    Routes($name = 'index', $callback = function() {}) {
        $name = $name.toString().split('/');
        if (this.GetUri().All()[0] == $name[1] && this.GetUri().All().length > 0) {
            $callback(this.getParameters(this.postParameters($name), $name));
        } else if (location.hash == "#/") {
            location.href = location.hash + 'index';
        }
    }

    GetUri() {
        return {
            All: () => {
                var r = (location.hash.length > 0) ? location.hash.split('/') : ['#', 'index'];
                delete r[0];
                return r.filter((val) => {
                    return val != 'undefined';
                });
            },
            Filter: ($string) => {
                $string = $string.replace(/(<([^>]+)>)/ig, "");
                $string = $string.replace(/<\/?[^>]+(>|$)/g, "");
                return $string;
            }
        }
    }

    getParameters($url, $uris) {
        this.Params = new Object();
        var arr = Object.values($url),
            ures = [];
        $uris.forEach((val) => {
            ures.push(val);
        });
        arr.forEach((val) => {
            this.Params[ures[val].replace(':', '')] = (isNaN(this.GetUri().All()[val])) ? this.GetUri().Filter(this.GetUri().All()[val]) : parseInt(this.GetUri().All()[val]);
        });
        return this.Params;
    }

    postParameters($url) {
        delete $url[0];
        $url = $url.filter((val) => {
            return val != 'undefined';
        });
        var achados = [];
        $url.forEach((val, index) => {
            if (val.indexOf(':') != -1) {
                achados.push(index);
            }
        });
        return achados;
    }

    /* RENDERIZA O HTML COM JS */

    DomRender($code) {
        return (document.querySelectorAll(`[khan-app='${this.app}']`).length > 0) ? document.querySelector(`[khan-app='${this.app}']`).innerHTML += $code : this.Log('Erro ! Não Existe a View "' + this.app + '"');
    }
    /* FAZ O CACHE DO CODIGO RENDERIZADO*/
    CachePage(_page, call) {

        if (sessionStorage.getItem(_page)) {

            call(window.atob(sessionStorage.getItem(_page)));
            return false;

        } else {

            return true;

        }

    }

    PageRender($page, $callback = () => {}) {
        //if(this.CachePage($page, $callback)){
        var $request = new XMLHttpRequest();
        $request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //sessionStorage.setItem($page, window.btoa(this.responseText));
                $callback(this.responseText);
            }
        };
        $request.open("GET", $page, true);
        $request.send();
        //}
    }

    /* FUNCOES DE DEBUG */

    Debug() {
        return {
            Log(str) {
                console.log(str);
            },
            Erro(str) {
                throw str;
            },
            Debug() {
                debugger;
            }
        };
    }

}
<commit_msg>Update app.js<commit_after>"use strict";
/* SISTEMA FEITO POR PAULAO */
/* SISTEMA KHAN */

class Khan {

    /* CONTRUTOR E JA SETA AS FUNCOES DE VERIFICACAO */
    constructor($app, status = false) {
        window["limparCacheModulos"] = function(m){
            m.map((v) => {
                 sessionStorage.removeItem(v);
                 console.log('Limpado Cache do Modulo '+ v);
            });
        };
        this.routeStatus = status;
        this.Addons();
        this.ImgLoaded();
        this.app = $app;
        this.Services = {};
        this.uriHome();
        this.ifModelBind();
        this.ifTextAnimate();
        this.Works = {};
        window.exports = {};
        window.modulesCached = {};
    }

    converteFunction(fun){
        var funncs, funnsName, funnsBody, parray = [], retorno = {};
        funnsName = Object.keys(fun).map((v) => {
            return v;
        });
        funnsBody = Object.values(fun).map((v) => {
            var indx = v.indexOf('{') + 1;
            v = v.substr(indx, v.length);
            v = v.substr(0, v.length - 1);
            v = v.replace(/  /g, '').replace(/\n/g, '');
            return v;
        });
        var params = Object.values(fun).map((v) => {
        var x = v.split('('),
            v = x[1].split(')');
            parray.push(v[0].split(','));
            funncs = v[1].split('{');
        });
        params = parray.map((v) => {
            return v.map((v) => {
              return v.replace(' ','');
            })
        });
        funnsName = funnsName.map((v, i) => {
            retorno[v] = new Function(...params[i], funnsBody[i]);
        });
        return retorno;
    }

    requireModule(module){
        var cache = (sessionStorage.getItem(module) == null) ? false : true;
        this.Work({
            name: 'Modules',
            url: 'works/KhanWorkModules.js'
        },function(Work){
            Work.postMessage(module);
            Work.onmessage = function(e){
                    var dtt = JSON.stringify(e.data);
                    if(cache){
                        sessionStorage.removeItem(module);
                        sessionStorage.setItem(module, dtt);
                    }else{
                        sessionStorage.setItem(module, dtt);
                        location.reload();
                    }
            };
        });
        cache = this.converteFunction(JSON.parse(sessionStorage.getItem(module)));
        return cache;
    }

    /* CARREGA AS IMAGENS ASSINCRONAMENTE */
    ImgLoaded() {
        setTimeout(() => {
            if (document.querySelectorAll('[khan-img-src]').length != 0) {
                document.querySelectorAll('[khan-img-src]').forEach((v, i) => {
                    this.Encrypt(v.getAttribute('khan-img-src')).then((va) => {
                        va = va.substr(0, va.length / 2.5);
                        v.setAttribute('hash', va);
                    });
                    v.setAttribute('khan-img-src', window.btoa(v.getAttribute('khan-img-src')));
                    v.setAttribute('class', 'khan-img-' + i);
                    if (sessionStorage.getItem('khan-img-' + i) != null) {
                        v.src = sessionStorage.getItem('khan-img-' + i);
                    } else {
                        var req = new Request(window.atob(v.getAttribute('khan-img-src')));
                        fetch(req).then(function(response) {
                            return response.blob();
                        }).then(function(myBlob) {
                            var objectURL = URL.createObjectURL(myBlob);
                            v.src = objectURL;
                            sessionStorage.setItem('khan-img-' + i, objectURL);
                        });
                    }
                });

            }
        }, 0.2);
    }

    /* GERADOR DE WORKS MACHINE */
    Work(ob, callback) {
        this.Works[ob.name] = new Worker(ob.url);
        callback(this.Works[ob.name]);
    }

    /* CONTAINERS */

    Containers(data) {
        var channel = data.channel;
        this.Work({
                name: 'Jskhan',
                url: 'works/KhanWork.js'
            },
            function(Work) {
                Work.postMessage({
                    name: data.channel,
                    fu: data.funcao.toString(),
                    action: 'setContainer'
                });
            });
        return {
            setContainer: function(data){
                data["Work"].postMessage({
                    name: data.channel,
                    fu: data.funcao.toString(),
                    action: 'setContainer'
                });
            },
            getContainer: function(data) {
                data.scope.postMessage({
                    name: data.channel,
                    action: 'getContainer'
                });
            },
            getRunService: function(data) {
                data.scope.postMessage({
                    name: data.channel,
                    action: 'getRunService'
                });
            },
            GetCanal: function() {
                return channel;
            },
            setRunService: function(data) {
                if (data.data.length == 0) {
                    data.scope.postMessage({
                        name: data.channel,
                        action: 'setRunService'
                    });
                } else {
                    data.scope.postMessage({
                        name: data.channel,
                        parame: data.data,
                        action: 'setRunService'
                    });
                }
            }
        };
    }

    /* FUNCOES EXTRAS Each e Memorize de Cache */

    Addons() {
        window["CacheModules"] = function(module){
            sessionStorage.removeItem(module);
            document.location.reload();
        },
        Object.prototype.Each = function(cb) {
            const Keys = Object.keys(this),
                Values = Object.values(this);
            cb(Values, Keys);
        };
        Function.prototype.Memorize = function() {
            const scope = this;
            let cache = new Object(),
                key;
            return (...args) => {
                key = JSON.stringify(args);
                return cache[key] || (cache[key] = scope.call(null, ...args));
            }
        };
    }

    /* CRIPTOGRAFADOR DE STRINGS */
    Encrypt(str) {

        return new Promise(function(resolve, reject) {

            var hash = CryptoJS.SHA256(str);
            const cryptado = hash.toString(CryptoJS.enc.Base64);
            resolve(cryptado);

        });

    }

    /* TEXTO ESCREVE NA TELA*/
    ifTextAnimate() {
        setTimeout(() => {

            if (document.querySelectorAll('[khan-txt-animate]').length != 0) {
                this.getTextAnimate();
            }

        }, 2000);

    }

    getTextAnimate() {

        var caixas = document.querySelectorAll('[khan-txt-animate]');

        caixas.forEach((v, i) => {
            var txt = v.innerHTML.split(''),
                t = document.createElement('p'),
                m = document.createElement('p');
            t.setAttribute('class', 'khan-txt-animate-' + i);
            m.setAttribute('class', 'khan-txt-animate-mark')
            m.innerHTML = ' |';
            v.innerHTML = '';
            v.appendChild(t);
            v.appendChild(m);
            var tAtual = document.querySelector('.khan-txt-animate-' + i);
            this.setTextAnimate(txt, tAtual);
        });

    }

    setTextAnimate(txt, tAtual) {

        txt.forEach((val, ind) => {
            setTimeout(() => {
                tAtual.innerHTML += val;
                if ((txt.length - 1) == ind) {
                    setTimeout(() => {
                        tAtual.innerHTML = '';
                        this.setTextAnimate(txt, tAtual);
                    }, 1500);
                }
            }, ind * 300);
        });

    }

    /* FUNCAO PARA PEGAR URL */
    uriHome() {

        if (location.hash.length == 0 && this.routeStatus == true) {
            location.href = '#/index';
        }

    }

    /* INPUT QUE ESCREVE EM OUTRO ELEMENTO */
    ifModelBind() {

        setTimeout(() => {
            if (document.querySelectorAll('[khan-model]').length > 0) {
                this.ModelBind();
            }
        }, 10);

    }

    ModelBind() {
        document.querySelectorAll('[khan-model]').forEach((v, i) => {
            v.onkeyup = function() {
                new Khan().ViewBind(this);
            };
        });
    }

    ViewBind($bind) {
        if (document.querySelector('[khan-view="' + $bind.getAttribute('khan-model') + '"]').nodeName == 'INPUT') {
            document.querySelector('[khan-view="' + $bind.getAttribute('khan-model') + '"]').
            value = $bind.value
        } else {
            document.querySelector('[khan-view="' + $bind.getAttribute('khan-model') + '"]').
            innerHTML = $bind.value;
        }
    }

    /* PEGA VIEW DO PROJETO */
    GetView() {
        return document.querySelector('[khan-app]').getAttribute('khan-app');
    }

    /* FETCH JSON REQUEST PROMISE */
    fetchJSON(ob) {
        return new Promise(function(resolve, reject) {

            fetch(ob.url, {
                method: ob.method // opcional
            }).then(function(response) {
                response.text().then(function(result) {
                    resolve(result);
                });
            }).catch(function(err) {
                reject("Ocorreu um erro");
            });

        });
    }

    /* REQUESTS */
    Request($page, $d, $callback = function() {}) {
        var $request = new XMLHttpRequest();
        var $posts = '';
        var $dataKeys = Object.keys($d),
            $dataValues = Object.values($d),
            $dataPostArr = '';
        $dataKeys.forEach((val, index) => {
            if ((index + 1) < $dataKeys.length) {
                $dataPostArr += val + '=' + $dataValues[index] + '&';
            } else if ((index + 1) == $dataKeys.length) {
                $dataPostArr += val + '=' + $dataValues[index];
            }
        });
        $request.onreadystatechange = () => {
            if (this.readyState == 4 && this.status == 200) {
                $callback(this.textReponse);
            }
        }
        $request.open("POST", $page, true);
        $request.send($dataPostArr);
    }

    /* SISTEM ROUTES */

    Routes($name = 'index', $callback = function() {}) {
        $name = $name.toString().split('/');
        if (this.GetUri().All()[0] == $name[1] && this.GetUri().All().length > 0) {
            $callback(this.getParameters(this.postParameters($name), $name));
        } else if (location.hash == "#/") {
            location.href = location.hash + 'index';
        }
    }

    GetUri() {
        return {
            All: () => {
                var r = (location.hash.length > 0) ? location.hash.split('/') : ['#', 'index'];
                delete r[0];
                return r.filter((val) => {
                    return val != 'undefined';
                });
            },
            Filter: ($string) => {
                $string = $string.replace(/(<([^>]+)>)/ig, "");
                $string = $string.replace(/<\/?[^>]+(>|$)/g, "");
                return $string;
            }
        }
    }

    getParameters($url, $uris) {
        this.Params = new Object();
        var arr = Object.values($url),
            ures = [];
        $uris.forEach((val) => {
            ures.push(val);
        });
        arr.forEach((val) => {
            this.Params[ures[val].replace(':', '')] = (isNaN(this.GetUri().All()[val])) ? this.GetUri().Filter(this.GetUri().All()[val]) : parseInt(this.GetUri().All()[val]);
        });
        return this.Params;
    }

    postParameters($url) {
        delete $url[0];
        $url = $url.filter((val) => {
            return val != 'undefined';
        });
        var achados = [];
        $url.forEach((val, index) => {
            if (val.indexOf(':') != -1) {
                achados.push(index);
            }
        });
        return achados;
    }

    /* RENDERIZA O HTML COM JS */

    DomRender($code) {
        return (document.querySelectorAll(`[khan-app='${this.app}']`).length > 0) ? document.querySelector(`[khan-app='${this.app}']`).innerHTML += $code : this.Log('Erro ! Não Existe a View "' + this.app + '"');
    }
    /* FAZ O CACHE DO CODIGO RENDERIZADO*/
    CachePage(_page, call) {

        if (sessionStorage.getItem(_page)) {

            call(window.atob(sessionStorage.getItem(_page)));
            return false;

        } else {

            return true;

        }

    }

    PageRender($page, $callback = () => {}) {
        //if(this.CachePage($page, $callback)){
        var $request = new XMLHttpRequest();
        $request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //sessionStorage.setItem($page, window.btoa(this.responseText));
                $callback(this.responseText);
            }
        };
        $request.open("GET", $page, true);
        $request.send();
        //}
    }

    /* FUNCOES DE DEBUG */

    Debug() {
        return {
            Log(str) {
                console.log(str);
            },
            Erro(str) {
                throw str;
            },
            Debug() {
                debugger;
            }
        };
    }

}
<|endoftext|>


<commit_before>// ==========================================================================
// Project:  SproutCore Runtime
// Copyright: ©2011 Strobe Inc. and contributors.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================
/*globals ENV sc_assert */

require('sproutcore-metal');

// ........................................
// GLOBAL CONSTANTS
//

/**
  @name YES
  @static
  @type Boolean
  @default true
  @constant
*/
YES = true;

/**
  @name NO
  @static
  @type Boolean
  @default NO
  @constant
*/
NO = false;

// ensure no undefined errors in browsers where console doesn't exist
if (typeof console === 'undefined') {
  window.console = {};
  console.log = console.info = console.warn = console.error = function() {};
}

// ..........................................................
// BOOTSTRAP
//

/**
  @static
  @type Boolean
  @default YES
  @constant

  Determines whether SproutCore should enhances some built-in object
  prototypes to provide a more friendly API.  If enabled, a few methods
  will be added to Function, String, and Array.  Object.prototype will not be
  enhanced, which is the one that causes most troubles for people.

  In general we recommend leaving this option set to true since it rarely
  conflicts with other code.  If you need to turn it off however, you can
  define an ENV.ENHANCE_PROTOTYPES config to disable it.
*/
SC.EXTEND_PROTOTYPES = (SC.ENV.EXTEND_PROTOTYPES !== false);

// ........................................
// TYPING & ARRAY MESSAGING
//

var TYPE_MAP = {};
var t ="Boolean Number String Function Array Date RegExp Object".split(" ");
t.forEach(function(name) {
	TYPE_MAP[ "[object " + name + "]" ] = name.toLowerCase();
});

var toString = Object.prototype.toString;

/**
  Returns a consistant type for the passed item.

  Use this instead of the built-in SC.typeOf() to get the type of an item.
  It will return the same result across all browsers and includes a bit
  more detail.  Here is what will be returned:

  | Return Value Constant | Meaning |
  | 'string' | String primitive |
  | 'number' | Number primitive |
  | 'boolean' | Boolean primitive |
  | 'null' | Null value |
  | 'undefined' | Undefined value |
  | 'function' | A function |
  | 'array' | An instance of Array |
  | 'class' | A SproutCore class (created using SC.Object.extend()) |
  | 'object' | A SproutCore object instance |
  | 'error' | An instance of the Error object |
  | 'hash' | A JavaScript object not inheriting from SC.Object |

  @param item {Object} the item to check
  @returns {String} the type
*/
SC.typeOf = function(item) {
  var ret;

  ret = item==null ? String(item) : TYPE_MAP[toString.call(item)]||'object';

  if (ret === 'function') {
    if (SC.Object && SC.Object.detect(item)) ret = 'class';
  } else if (ret === 'object') {
    if (item instanceof Error) ret = 'error';
    else if (SC.Object && item instanceof SC.Object) ret = 'instance';
    else ret = 'object';
  }

  return ret;
};

/**
  Returns YES if the passed value is null or undefined.  This avoids errors
  from JSLint complaining about use of ==, which can be technically
  confusing.

  @param {Object} obj Value to test
  @returns {Boolean}
*/
SC.none = function(obj) {
  return obj === null || obj === undefined;
};

/**
  Verifies that a value is either null or an empty string. Return false if
  the object is not a string.

  @param {Object} obj Value to test
  @returns {Boolean}
*/
SC.empty = function(obj) {
  return obj === null || obj === undefined || obj === '';
};

/**
  SC.isArray defined in sproutcore-metal/lib/utils
**/

/**
 This will compare two javascript values of possibly different types.
 It will tell you which one is greater than the other by returning:

  - -1 if the first is smaller than the second,
  - 0 if both are equal,
  - 1 if the first is greater than the second.

 The order is calculated based on SC.ORDER_DEFINITION, if types are different.
 In case they have the same type an appropriate comparison for this type is made.

 @param {Object} v First value to compare
 @param {Object} w Second value to compare
 @returns {Number} -1 if v < w, 0 if v = w and 1 if v > w.
*/
SC.compare = function (v, w) {
  if (v === w) { return 0; }

  var type1 = SC.typeOf(v);
  var type2 = SC.typeOf(w);

  var Comparable = SC.Comparable;
  if (Comparable) {
    if (type1==='instance' && Comparable.detect(v.constructor)) {
      return v.constructor.compare(v, w);
    }

    if (type2 === 'instance' && Comparable.detect(w.constructor)) {
      return 1-w.constructor.compare(w, v);
    }
  }

  // If we haven't yet generated a reverse-mapping of SC.ORDER_DEFINITION,
  // do so now.
  var mapping = SC.ORDER_DEFINITION_MAPPING;
  if (!mapping) {
    var order = SC.ORDER_DEFINITION;
    mapping = SC.ORDER_DEFINITION_MAPPING = {};
    var idx, len;
    for (idx = 0, len = order.length; idx < len;  ++idx) {
      mapping[order[idx]] = idx;
    }

    // We no longer need SC.ORDER_DEFINITION.
    delete SC.ORDER_DEFINITION;
  }

  var type1Index = mapping[type1];
  var type2Index = mapping[type2];

  if (type1Index < type2Index) { return -1; }
  if (type1Index > type2Index) { return 1; }

  // types are equal - so we have to check values now
  switch (type1) {
    case 'boolean':
    case 'number':
      if (v < w) { return -1; }
      if (v > w) { return 1; }
      return 0;

    case 'string':
      var comp = v.localeCompare(w);
      if (comp < 0) { return -1; }
      if (comp > 0) { return 1; }
      return 0;

    case 'array':
      var vLen = v.length;
      var wLen = w.length;
      var l = Math.min(vLen, wLen);
      var r = 0;
      var i = 0;
      var thisFunc = arguments.callee;
      while (r === 0 && i < l) {
        r = thisFunc(v[i],w[i]);
        i++;
      }
      if (r !== 0) { return r; }

      // all elements are equal now
      // shorter array should be ordered first
      if (vLen < wLen) { return -1; }
      if (vLen > wLen) { return 1; }
      // arrays are equal now
      return 0;

    case 'instance':
      if (SC.Comparable && SC.Comparable.detect(v)) {
        return v.compare(v, w);
      }
      return 0;

    default:
      return 0;
  }
};

function _copy(obj, deep, seen, copies) {
  var ret, loc, key;

  // primitive data types are immutable, just return them.
  if ('object' !== typeof obj || obj===null) return obj;

  // avoid cyclical loops
  if (deep && (loc=seen.indexOf(obj))>=0) return copies[loc];

  sc_assert('Cannot clone an SC.Object that does not implement SC.Copyable', !(obj instanceof SC.Object) || (SC.Copyable && SC.Copyable.detect(obj)));

  // IMPORTANT: this specific test will detect a native array only.  Any other
  // object will need to implement Copyable.
  if (SC.typeOf(obj) === 'array') {
    ret = obj.slice();
    if (deep) {
      loc = ret.length;
      while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies);
    }
  } else if (SC.Copyable && SC.Copyable.detect(obj)) {
    ret = obj.copy(deep, seen, copies);
  } else {
    ret = {};
    for(key in obj) {
      if (!obj.hasOwnProperty(key)) continue;
      ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key];
    }
  }

  if (deep) {
    seen.push(obj);
    copies.push(ret);
  }

  return ret;
}

/**
  Creates a clone of the passed object. This function can take just about
  any type of object and create a clone of it, including primitive values
  (which are not actually cloned because they are immutable).

  If the passed object implements the clone() method, then this function
  will simply call that method and return the result.

  @param {Object} object The object to clone
  @param {Boolean} deep If true, a deep copy of the object is made
  @returns {Object} The cloned object
*/
SC.copy = function(obj, deep) {
  // fast paths
  if ('object' !== typeof obj || obj===null) return obj; // can't copy primitives
  if (SC.Copyable && SC.Copyable.detect(obj)) return obj.copy(deep);
  return _copy(obj, deep, deep ? [] : null, deep ? [] : null);
};

/**
  Convenience method to inspect an object. This method will attempt to
  convert the object into a useful string description.

  @param {Object} obj The object you want to inspec.
  @returns {String} A description of the object
*/
SC.inspect = function(obj) {
  var v, ret = [];
  for(var key in obj) {
    if (obj.hasOwnProperty(key)) {
      v = obj[key];
      if (v === 'toString') { continue; } // ignore useless items
      if (SC.typeOf(v) === SC.T_FUNCTION) { v = "function() { ... }"; }
      ret.push(key + ": " + v);
    }
  }
  return "{" + ret.join(" , ") + "}";
};

/**
  Compares two objects, returning true if they are logically equal.  This is
  a deeper comparison than a simple triple equal.  For arrays and enumerables
  it will compare the internal objects.  For any other object that implements
  `isEqual()` it will respect that method.

  @param {Object} a first object to compare
  @param {Object} b second object to compare
  @returns {Boolean}
*/
SC.isEqual = function(a, b) {
  if (a && 'function'===typeof a.isEqual) return a.isEqual(b);
  return a === b;
};

/**
  @private
  Used by SC.compare
*/
SC.ORDER_DEFINITION = SC.ENV.ORDER_DEFINITION || [
  'undefined',
  'null',
  'boolean',
  'number',
  'string',
  'array',
  'object',
  'instance',
  'function',
  'class'
];

/**
  Returns all of the keys defined on an object or hash. This is useful
  when inspecting objects for debugging.  On browsers that support it, this
  uses the native Object.keys implementation.

  @function
  @param {Object} obj
  @returns {Array} Array containing keys of obj
*/
SC.keys = Object.keys;

if (!SC.keys) {
  SC.keys = function(obj) {
    var ret = [];
    for(var key in obj) {
      if (obj.hasOwnProperty(key)) { ret.push(key); }
    }
    return ret;
  };
}

// ..........................................................
// ERROR
//

/**
  @class

  A subclass of the JavaScript Error object for use in SproutCore.
*/
SC.Error = function() {
  var tmp = Error.prototype.constructor.apply(this, arguments);

  for (var p in tmp) {
    if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }
  }
};

SC.Error.prototype = SC.create(Error.prototype);

// ..........................................................
// LOGGER
//

/**
  @class

  Inside SproutCore-Runtime, simply uses the window.console object.
  Override this to provide more robust logging functionality.
*/
SC.Logger = window.console;
<commit_msg>SC.inspect still referenced SC.T_FUNCTION, change it to 'function'<commit_after>// ==========================================================================
// Project:  SproutCore Runtime
// Copyright: ©2011 Strobe Inc. and contributors.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================
/*globals ENV sc_assert */

require('sproutcore-metal');

// ........................................
// GLOBAL CONSTANTS
//

/**
  @name YES
  @static
  @type Boolean
  @default true
  @constant
*/
YES = true;

/**
  @name NO
  @static
  @type Boolean
  @default NO
  @constant
*/
NO = false;

// ensure no undefined errors in browsers where console doesn't exist
if (typeof console === 'undefined') {
  window.console = {};
  console.log = console.info = console.warn = console.error = function() {};
}

// ..........................................................
// BOOTSTRAP
//

/**
  @static
  @type Boolean
  @default YES
  @constant

  Determines whether SproutCore should enhances some built-in object
  prototypes to provide a more friendly API.  If enabled, a few methods
  will be added to Function, String, and Array.  Object.prototype will not be
  enhanced, which is the one that causes most troubles for people.

  In general we recommend leaving this option set to true since it rarely
  conflicts with other code.  If you need to turn it off however, you can
  define an ENV.ENHANCE_PROTOTYPES config to disable it.
*/
SC.EXTEND_PROTOTYPES = (SC.ENV.EXTEND_PROTOTYPES !== false);

// ........................................
// TYPING & ARRAY MESSAGING
//

var TYPE_MAP = {};
var t ="Boolean Number String Function Array Date RegExp Object".split(" ");
t.forEach(function(name) {
	TYPE_MAP[ "[object " + name + "]" ] = name.toLowerCase();
});

var toString = Object.prototype.toString;

/**
  Returns a consistant type for the passed item.

  Use this instead of the built-in SC.typeOf() to get the type of an item.
  It will return the same result across all browsers and includes a bit
  more detail.  Here is what will be returned:

  | Return Value Constant | Meaning |
  | 'string' | String primitive |
  | 'number' | Number primitive |
  | 'boolean' | Boolean primitive |
  | 'null' | Null value |
  | 'undefined' | Undefined value |
  | 'function' | A function |
  | 'array' | An instance of Array |
  | 'class' | A SproutCore class (created using SC.Object.extend()) |
  | 'object' | A SproutCore object instance |
  | 'error' | An instance of the Error object |
  | 'hash' | A JavaScript object not inheriting from SC.Object |

  @param item {Object} the item to check
  @returns {String} the type
*/
SC.typeOf = function(item) {
  var ret;

  ret = item==null ? String(item) : TYPE_MAP[toString.call(item)]||'object';

  if (ret === 'function') {
    if (SC.Object && SC.Object.detect(item)) ret = 'class';
  } else if (ret === 'object') {
    if (item instanceof Error) ret = 'error';
    else if (SC.Object && item instanceof SC.Object) ret = 'instance';
    else ret = 'object';
  }

  return ret;
};

/**
  Returns YES if the passed value is null or undefined.  This avoids errors
  from JSLint complaining about use of ==, which can be technically
  confusing.

  @param {Object} obj Value to test
  @returns {Boolean}
*/
SC.none = function(obj) {
  return obj === null || obj === undefined;
};

/**
  Verifies that a value is either null or an empty string. Return false if
  the object is not a string.

  @param {Object} obj Value to test
  @returns {Boolean}
*/
SC.empty = function(obj) {
  return obj === null || obj === undefined || obj === '';
};

/**
  SC.isArray defined in sproutcore-metal/lib/utils
**/

/**
 This will compare two javascript values of possibly different types.
 It will tell you which one is greater than the other by returning:

  - -1 if the first is smaller than the second,
  - 0 if both are equal,
  - 1 if the first is greater than the second.

 The order is calculated based on SC.ORDER_DEFINITION, if types are different.
 In case they have the same type an appropriate comparison for this type is made.

 @param {Object} v First value to compare
 @param {Object} w Second value to compare
 @returns {Number} -1 if v < w, 0 if v = w and 1 if v > w.
*/
SC.compare = function (v, w) {
  if (v === w) { return 0; }

  var type1 = SC.typeOf(v);
  var type2 = SC.typeOf(w);

  var Comparable = SC.Comparable;
  if (Comparable) {
    if (type1==='instance' && Comparable.detect(v.constructor)) {
      return v.constructor.compare(v, w);
    }

    if (type2 === 'instance' && Comparable.detect(w.constructor)) {
      return 1-w.constructor.compare(w, v);
    }
  }

  // If we haven't yet generated a reverse-mapping of SC.ORDER_DEFINITION,
  // do so now.
  var mapping = SC.ORDER_DEFINITION_MAPPING;
  if (!mapping) {
    var order = SC.ORDER_DEFINITION;
    mapping = SC.ORDER_DEFINITION_MAPPING = {};
    var idx, len;
    for (idx = 0, len = order.length; idx < len;  ++idx) {
      mapping[order[idx]] = idx;
    }

    // We no longer need SC.ORDER_DEFINITION.
    delete SC.ORDER_DEFINITION;
  }

  var type1Index = mapping[type1];
  var type2Index = mapping[type2];

  if (type1Index < type2Index) { return -1; }
  if (type1Index > type2Index) { return 1; }

  // types are equal - so we have to check values now
  switch (type1) {
    case 'boolean':
    case 'number':
      if (v < w) { return -1; }
      if (v > w) { return 1; }
      return 0;

    case 'string':
      var comp = v.localeCompare(w);
      if (comp < 0) { return -1; }
      if (comp > 0) { return 1; }
      return 0;

    case 'array':
      var vLen = v.length;
      var wLen = w.length;
      var l = Math.min(vLen, wLen);
      var r = 0;
      var i = 0;
      var thisFunc = arguments.callee;
      while (r === 0 && i < l) {
        r = thisFunc(v[i],w[i]);
        i++;
      }
      if (r !== 0) { return r; }

      // all elements are equal now
      // shorter array should be ordered first
      if (vLen < wLen) { return -1; }
      if (vLen > wLen) { return 1; }
      // arrays are equal now
      return 0;

    case 'instance':
      if (SC.Comparable && SC.Comparable.detect(v)) {
        return v.compare(v, w);
      }
      return 0;

    default:
      return 0;
  }
};

function _copy(obj, deep, seen, copies) {
  var ret, loc, key;

  // primitive data types are immutable, just return them.
  if ('object' !== typeof obj || obj===null) return obj;

  // avoid cyclical loops
  if (deep && (loc=seen.indexOf(obj))>=0) return copies[loc];

  sc_assert('Cannot clone an SC.Object that does not implement SC.Copyable', !(obj instanceof SC.Object) || (SC.Copyable && SC.Copyable.detect(obj)));

  // IMPORTANT: this specific test will detect a native array only.  Any other
  // object will need to implement Copyable.
  if (SC.typeOf(obj) === 'array') {
    ret = obj.slice();
    if (deep) {
      loc = ret.length;
      while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies);
    }
  } else if (SC.Copyable && SC.Copyable.detect(obj)) {
    ret = obj.copy(deep, seen, copies);
  } else {
    ret = {};
    for(key in obj) {
      if (!obj.hasOwnProperty(key)) continue;
      ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key];
    }
  }

  if (deep) {
    seen.push(obj);
    copies.push(ret);
  }

  return ret;
}

/**
  Creates a clone of the passed object. This function can take just about
  any type of object and create a clone of it, including primitive values
  (which are not actually cloned because they are immutable).

  If the passed object implements the clone() method, then this function
  will simply call that method and return the result.

  @param {Object} object The object to clone
  @param {Boolean} deep If true, a deep copy of the object is made
  @returns {Object} The cloned object
*/
SC.copy = function(obj, deep) {
  // fast paths
  if ('object' !== typeof obj || obj===null) return obj; // can't copy primitives
  if (SC.Copyable && SC.Copyable.detect(obj)) return obj.copy(deep);
  return _copy(obj, deep, deep ? [] : null, deep ? [] : null);
};

/**
  Convenience method to inspect an object. This method will attempt to
  convert the object into a useful string description.

  @param {Object} obj The object you want to inspec.
  @returns {String} A description of the object
*/
SC.inspect = function(obj) {
  var v, ret = [];
  for(var key in obj) {
    if (obj.hasOwnProperty(key)) {
      v = obj[key];
      if (v === 'toString') { continue; } // ignore useless items
      if (SC.typeOf(v) === 'function') { v = "function() { ... }"; }
      ret.push(key + ": " + v);
    }
  }
  return "{" + ret.join(" , ") + "}";
};

/**
  Compares two objects, returning true if they are logically equal.  This is
  a deeper comparison than a simple triple equal.  For arrays and enumerables
  it will compare the internal objects.  For any other object that implements
  `isEqual()` it will respect that method.

  @param {Object} a first object to compare
  @param {Object} b second object to compare
  @returns {Boolean}
*/
SC.isEqual = function(a, b) {
  if (a && 'function'===typeof a.isEqual) return a.isEqual(b);
  return a === b;
};

/**
  @private
  Used by SC.compare
*/
SC.ORDER_DEFINITION = SC.ENV.ORDER_DEFINITION || [
  'undefined',
  'null',
  'boolean',
  'number',
  'string',
  'array',
  'object',
  'instance',
  'function',
  'class'
];

/**
  Returns all of the keys defined on an object or hash. This is useful
  when inspecting objects for debugging.  On browsers that support it, this
  uses the native Object.keys implementation.

  @function
  @param {Object} obj
  @returns {Array} Array containing keys of obj
*/
SC.keys = Object.keys;

if (!SC.keys) {
  SC.keys = function(obj) {
    var ret = [];
    for(var key in obj) {
      if (obj.hasOwnProperty(key)) { ret.push(key); }
    }
    return ret;
  };
}

// ..........................................................
// ERROR
//

/**
  @class

  A subclass of the JavaScript Error object for use in SproutCore.
*/
SC.Error = function() {
  var tmp = Error.prototype.constructor.apply(this, arguments);

  for (var p in tmp) {
    if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }
  }
};

SC.Error.prototype = SC.create(Error.prototype);

// ..........................................................
// LOGGER
//

/**
  @class

  Inside SproutCore-Runtime, simply uses the window.console object.
  Override this to provide more robust logging functionality.
*/
SC.Logger = window.console;
<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//$.ajaxSetup provides the default settings for $.ajax()
// beforeSend - pre-request callback used to modify jqXHR (XMLHTTPRequest). Returning false in this function cancels the request.
// data - data to be sent to server, converted to a questy string. Object is key:value pair
/*success - function to be called with the request succeeds. data - data retunred from the server (formatted according
to dataType parameter), string describing statys and the jqXHR (XMLHTTPRequest object). In the code below,
xhr is used to specify jqXHR

jqXHR object- jQuery XMLHTTPRequest is superset of XMLHTTPRequest. It contains- responseTest, responseXML, getResponseHeader() method.
The XMLHttpRequest object is used to exchange data with a server behind the scenes.

*/

$(window).load(function(){
$.ajaxSetup({
'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

//sending height, width of resizable image. ID is sent as rid
  $("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

//sending height, width of resizable image. ID is sent as rid
$("#.cat img").load( function(){
$("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

});

// Making all cats draggable

    $("#cat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#cat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#cat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#cat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

// Making all hats draggable
    $("#hat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#hat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#hat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	  $("#hat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#hat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#hat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

  $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this ).find( "p" ).hide();
        var offset1=$("#droppable").offset();
$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ top: ui.offset["top"], left: ui.offset["left"], pid: (ui.draggable).attr("id"), backx: offset1.left, backy: offset1.top  },
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){alert('Failure')}
});
      }
    });

	       $("#various1").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

	       $("#various2").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

		  $("#various3").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

          $("#various4").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });
		$("#uploadcat").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'type' : 'iframe'
		   });

});

$(window).resize (function() {
 clearTimeout (resizeTimer);
 resizeTimer=setTimeout(doSomething,100);

});

function doSomething(){
var offset1 = $("#droppable").offset();
$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ backx: offset1.left, backy: offset1.top  },
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){alert('Failure')}
});
}

<commit_msg>sending coordinates of the background image<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//$.ajaxSetup provides the default settings for $.ajax()
// beforeSend - pre-request callback used to modify jqXHR (XMLHTTPRequest). Returning false in this function cancels the request.
// data - data to be sent to server, converted to a questy string. Object is key:value pair
/*success - function to be called with the request succeeds. data - data retunred from the server (formatted according
to dataType parameter), string describing statys and the jqXHR (XMLHTTPRequest object). In the code below,
xhr is used to specify jqXHR

jqXHR object- jQuery XMLHTTPRequest is superset of XMLHTTPRequest. It contains- responseTest, responseXML, getResponseHeader() method.
The XMLHttpRequest object is used to exchange data with a server behind the scenes.

*/

$(window).load(function(){
$.ajaxSetup({
'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

//sending height, width of resizable image. ID is sent as rid
  $("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

//sending height, width of resizable image. ID is sent as rid
$("#.cat img").load( function(){
$("#.cat img").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true,
  stop: function(event, ui) {

$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ width: ui.size["width"], height: ui.size["height"], rid:$(this).parent().attr('id')},
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){ //alert('Failure')
}
});
}
});

});

// Making all cats draggable

    $("#cat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#cat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#cat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#cat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#cat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

// Making all hats draggable
    $("#hat1").draggable({containment: "#droppable", snap:false, cursor: "move"});
$("#hat2").draggable({containment: "#droppable", snap:false, cursor: "move"});
    $("#hat3").draggable({containment: "#droppable", snap:false, cursor: "move"});
	  $("#hat4").draggable({containment: "#droppable", snap:false, cursor: "move"});
	$("#hat5").draggable({containment: "#droppable", snap:false, cursor: "move"});
	    $("#hat6").draggable({containment: "#droppable", snap:false, cursor: "move"});

  $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this ).find( "p" ).hide();
        var offset1=$("#droppable").offset();
$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ top: ui.offset["top"], left: ui.offset["left"], pid: (ui.draggable).attr("id"), backx: offset1.left, backy: offset1.top  },
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){alert('Failure')}
});
      }
    });

	       $("#various1").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

	       $("#various2").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

		  $("#various3").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });

          $("#various4").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
		   });
		$("#uploadcat").fancybox({
					'titlePosition'		: 'inside',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'type' : 'iframe'
		   });

});

$(window).resize (function() {
 clearTimeout (resizeTimer);
 resizeTimer=setTimeout(function (){
var offset1 = $("#droppable").offset();
$.ajax({
type: 'POST',
url: 'http://high-robot-603.heroku.com/jmsg',
dataType: 'json',
data:{ backx: offset1.left, backy: offset1.top  },
success: function(json, status, xhr)
{ // alert ('Success')
//$("#show_message").html("hello world");
},
error: function(data, status, xhr){alert('Failure')}
});
},100);

});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  Text,
  View,
  Image,
  TouchableHighlight,
  TouchableOpacity,
  Switch
} from 'react-native';
import styles from '../styles.ios.js';
import Nav from './Navbar.ios.js';
import SearchBar from './Searchbar.ios.js';
import { connect } from "react-redux";
import {bindActionCreators} from 'redux';
import * as app from '../actions/appActions.ios.js';
import getApp from '../reducers/appReducers.ios.js';
import camera from './Camera.ios.js';
import FacebookLogin from './FacebookLogin.ios.js';

class App extends Component {
  constructor(props) {
    super(props);
  }

  border(color) {
    return {
      borderColor: color,
      borderWidth: 5,
    }
  }

  changeNavigationHome() {
    this.props.navigator.push({
      id: 'Home'
    })
  }

  changeNavigationCamera() {
    this.props.navigator.push({
      component: camera,
      passProps: { store: this.props.store }
    })
  }

  rendering() {
    actions.rendering();
    this.forceUpdate()
  }
  render() {
    const {state, actions} = this.props;
    if (state.rendering) {
      return (
        <Image
          source= {{uri: 'https://media.blueapron.com/assets/loader/pot-loader-6047abec2ec57c18d848f623c036f7fe80236dce689bb48279036c4f914d0c9e.gif'}}
          style = {styles.loadingGif}
        />
      )
    }
    return (
      <View style={[styles.container]}>
        <View style={[styles.navigation]} >
          <Nav
            changeNavigationCamera={this.changeNavigationCamera.bind(this)}
          />
        </View>
        <View style={styles.app} >
          <Image style={styles.welcomeImage} source={require('../public/snacktimewelcome.jpg')}/>
          <FacebookLogin />
        </View>
        { /* conditional camera / search bar render */
          state.showSearchBar
            ?
              (
                <View style={[styles.searchBarPictureFrame]} >
                  <SearchBar store={this.props.store}
                             navigator={this.props.navigator}
                             rendering={actions.rendering}
                             lagOut={actions.laggedOut}
                             isRendering={state.rendering}
                  />
                </View>
              )
            :
              (
                <TouchableHighlight style={[styles.buttonView]}
                                    onPress={this.changeNavigationCamera.bind(this)}
                >
                  <Image
                    style={[styles.takePicture]}
                    source={{uri: 'https://s3.amazonaws.com/features.ifttt.com/newsletter_images/2015_February/camera512x512+(1).png'}}
                  />
                </TouchableHighlight>
              )
        }
        <View style={{flexDirection: 'row'}}>
          <Switch
            onValueChange={actions.showSearchBar}
            style={styles.switch}
            value={state.showSearchBar}
          />
        </View>
      </View>
    );
  }
}

export default connect(state => ({
    state: state.app
  }),
  (dispatch) => ({
    actions: bindActionCreators(app.default, dispatch)
  })
)(App);
<commit_msg>(code refactor) minor code cleanup<commit_after>import React, { Component } from 'react';
import {
  Text,
  View,
  Image,
  TouchableHighlight,
  TouchableOpacity,
  Switch,
  Linking
} from 'react-native';
import styles from '../styles.ios.js';
import Nav from './Navbar.ios.js';
import SearchBar from './Searchbar.ios.js';
import { connect } from "react-redux";
import {bindActionCreators} from 'redux';
import * as app from '../actions/appActions.ios.js';
import getApp from '../reducers/appReducers.ios.js';
import camera from './Camera.ios.js';
import FacebookLogin from './FacebookLogin.ios.js';
var SafariView = require('react-native-safari-view');

class App extends Component {
  constructor(props) {
    super(props);
  }

  border(color) {
    return {
      borderColor: color,
      borderWidth: 5,
    }
  }

  changeNavigationHome() {
    this.props.navigator.push({
      id: 'Home'
    })
  }

  changeNavigationCamera() {
    this.props.navigator.push({
      component: camera,
      passProps: { store: this.props.store }
    })
  }

  handleTwitterLogin() {
    SafariView.isAvailable()
      .then(SafariView.show({
        url: 'https://github.com/naoufal'
      }))
      .catch(error => {
        // Fallback WebView code for iOS 8 and earlier
        Linking.openURL('https://api.twitter.com/oauth/authenticate?oauth_token=')
      });
  }

  rendering() {
    actions.rendering();
    this.forceUpdate()
  }

  render() {
    const {state, actions} = this.props;
    if (state.rendering) {
      return (
        <Image
          source= {{uri: 'https://media.blueapron.com/assets/loader/pot-loader-6047abec2ec57c18d848f623c036f7fe80236dce689bb48279036c4f914d0c9e.gif'}}
          style = {styles.loadingGif}
        />
      )
    }
    return (
      <View style={[styles.container]}>
        <View style={[styles.navigation]} >
          <Nav
            changeNavigationCamera={this.changeNavigationCamera.bind(this)}
          />
        </View>
        <View style={styles.app} >
          <Image style={styles.welcomeImage} source={require('../public/snacktimewelcome.jpg')}/>
          <FacebookLogin />

          {/* Experimental twitter OAuth safari view controller 3-legged OAuth login */}
          <TouchableOpacity onPress={() => handleTwitterLogin()}>

          </TouchableOpacity>

        </View>
        { /* conditional camera / search bar render */
          state.showSearchBar
            ?
              (
                <View style={[styles.searchBarPictureFrame]} >
                  <SearchBar store={this.props.store}
                             navigator={this.props.navigator}
                             rendering={actions.rendering}
                             lagOut={actions.laggedOut}
                             isRendering={state.rendering}
                  />
                </View>
              )
            :
              (
                <TouchableHighlight style={[styles.buttonView]}
                                    onPress={this.changeNavigationCamera.bind(this)}
                >
                  <Image
                    style={[styles.takePicture]}
                    source={{uri: 'https://s3.amazonaws.com/features.ifttt.com/newsletter_images/2015_February/camera512x512+(1).png'}}
                  />
                </TouchableHighlight>
              )
        }
        <View style={{flexDirection: 'row'}}>
          <Switch
            onValueChange={actions.showSearchBar}
            style={styles.switch}
            value={state.showSearchBar}
          />
        </View>
      </View>
    );
  }
}

export default connect(state => ({
    state: state.app
  }),
  (dispatch) => ({
    actions: bindActionCreators(app.default, dispatch)
  })
)(App);
<|endoftext|>


<commit_before>// Copyright (c) 2014 Turbulenz Limited
/* global Protolib: false*/
/* global Config: false*/
/* global Floor: false*/
/* global PhysicsManager: false */

function Application() {}
Application.prototype =
    {
    // Use the properties from Config by default, otherwise use these defaults
    protolibConfig: Protolib.extend(true, {
        fps: 60,
        useShadows: true
    },
                                    Config),

    init: function initFn()
    {
        var errorCallback = function errorCallback(msg) {
            window.alert(msg);
        };
        TurbulenzEngine.onerror = errorCallback;

        var warningCallback = function warningCallback(msg) {
            window.alert(msg);
        };
        TurbulenzEngine.onwarning = warningCallback;

        var protolib = this.protolib;
        var version = protolib.version;
        var requiredVersion = [0, 2, 1];
        if (version === undefined ||
            version[0] !== requiredVersion[0] ||
            version[1] !== requiredVersion[1] ||
            version[2] !== requiredVersion[2])
        {
            protolib.utils.error("Protolib is not requiredVersion");
            return false;
        }

        var mathDevice = protolib.getMathDevice();
        var graphicsDevice = protolib.getGraphicsDevice();
        var inputDevice = protolib.getInputDevice();
        var draw2D = protolib.globals.draw2D;
        var camera = protolib.globals.camera;
        var scene = protolib.globals.scene;

        protolib.setClearColor(mathDevice.v3Build(0.0, 0.0, 0.0));

        // Initialization code goes here

        this.realTime = 0;

        var floor = this.floor = Floor.create(graphicsDevice, mathDevice);
        var cameraController = this.cameraController = CameraController.create(graphicsDevice, inputDevice, camera);

        // positio camera
        protolib.moveCamera(mathDevice.v3Build(0, 5, -10));
        protolib.setCameraDirection(mathDevice.v3Build(0, -0.2, -1));

        // Physics
        var physicsDeviceParameters = {};
        var physicsDevice = TurbulenzEngine.createPhysicsDevice(physicsDeviceParameters);

        var dynamicsWorldParameters = {};
        var dynamicsWorld = this.dynamicsWorld = physicsDevice.createDynamicsWorld(dynamicsWorldParameters);
        var physicsManager = this.physicsManager = PhysicsManager.create(mathDevice, physicsDevice, dynamicsWorld);

        // Floor is represented by a plane
        var floorShape = physicsDevice.createPlaneShape({
            normal: mathDevice.v3Build(0, 1, 0),
            distance: 0,
            margin: 0.005
        });

        var floorSceneNode = SceneNode.create({
            name: "Floor1",
            local: mathDevice.m43BuildTranslation(0, 0, 0),
            dynamic: true,
            disabled: false
        });

        var floorRigidBody = physicsDevice.createCollisionObject({
            shape: floorShape,
            transform: mathDevice.m43BuildIdentity(),
            friction: 0.5,
            restitution: 0.3,
            group: physicsDevice.FILTER_STATIC,
            mask: physicsDevice.FILTER_ALL
        });

        this.physicsManager.addNode(floorSceneNode, floorRigidBody);

        // Create the collision box
        var collisionBoxSize = mathDevice.v3Build(0.5, 0.5, 0.5);
        var boxShape = physicsDevice.createBoxShape({
            halfExtents: collisionBoxSize,
            margin: 0.001
        });

        var boxSceneNode = SceneNode.create({
            name: "Box1",
            local: mathDevice.m43BuildTranslation(0, 0, 0),
            dynamic: true,
            disabled: false
        });

        var boxRigidBody = physicsDevice.createRigidBody({
            shape: boxShape,
            mass: 10.0,
            inertia: mathDevice.v3ScalarMul(boxShape.inertia, 10.0),
            transform: mathDevice.m43BuildTranslation(0, 5, 0),
            friction: 0.8,
            restitution: 0.2,
            angularDamping: 0.4,
            linearVelocity: mathDevice.v3Build(0, 0, 0)
        });

        this.physicsManager.addNode(boxSceneNode, boxRigidBody);

        protolib.setPreDraw(function drawFn() {

            cameraController.update();
            dynamicsWorld.update();
            physicsManager.update();

        });

        protolib.setPreRendererDraw(function renderDrawFn() {

            floor.render(graphicsDevice, camera);
            scene.drawPhysicsGeometry(graphicsDevice, protolib.globals.shaderManager, camera, physicsManager);

        });

        return true;
    },

    reset: function resetFn()
    {

    },

    update: function updateFn()
    {
        var protolib = this.protolib;
        var mathDevice = protolib.getMathDevice();
        var graphicsDevice = protolib.getGraphicsDevice();
        var delta = protolib.time.app.delta;
        var camera = protolib.globals.camera;

        if (protolib.beginFrame())
        {
            // Update code goes here

            protolib.drawText({
                text: "Hello World!",
                position: mathDevice.v3Build(200, 100, 1),
                scale: 5,
                v3Color: mathDevice.v3Build(1.0, 1.0, 1.0)
            });

            protolib.endFrame();
        }
    },

    destroy: function destroyFn()
    {
        var protolib = this.protolib;
        if (protolib)
        {
            // Destruction code goes here
            protolib.destroy();
            this.protolib = null;
        }
    }
};

// Application constructor function
Application.create = function applicationCreateFn(params)
{
    var app = new Application();
    app.protolib = params.protolib;
    if (!app.protolib)
    {
        var console = window.console;
        if (console)
        {
            console.error("Protolib could not be found");
        }
        return null;
    }
    if (!app.init())
    {
        app.protolib.utils.error("Protolib could not be initialized");
        return null;
    }
    return app;
};
<commit_msg>basic setup finish<commit_after>// Copyright (c) 2014 Turbulenz Limited
/* global Protolib: false*/
/* global Config: false*/
/* global Floor: false*/
/* global PhysicsManager: false */

function Application() {}
Application.prototype =
    {
    // Use the properties from Config by default, otherwise use these defaults
    protolibConfig: Protolib.extend(true, {
        fps: 60,
        useShadows: true
    },
                                    Config),

    init: function initFn()
    {
        var errorCallback = function errorCallback(msg) {
            window.alert(msg);
        };
        TurbulenzEngine.onerror = errorCallback;

        var warningCallback = function warningCallback(msg) {
            window.alert(msg);
        };
        TurbulenzEngine.onwarning = warningCallback;

        var protolib = this.protolib;
        var version = protolib.version;
        var requiredVersion = [0, 2, 1];
        if (version === undefined ||
            version[0] !== requiredVersion[0] ||
            version[1] !== requiredVersion[1] ||
            version[2] !== requiredVersion[2])
        {
            protolib.utils.error("Protolib is not requiredVersion");
            return false;
        }

        var mathDevice = protolib.getMathDevice();
        var graphicsDevice = protolib.getGraphicsDevice();
        var inputDevice = protolib.getInputDevice();
        var draw2D = protolib.globals.draw2D;
        var camera = protolib.globals.camera;
        var scene = protolib.globals.scene;

        protolib.setClearColor(mathDevice.v3Build(0.0, 0.0, 0.0));

        // Initialization code goes here

        this.realTime = 0;

        var floor = this.floor = Floor.create(graphicsDevice, mathDevice);
        var cameraController = this.cameraController = CameraController.create(graphicsDevice, inputDevice, camera);

        // positio camera
        protolib.moveCamera(mathDevice.v3Build(0, 5, -10));
        protolib.setCameraDirection(mathDevice.v3Build(0, -0.2, -1));

        // Physics
        var physicsDeviceParameters = {};
        var physicsDevice = TurbulenzEngine.createPhysicsDevice(physicsDeviceParameters);

        var dynamicsWorldParameters = {};
        var dynamicsWorld = this.dynamicsWorld = physicsDevice.createDynamicsWorld(dynamicsWorldParameters);
        var physicsManager = this.physicsManager = PhysicsManager.create(mathDevice, physicsDevice, dynamicsWorld);

        // Create floor
        var floorShape = physicsDevice.createPlaneShape({
            normal: mathDevice.v3Build(0, 1, 0),
            distance: 0,
            margin: 0.005
        });

        var floorSceneNode = SceneNode.create({
            name: "Floor1",
            local: mathDevice.m43BuildTranslation(0, 0, 0),
            dynamic: true,
            disabled: false
        });

        var floorRigidBody = physicsDevice.createCollisionObject({
            shape: floorShape,
            transform: mathDevice.m43BuildTranslation(0, 0, 0),
            friction: 0.5,
            restitution: 0.3,
            group: physicsDevice.FILTER_STATIC,
            mask: physicsDevice.FILTER_ALL
        });

        this.physicsManager.addNode(floorSceneNode, floorRigidBody);

        // Create box
        var collisionBoxSize = mathDevice.v3Build(0.5, 0.5, 0.5);
        var boxShape = physicsDevice.createBoxShape({
            halfExtents: collisionBoxSize,
            margin: 0.001
        });

        var boxRigidbody = physicsDevice.createRigidBody({
            shape: boxShape,
            mass: 10.0,
            inertia: mathDevice.v3ScalarMul(boxShape.inertia, 10.0),
            transform: mathDevice.m43BuildTranslation(0, 7, 0),
            friction: 0.1,
            restitution: 0.2,
            angularDamping: 0.4
        });

        var boxMesh = protolib.loadMesh({
            mesh: "models/cube.dae",
            v3Position: mathDevice.v3Build(0, 7, 0),
            v3Size: mathDevice.v3Build(1.0, 1.0, 1.0)
        });

        this.physicsManager.addNode(boxMesh.node, boxRigidbody);

        // Add light
        protolib.setAmbientLightColor(mathDevice.v3Build(1, 1, 1));

        // Controls
        var settings = {
            debug: false
        }
        protolib.addWatchVariable({
            title: "Enable Debugging",
            object: settings,
            property: "debug",
            group: "Settings",
            type: protolib.watchTypes.SLIDER,
            options: {
                min: 0,
                max: 1,
                step: 1
            }
        });

        protolib.setPreDraw(function drawFn() {

            cameraController.update();
            dynamicsWorld.update();
            physicsManager.update();

        });

        protolib.setPreRendererDraw(function renderDrawFn() {

            floor.render(graphicsDevice, camera);
            if (settings.debug) {
                scene.drawPhysicsNodes(graphicsDevice, protolib.globals.shaderManager, camera, physicsManager);
                scene.drawPhysicsGeometry(graphicsDevice, protolib.globals.shaderManager, camera, physicsManager);
            }

        });

        return true;
    },

    reset: function resetFn()
    {

    },

    update: function updateFn()
    {
        var protolib = this.protolib;
        var mathDevice = protolib.getMathDevice();
        var graphicsDevice = protolib.getGraphicsDevice();
        var delta = protolib.time.app.delta;
        var camera = protolib.globals.camera;

        if (protolib.beginFrame())
        {
            // Update code goes here

            protolib.drawText({
                text: "Hello World!",
                position: mathDevice.v3Build(200, 100, 1),
                scale: 5,
                v3Color: mathDevice.v3Build(1.0, 1.0, 1.0)
            });

            protolib.endFrame();
        }
    },

    destroy: function destroyFn()
    {
        var protolib = this.protolib;
        if (protolib)
        {
            // Destruction code goes here
            protolib.destroy();
            this.protolib = null;
        }
    }
};

// Application constructor function
Application.create = function applicationCreateFn(params)
{
    var app = new Application();
    app.protolib = params.protolib;
    if (!app.protolib)
    {
        var console = window.console;
        if (console)
        {
            console.error("Protolib could not be found");
        }
        return null;
    }
    if (!app.init())
    {
        app.protolib.utils.error("Protolib could not be initialized");
        return null;
    }
    return app;
};
<|endoftext|>


<commit_before>$(document).ready(function() {
  init_geolocal();
  $("form.nestedAnswerForm").hide();
  $("#add_comment_form").hide();
  $("form").live('submit', function() {
    var textarea = $(this).find('textarea');
    removeFromLocalStorage(location.href, textarea.attr('id'));
    window.onbeforeunload = null;
  });

  $('.confirm-domain').submit(function(){
      var bool = confirm($(this).attr('data-confirm'));
      if(bool==false) return false;

  })
  $("#feedbackform").dialog({ title: "Feedback", autoOpen: false, modal: true, width:"420px" })
  $('#feedbackform .cancel-feedback').click(function(){
    $("#feedbackform").dialog('close');
    return false;
  })
  $('#feedback').click(function(){
    var isOpen = $("#feedbackform").dialog('isOpen');
    if (isOpen){
      $("#feedbackform").dialog('close');
    } else {
      $("#feedbackform").dialog('open');
    }
    return false;
  })

  $('.autocomplete_for_tags').ricodigoComplete();
  $('#quick_question').find('.tagwrapper').css({'margin-left':'18px',width:'68%'});
  if(supports_input_placeholder()){$('.hideifplaceholder').remove();};
  $(".quick-vote-button").live("click", function(event) {
    var btn = $(this);
    btn.hide();
    var src = btn.attr('src');
    if (src.indexOf('/images/dialog-ok.png') == 0){
      var btn_name = $(this).attr("name")
      var form = $(this).parents("form");
      $.post(form.attr("action"), form.serialize()+"&"+btn_name+"=1", function(data){
        if(data.success){
          btn.parents('.item').find('.votes .counter').text(data.average);
          btn.attr('src', '/images/dialog-ok-apply.png');
          showMessage(data.message, "notice")
        } else {
          showMessage(data.message, "error")
          if(data.status == "unauthenticate") {
            window.onbeforeunload = null;
            window.location="/users/login"
          }
        }
        btn.show();
      }, "json");
    }
    return false;
  });

  $("a#hide_announcement").click(function() {
    $("#announcement").fadeOut();
    $.post($(this).attr("href"), "format=js");
    return false;
  });

  $('textarea').live('keyup',function(){
      var value = $(this).val();
      var id = $(this).attr('id');
      addToLocalStorage(location.href, id, value);
  })

  initStorageMethods();
  fillTextareas();

  $(".highlight_for_user").effect("highlight", {}, 2000);
  sortValues('#group_language', 'option', ':last', 'text', null);
  sortValues('#language_filter', 'option',  ':lt(2)', 'text', null);
  sortValues('#user_language', 'option',  false, 'text', null);
  sortValues('#lang_opts', '.radio_option', false, 'attr', 'id');

  $('.langbox.jshide').hide();
  $('.show-more-lang').click(function(){
      $('.langbox.jshide').toggle();
      return false;
  })
})

function manageAjaxError(XMLHttpRequest, textStatus, errorThrown) {
  showMessage("sorry, something went wrong.", "error");
}

function showMessage(message, t, delay) {
  $("#notifyBar").remove();
  $.notifyBar({
    html: "
"+message+"
",
    delay: delay||3000,
    animationSpeed: "normal",
    barClass: "flash"
  });
}

function hasStorage(){
  if (window.localStorage && typeof(Storage)!='undefined'){
    return true;
  } else {
      return false;
  }
}

function initStorageMethods(){
  if(hasStorage()){
    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    }

    Storage.prototype.getObject = function(key) {
        return JSON.parse(this.getItem(key));
    }
  }
}

function fillTextareas(){
   if(hasStorage() && localStorage[location.href]!=null && localStorage[location.href]!='null'){
       localStorageArr = localStorage.getObject(location.href);
       $.each(localStorageArr, function(i, n){
           $("#"+n.id).val(n.value);
           $("#"+n.id).parents('form.commentForm').show();
           $("#"+n.id).parents('form.nestedAnswerForm').show();
       })
    }
}

function addToLocalStorage(key, id, value){
  if(hasStorage()){
    var ls = localStorage[key];
    if($.trim(value)!=""){
      if(ls == null || ls == "null" || typeof(ls)=="undefined"){
          localStorage.setObject(key,[{id: id, value: value}]);
      } else {
          var storageArr = localStorage.getObject(key);
          var isIn = false;
          storageArr = $.map(storageArr, function(n, i){
              if(n.id == id){
                n.value = value;
                isIn = true;
              }
          return n;
        })
      if(!isIn)
        storageArr = $.merge(storageArr, [{id: id, value: value}]);
      localStorage.setObject(key, storageArr);
    }
    } else {removeFromLocalStorage(key, id);}
  }
}

function removeFromLocalStorage(key, id){
  if(hasStorage()){
    var ls = localStorage[key];
    if(typeof(ls)=='string'){
      var storageArr = localStorage.getObject(key);

      storageArr = $.map(storageArr, function(n, i){
          if(n.id == id){
            return null;
          } else {
              return n;
          }
      })
      localStorage.setObject(key, storageArr);
    }
  }
}

function sortValues(selectID, child, keepers, method, arg){
  if(keepers){
    var any = $(selectID+' '+child+keepers);
    any.remove();
  }
  var sortedVals = $.makeArray($(selectID+' '+child)).sort(function(a,b){
    return $(a)[method](arg) > $(b)[method](arg) ? 1: -1;
  });
  $(selectID).empty().html(sortedVals);
  if(keepers)
    $(selectID).prepend(any);
  // needed for firefox:
  $(selectID).val($(selectID+' '+child+'[selected=selected]').val());
};

function highlightEffect(object) {
  if(typeof object != "undefined") {
    object.fadeOut(400, function() {
      object.fadeIn(400)
    });
  }
}

function supports_input_placeholder() {
  var i = document.createElement('input');
  return 'placeholder' in i;
}

function init_geolocal(){
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){
        $('.lat_input').val(position.coords.latitude)
        $('.long_input').val(position.coords.longitude)
    }, function(){});
  } else {
      //error('not supported');
  }
}<commit_msg>only ask for location when focus on textarea<commit_after>$(document).ready(function() {
  init_geolocal();
  $("form.nestedAnswerForm").hide();
  $("#add_comment_form").hide();
  $("form").live('submit', function() {
    var textarea = $(this).find('textarea');
    removeFromLocalStorage(location.href, textarea.attr('id'));
    window.onbeforeunload = null;
  });

  $('.confirm-domain').submit(function(){
      var bool = confirm($(this).attr('data-confirm'));
      if(bool==false) return false;

  })
  $("#feedbackform").dialog({ title: "Feedback", autoOpen: false, modal: true, width:"420px" })
  $('#feedbackform .cancel-feedback').click(function(){
    $("#feedbackform").dialog('close');
    return false;
  })
  $('#feedback').click(function(){
    var isOpen = $("#feedbackform").dialog('isOpen');
    if (isOpen){
      $("#feedbackform").dialog('close');
    } else {
      $("#feedbackform").dialog('open');
    }
    return false;
  })

  $('.autocomplete_for_tags').ricodigoComplete();
  $('#quick_question').find('.tagwrapper').css({'margin-left':'18px',width:'68%'});
  if(supports_input_placeholder()){$('.hideifplaceholder').remove();};
  $(".quick-vote-button").live("click", function(event) {
    var btn = $(this);
    btn.hide();
    var src = btn.attr('src');
    if (src.indexOf('/images/dialog-ok.png') == 0){
      var btn_name = $(this).attr("name")
      var form = $(this).parents("form");
      $.post(form.attr("action"), form.serialize()+"&"+btn_name+"=1", function(data){
        if(data.success){
          btn.parents('.item').find('.votes .counter').text(data.average);
          btn.attr('src', '/images/dialog-ok-apply.png');
          showMessage(data.message, "notice")
        } else {
          showMessage(data.message, "error")
          if(data.status == "unauthenticate") {
            window.onbeforeunload = null;
            window.location="/users/login"
          }
        }
        btn.show();
      }, "json");
    }
    return false;
  });

  $("a#hide_announcement").click(function() {
    $("#announcement").fadeOut();
    $.post($(this).attr("href"), "format=js");
    return false;
  });

  $('textarea').live('keyup',function(){
      var value = $(this).val();
      var id = $(this).attr('id');
      addToLocalStorage(location.href, id, value);
  })

  initStorageMethods();
  fillTextareas();

  $(".highlight_for_user").effect("highlight", {}, 2000);
  sortValues('#group_language', 'option', ':last', 'text', null);
  sortValues('#language_filter', 'option',  ':lt(2)', 'text', null);
  sortValues('#user_language', 'option',  false, 'text', null);
  sortValues('#lang_opts', '.radio_option', false, 'attr', 'id');

  $('.langbox.jshide').hide();
  $('.show-more-lang').click(function(){
      $('.langbox.jshide').toggle();
      return false;
  })
})

function manageAjaxError(XMLHttpRequest, textStatus, errorThrown) {
  showMessage("sorry, something went wrong.", "error");
}

function showMessage(message, t, delay) {
  $("#notifyBar").remove();
  $.notifyBar({
    html: "
"+message+"
",
    delay: delay||3000,
    animationSpeed: "normal",
    barClass: "flash"
  });
}

function hasStorage(){
  if (window.localStorage && typeof(Storage)!='undefined'){
    return true;
  } else {
      return false;
  }
}

function initStorageMethods(){
  if(hasStorage()){
    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    }

    Storage.prototype.getObject = function(key) {
        return JSON.parse(this.getItem(key));
    }
  }
}

function fillTextareas(){
   if(hasStorage() && localStorage[location.href]!=null && localStorage[location.href]!='null'){
       localStorageArr = localStorage.getObject(location.href);
       $.each(localStorageArr, function(i, n){
           $("#"+n.id).val(n.value);
           $("#"+n.id).parents('form.commentForm').show();
           $("#"+n.id).parents('form.nestedAnswerForm').show();
       })
    }
}

function addToLocalStorage(key, id, value){
  if(hasStorage()){
    var ls = localStorage[key];
    if($.trim(value)!=""){
      if(ls == null || ls == "null" || typeof(ls)=="undefined"){
          localStorage.setObject(key,[{id: id, value: value}]);
      } else {
          var storageArr = localStorage.getObject(key);
          var isIn = false;
          storageArr = $.map(storageArr, function(n, i){
              if(n.id == id){
                n.value = value;
                isIn = true;
              }
          return n;
        })
      if(!isIn)
        storageArr = $.merge(storageArr, [{id: id, value: value}]);
      localStorage.setObject(key, storageArr);
    }
    } else {removeFromLocalStorage(key, id);}
  }
}

function removeFromLocalStorage(key, id){
  if(hasStorage()){
    var ls = localStorage[key];
    if(typeof(ls)=='string'){
      var storageArr = localStorage.getObject(key);

      storageArr = $.map(storageArr, function(n, i){
          if(n.id == id){
            return null;
          } else {
              return n;
          }
      })
      localStorage.setObject(key, storageArr);
    }
  }
}

function sortValues(selectID, child, keepers, method, arg){
  if(keepers){
    var any = $(selectID+' '+child+keepers);
    any.remove();
  }
  var sortedVals = $.makeArray($(selectID+' '+child)).sort(function(a,b){
    return $(a)[method](arg) > $(b)[method](arg) ? 1: -1;
  });
  $(selectID).empty().html(sortedVals);
  if(keepers)
    $(selectID).prepend(any);
  // needed for firefox:
  $(selectID).val($(selectID+' '+child+'[selected=selected]').val());
};

function highlightEffect(object) {
  if(typeof object != "undefined") {
    object.fadeOut(400, function() {
      object.fadeIn(400)
    });
  }
}

function supports_input_placeholder() {
  var i = document.createElement('input');
  return 'placeholder' in i;
}

function init_geolocal(){
  if (navigator.geolocation) {
    $('textarea, #question_title').live('focus', function(){
      navigator.geolocation.getCurrentPosition(function(position){
          $('.lat_input').val(position.coords.latitude)
          $('.long_input').val(position.coords.longitude)
      }, function(){});
    });
  } else {
      //error('not supported');
  }
}<|endoftext|>