<commit_before>var CloudCommander;
var CloudFunc;
CloudCommander.keyBinding=(function(){
    "use strict";
    var key_event=function(event){
            var lCurrentFile;
            var lName;
            /* если клавиши можно обрабатывать*/
            if(CloudCommander.keyBinded){
                /* если нажали таб:
                 * переносим курсор на
                 * правую панель, если
                 * мы были на левой и
                 * наоборот
                 */
                if(event.keyCode===9){
                    console.log('Tab pressed');
                    try{
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                    }catch(error){console.log(error);}
                }
                /* навигация по таблице файлов*/
                /* если нажали клавишу вверх*/
                else if(event.keyCode===38){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это строка существет и
                     * если она не заголовок
                     * файловой таблицы
                     */
                    if(lCurrentFile.previousSibling &&
                       lCurrentFile.previousSibling.className!=='fm_header' ){
                        /* убираем выделение с текущего элемента */
                        lCurrentFile.className='';
                        /* и выделяем предыдущую строку*/
                        lCurrentFile.previousSibling.className=CloudCommander.CURRENT_FILE;
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу в низ*/
                else if(event.keyCode===40){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это не последняя строка */
                    if(lCurrentFile.nextSibling){
                        /* убираем с него выделение */
                        lCurrentFile.className='';
                        /* выделяем следующую строку*/
                        lCurrentFile.nextSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.nextSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу page up или Home
                 * переходим к самому верхнему
                 * элементу
                 */
                else if(/*event.keyCode===33 ||*/ event.keyCode===36){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* убираем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* получаем первый элемент*/
                        lCurrentFile.parentElement.firstElementChild
                        /* пропускаем путь и заголовки столбиков*/
                            .nextElementSibling.nextElementSibling
                            /* выделяем верхий файл */
                            .className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали клавишу page down или End
                 * выделяем последний элемент
                 */
                else if(/*event.keyCode===34 ||*/ event.keyCode===35){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* снимаем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* выделяем самый нижний файл */
                        lCurrentFile.parentElement.lastElementChild.className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали Enter - открываем папку*/
                else if(event.keyCode===13){
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile.length)return;
                    lCurrentFile=lCurrentFile[0];
                    /* из него достаём спан с именем файла*/
                    lName=lCurrentFile.getElementsByClassName('name');
                    /* если нету (что вряд ли) - выходим*/
                    if(!lName)return false;
                    /* достаём все ссылки*/
                    var lATag=lName[0].getElementsByTagName('a');
                    /* если нету - выходим */
                    if(!lATag)return false;

                    /* вызываем ajaxload привязанный через changelinks
                     * пробулем нажать на ссылку, если не получиться
                     * (opera, ie), вызываем событие onclick,
                     * которое пока не прописано у файлов
                     */

                     if(lCurrentFile.onclick)lCurrentFile.onclick(true);
                     else try{
                         lATag[0].click();
                     }
                     catch(error){
                         console.log(error);
                     }
                }
                /* если нажали <ctr>+r
                 * обновляем страницу,
                 * загружаем содержимое каталога
                 * при этом данные берём всегда с
                 * сервера, а не из кэша
                 * (обновляем кэш)
                 */
                else if(event.keyCode===82 &&
                    event.ctrlKey){
                    console.log('<ctrl>+r pressed');
                    console.log('reloading page...');
                    console.log('press <alt>+q to remove all key-handlers');
                    /* Программно нажимаем на кнопку перезагрузки
                     * содержимого каталога
                     */
                    var lRefreshIcon=document.getElementsByClassName(CloudFunc.REFRESHICON);
                    if(lRefreshIcon)lRefreshIcon=lRefreshIcon[0];
                    if(lRefreshIcon){
                        /* находим файл который сейчас выделен */
                         lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                         if(lCurrentFile.length>0)lCurrentFile=lCurrentFile[0];
                         /* получаем название файла*/
                         var lSelectedName=lCurrentFile.getElementsByTagName('a')[0].textContent;
                         /* если нашли элемент нажимаем него
                          * а если не можем - нажимаем на
                          * ссылку, на которую повешен eventHandler
                          * onclick
                          */
                        if(lRefreshIcon.click)lRefreshIcon.parentElement.click();
                        else lRefreshIcon.parentElement.onclick();

                        /* перебираем файлы левой панели
                         * в поисках подсвеченого файла
                         */
                        var lLeft=document.getElementById('left');
                        if(lLeft){
                            /* перебираем все файлы в панели */
                            var lLi=lLeft.getElementsByTagName('li');
                            lCurrentFile.className='';
                            /* начинаем с 2-ух, по скольку
                             * 0 - это путь
                             * 1 - это заголовок файловой таблицы
                             */
                            for(var i=2;i<lLi.length;i++){
                                lName=lLi[i].getElementsByTagName('a')[0].textContent;
                                if(lSelectedName.length===lName.length &&
                                    !lSelectedName.indexOf(lName)){
                                        lLi[i].className=CloudCommander.CURRENT_FILE;
                                        break;
                                }
                            }
                        }

                        event.preventDefault();//запрет на дальнейшее действие
                    }
                }
                /* если нажали <ctrl>+d чистим кэш */
                else if(event.keyCode===68 &&
                    event.ctrlKey){
                        console.log('<ctrl>+d pressed');
                        console.log('clearing cache...');
                        console.log('press <alt>+q to remove all key-handlers');

                        var lClearCache=document.getElementById('clear-cache');
                        if(lClearCache && lClearCache.onclick)lClearCache.onclick();

                        event.preventDefault();//запрет на дальнейшее действие
                }
                /* если нажали <alt>+q
                 * убираем все обработчики
                 * нажатий клавиш
                 */
                else if(event.keyCode===81 &&
                    event.altKey){
                        //document.removeEventListener('keydown', key_event,false);
                        console.log('<alt>+q pressed');
                        console.log('<ctrl>+r reload key-handerl - removed');
                        console.log('<ctrl>+s clear cache key-handler - removed');
                        console.log('press <alt>+s to to set them');

                        /* обработчик нажатий клавиш снят*/
                        CloudCommander.keyBinded=false;
                }
            }
            /* если нажали <alt>+s
             * устанавливаем все обработчики
             * нажатий клавиш
             */
            else if(event.keyCode===83 &&
                event.altKey){
                    /*
                        document.addEventListener('keydown', key_event,false);
                    */
                    /* обрабатываем нажатия на клавиши*/
                    CloudCommander.keyBinded=true;

                    console.log('<alt>+s pressed');
                    console.log('<ctrl>+r reload key-handerl - set');
                    console.log('<ctrl>+s clear cache key-handler - set');
                    console.log('press <alt>+q to remove them');
            }

         return false;
    };
    /* добавляем обработчик клавишь */
    if(document.addEventListener)
        document.addEventListener('keydown', key_event,false);
    else document.onkeypress=key_event;
    /* клавиши назначены*/
    CloudCommander.keyBinded=true;
});<commit_msg>minor changes<commit_after>var CloudCommander;
var CloudFunc;
CloudCommander.keyBinding=(function(){
    "use strict";
    var key_event=function(event){
            var lCurrentFile;
            var lName;
            /* если клавиши можно обрабатывать*/
            if(CloudCommander.keyBinded){
                /* если нажали таб:
                 * переносим курсор на
                 * правую панель, если
                 * мы были на левой и
                 * наоборот
                 */
                if(event.keyCode===9){
                    console.log('Tab pressed');
                    try{
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                    }catch(error){console.log(error);}
                }
                /* навигация по таблице файлов*/
                /* если нажали клавишу вверх*/
                else if(event.keyCode===38){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это строка существет и
                     * если она не заголовок
                     * файловой таблицы
                     */
                    if(lCurrentFile.previousSibling &&
                       lCurrentFile.previousSibling.className!=='fm_header' ){
                        /* убираем выделение с текущего элемента */
                        lCurrentFile.className='';
                        /* и выделяем предыдущую строку*/
                        lCurrentFile.previousSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.nextSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу в низ*/
                else if(event.keyCode===40){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это не последняя строка */
                    if(lCurrentFile.nextSibling){
                        /* убираем с него выделение */
                        lCurrentFile.className='';
                        /* выделяем следующую строку*/
                        lCurrentFile.nextSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.nextSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу page up или Home
                 * переходим к самому верхнему
                 * элементу
                 */
                else if(/*event.keyCode===33 ||*/ event.keyCode===36){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* убираем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* получаем первый элемент*/
                        lCurrentFile.parentElement.firstElementChild
                        /* пропускаем путь и заголовки столбиков*/
                            .nextElementSibling.nextElementSibling
                            /* выделяем верхий файл */
                            .className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали клавишу page down или End
                 * выделяем последний элемент
                 */
                else if(/*event.keyCode===34 ||*/ event.keyCode===35){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* снимаем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* выделяем самый нижний файл */
                        lCurrentFile.parentElement.lastElementChild.className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали Enter - открываем папку*/
                else if(event.keyCode===13){
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile.length)return;
                    lCurrentFile=lCurrentFile[0];
                    /* из него достаём спан с именем файла*/
                    lName=lCurrentFile.getElementsByClassName('name');
                    /* если нету (что вряд ли) - выходим*/
                    if(!lName)return false;
                    /* достаём все ссылки*/
                    var lATag=lName[0].getElementsByTagName('a');
                    /* если нету - выходим */
                    if(!lATag)return false;

                    /* вызываем ajaxload привязанный через changelinks
                     * пробулем нажать на ссылку, если не получиться
                     * (opera, ie), вызываем событие onclick,
                     * которое пока не прописано у файлов
                     */

                     if(lCurrentFile.onclick)lCurrentFile.onclick(true);
                     else try{
                         lATag[0].click();
                     }
                     catch(error){
                         console.log(error);
                     }
                }
                /* если нажали <ctr>+r
                 * обновляем страницу,
                 * загружаем содержимое каталога
                 * при этом данные берём всегда с
                 * сервера, а не из кэша
                 * (обновляем кэш)
                 */
                else if(event.keyCode===82 &&
                    event.ctrlKey){
                    console.log('<ctrl>+r pressed');
                    console.log('reloading page...');
                    console.log('press <alt>+q to remove all key-handlers');
                    /* Программно нажимаем на кнопку перезагрузки
                     * содержимого каталога
                     */
                    var lRefreshIcon=document.getElementsByClassName(CloudFunc.REFRESHICON);
                    if(lRefreshIcon)lRefreshIcon=lRefreshIcon[0];
                    if(lRefreshIcon){
                        /* находим файл который сейчас выделен */
                         lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                         if(lCurrentFile.length>0)lCurrentFile=lCurrentFile[0];
                         /* получаем название файла*/
                         var lSelectedName=lCurrentFile.getElementsByTagName('a')[0].textContent;
                         /* если нашли элемент нажимаем него
                          * а если не можем - нажимаем на
                          * ссылку, на которую повешен eventHandler
                          * onclick
                          */
                        if(lRefreshIcon.click)lRefreshIcon.parentElement.click();
                        else lRefreshIcon.parentElement.onclick();

                        /* перебираем файлы левой панели
                         * в поисках подсвеченого файла
                         */
                        var lLeft=document.getElementById('left');
                        if(lLeft){
                            /* перебираем все файлы в панели */
                            var lLi=lLeft.getElementsByTagName('li');
                            lCurrentFile.className='';
                            /* начинаем с 2-ух, по скольку
                             * 0 - это путь
                             * 1 - это заголовок файловой таблицы
                             */
                            for(var i=2;i<lLi.length;i++){
                                lName=lLi[i].getElementsByTagName('a')[0].textContent;
                                if(lSelectedName.length===lName.length &&
                                    !lSelectedName.indexOf(lName)){
                                        lLi[i].className=CloudCommander.CURRENT_FILE;
                                        break;
                                }
                            }
                        }

                        event.preventDefault();//запрет на дальнейшее действие
                    }
                }
                /* если нажали <ctrl>+d чистим кэш */
                else if(event.keyCode===68 &&
                    event.ctrlKey){
                        console.log('<ctrl>+d pressed');
                        console.log('clearing cache...');
                        console.log('press <alt>+q to remove all key-handlers');

                        var lClearCache=document.getElementById('clear-cache');
                        if(lClearCache && lClearCache.onclick)lClearCache.onclick();

                        event.preventDefault();//запрет на дальнейшее действие
                }
                /* если нажали <alt>+q
                 * убираем все обработчики
                 * нажатий клавиш
                 */
                else if(event.keyCode===81 &&
                    event.altKey){
                        //document.removeEventListener('keydown', key_event,false);
                        console.log('<alt>+q pressed');
                        console.log('<ctrl>+r reload key-handerl - removed');
                        console.log('<ctrl>+s clear cache key-handler - removed');
                        console.log('press <alt>+s to to set them');

                        /* обработчик нажатий клавиш снят*/
                        CloudCommander.keyBinded=false;
                }
            }
            /* если нажали <alt>+s
             * устанавливаем все обработчики
             * нажатий клавиш
             */
            else if(event.keyCode===83 &&
                event.altKey){
                    /*
                        document.addEventListener('keydown', key_event,false);
                    */
                    /* обрабатываем нажатия на клавиши*/
                    CloudCommander.keyBinded=true;

                    console.log('<alt>+s pressed');
                    console.log('<ctrl>+r reload key-handerl - set');
                    console.log('<ctrl>+s clear cache key-handler - set');
                    console.log('press <alt>+q to remove them');
            }

         return false;
    };
    /* добавляем обработчик клавишь */
    if(document.addEventListener)
        document.addEventListener('keydown', key_event,false);
    else document.onkeypress=key_event;
    /* клавиши назначены*/
    CloudCommander.keyBinded=true;
});<|endoftext|>


<commit_before>/** vim: et:ts=4:sw=4:sts=4
 * @license RequireJS 2.3.6 Copyright jQuery Foundation and other contributors.
 * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE
 */
var requirejs,require,define;!function(global,setTimeout){var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version="2.3.6",commentRegExp=/\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/gm,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,isBrowser=!("undefined"==typeof window||"undefined"==typeof navigator||!window.document),isWebWorker=!isBrowser&&"undefined"!=typeof importScripts,readyRegExp=isBrowser&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,defContextName="_",isOpera="undefined"!=typeof opera&&"[object Opera]"===opera.toString(),contexts={},cfg={},globalDefQueue=[],useInteractive=!1;function commentReplace(e,t){return t||""}function isFunction(e){return"[object Function]"===ostring.call(e)}function isArray(e){return"[object Array]"===ostring.call(e)}function each(e,t){var i;if(e)for(i=0;i<e.length&&(!e[i]||!t(e[i],i,e));i+=1);}function eachReverse(e,t){var i;if(e)for(i=e.length-1;-1<i&&(!e[i]||!t(e[i],i,e));i-=1);}function hasProp(e,t){return hasOwn.call(e,t)}function getOwn(e,t){return hasProp(e,t)&&e[t]}function eachProp(e,t){var i;for(i in e)if(hasProp(e,i)&&t(e[i],i))break}function mixin(i,e,r,n){return e&&eachProp(e,function(e,t){!r&&hasProp(i,t)||(!n||"object"!=typeof e||!e||isArray(e)||isFunction(e)||e instanceof RegExp?i[t]=e:(i[t]||(i[t]={}),mixin(i[t],e,r,n)))}),i}function bind(e,t){return function(){return t.apply(e,arguments)}}function scripts(){return document.getElementsByTagName("script")}function defaultOnError(e){throw e}function getGlobal(e){if(!e)return e;var t=global;return each(e.split("."),function(e){t=t[e]}),t}function makeError(e,t,i,r){var n=new Error(t+"\nhttps://requirejs.org/docs/errors.html#"+e);return n.requireType=e,n.requireModules=r,i&&(n.originalError=i),n}if(void 0===define){if(void 0!==requirejs){if(isFunction(requirejs))return;cfg=requirejs,requirejs=void 0}void 0===require||isFunction(require)||(cfg=require,require=void 0),req=requirejs=function(e,t,i,r){var n,o,a=defContextName;return isArray(e)||"string"==typeof e||(o=e,isArray(t)?(e=t,t=i,i=r):e=[]),o&&o.context&&(a=o.context),(n=getOwn(contexts,a))||(n=contexts[a]=req.s.newContext(a)),o&&n.configure(o),n.require(e,t,i)},req.config=function(e){return req(e)},req.nextTick=void 0!==setTimeout?function(e){setTimeout(e,4)}:function(e){e()},require||(require=req),req.version=version,req.jsExtRegExp=/^\/|:|\?|\.js$/,req.isBrowser=isBrowser,s=req.s={contexts:contexts,newContext:newContext},req({}),each(["toUrl","undef","defined","specified"],function(t){req[t]=function(){var e=contexts[defContextName];return e.require[t].apply(e,arguments)}}),isBrowser&&(head=s.head=document.getElementsByTagName("head")[0],baseElement=document.getElementsByTagName("base")[0],baseElement&&(head=s.head=baseElement.parentNode)),req.onError=defaultOnError,req.createNode=function(e,t,i){var r=e.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");return r.type=e.scriptType||"text/javascript",r.charset="utf-8",r.async=!0,r},req.load=function(t,i,r){var e,n=t&&t.config||{};if(isBrowser)return(e=req.createNode(n,i,r)).setAttribute("data-requirecontext",t.contextName),e.setAttribute("data-requiremodule",i),!e.attachEvent||e.attachEvent.toString&&e.attachEvent.toString().indexOf("[native code")<0||isOpera?(e.addEventListener("load",t.onScriptLoad,!1),e.addEventListener("error",t.onScriptError,!1)):(useInteractive=!0,e.attachEvent("onreadystatechange",t.onScriptLoad)),e.src=r,n.onNodeCreated&&n.onNodeCreated(e,n,i,r),currentlyAddingScript=e,baseElement?head.insertBefore(e,baseElement):head.appendChild(e),currentlyAddingScript=null,e;if(isWebWorker)try{setTimeout(function(){},0),importScripts(r),t.completeLoad(i)}catch(e){t.onError(makeError("importscripts","importScripts failed for "+i+" at "+r,e,[i]))}},isBrowser&&!cfg.skipDataMain&&eachReverse(scripts(),function(e){if(head||(head=e.parentNode),dataMain=e.getAttribute("data-main"))return mainScript=dataMain,cfg.baseUrl||-1!==mainScript.indexOf("!")||(mainScript=(src=mainScript.split("/")).pop(),subPath=src.length?src.join("/")+"/":"./",cfg.baseUrl=subPath),mainScript=mainScript.replace(jsSuffixRegExp,""),req.jsExtRegExp.test(mainScript)&&(mainScript=dataMain),cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript],!0}),define=function(e,i,t){var r,n;"string"!=typeof e&&(t=i,i=e,e=null),isArray(i)||(t=i,i=null),!i&&isFunction(t)&&(i=[],t.length&&(t.toString().replace(commentRegExp,commentReplace).replace(cjsRequireRegExp,function(e,t){i.push(t)}),i=(1===t.length?["require"]:["require","exports","module"]).concat(i))),useInteractive&&(r=currentlyAddingScript||getInteractiveScript())&&(e||(e=r.getAttribute("data-requiremodule")),n=contexts[r.getAttribute("data-requirecontext")]),n?(n.defQueue.push([e,i,t]),n.defQueueMap[e]=!0):globalDefQueue.push([e,i,t])},define.amd={jQuery:!0},req.exec=function(text){return eval(text)},req(cfg)}function newContext(u){var i,e,l,c,d,g={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},p={},f={},r={},h=[],m={},n={},v={},x=1,b=1;function q(e,t,i){var r,n,o,a,s,u,c,d,p,f,l=t&&t.split("/"),h=g.map,m=h&&h["*"];if(e&&(u=(e=e.split("/")).length-1,g.nodeIdCompat&&jsSuffixRegExp.test(e[u])&&(e[u]=e[u].replace(jsSuffixRegExp,"")),"."===e[0].charAt(0)&&l&&(e=l.slice(0,l.length-1).concat(e)),function(e){var t,i;for(t=0;t<e.length;t++)if("."===(i=e[t]))e.splice(t,1),t-=1;else if(".."===i){if(0===t||1===t&&".."===e[2]||".."===e[t-1])continue;0<t&&(e.splice(t-1,2),t-=2)}}(e),e=e.join("/")),i&&h&&(l||m)){e:for(o=(n=e.split("/")).length;0<o;o-=1){if(s=n.slice(0,o).join("/"),l)for(a=l.length;0<a;a-=1)if((r=getOwn(h,l.slice(0,a).join("/")))&&(r=getOwn(r,s))){c=r,d=o;break e}!p&&m&&getOwn(m,s)&&(p=getOwn(m,s),f=o)}!c&&p&&(c=p,d=f),c&&(n.splice(0,d,c),e=n.join("/"))}return getOwn(g.pkgs,e)||e}function E(t){isBrowser&&each(scripts(),function(e){if(e.getAttribute("data-requiremodule")===t&&e.getAttribute("data-requirecontext")===l.contextName)return e.parentNode.removeChild(e),!0})}function w(e){var t=getOwn(g.paths,e);if(t&&isArray(t)&&1<t.length)return t.shift(),l.require.undef(e),l.makeRequire(null,{skipMap:!0})([e]),!0}function y(e){var t,i=e?e.indexOf("!"):-1;return-1<i&&(t=e.substring(0,i),e=e.substring(i+1,e.length)),[t,e]}function S(e,t,i,r){var n,o,a,s,u=null,c=t?t.name:null,d=e,p=!0,f="";return e||(p=!1,e="_@r"+(x+=1)),u=(s=y(e))[0],e=s[1],u&&(u=q(u,c,r),o=getOwn(m,u)),e&&(u?f=i?e:o&&o.normalize?o.normalize(e,function(e){return q(e,c,r)}):-1===e.indexOf("!")?q(e,c,r):e:(u=(s=y(f=q(e,c,r)))[0],f=s[1],i=!0,n=l.nameToUrl(f))),{prefix:u,name:f,parentMap:t,unnormalized:!!(a=!u||o||i?"":"_unnormalized"+(b+=1)),url:n,originalName:d,isDefine:p,id:(u?u+"!"+f:f)+a}}function k(e){var t=e.id,i=getOwn(p,t);return i||(i=p[t]=new l.Module(e)),i}function M(e,t,i){var r=e.id,n=getOwn(p,r);!hasProp(m,r)||n&&!n.defineEmitComplete?(n=k(e)).error&&"error"===t?i(n.error):n.on(t,i):"defined"===t&&i(m[r])}function O(i,e){var t=i.requireModules,r=!1;e?e(i):(each(t,function(e){var t=getOwn(p,e);t&&(t.error=i,t.events.error&&(r=!0,t.emit("error",i)))}),r||req.onError(i))}function j(){globalDefQueue.length&&(each(globalDefQueue,function(e){var t=e[0];"string"==typeof t&&(l.defQueueMap[t]=!0),h.push(e)}),globalDefQueue=[])}function P(e){delete p[e],delete f[e]}function R(){var e,r,t=1e3*g.waitSeconds,n=t&&l.startTime+t<(new Date).getTime(),o=[],a=[],s=!1,u=!0;if(!i){if(i=!0,eachProp(f,function(e){var t=e.map,i=t.id;if(e.enabled&&(t.isDefine||a.push(e),!e.error))if(!e.inited&&n)w(i)?s=r=!0:(o.push(i),E(i));else if(!e.inited&&e.fetched&&t.isDefine&&(s=!0,!t.prefix))return u=!1}),n&&o.length)return(e=makeError("timeout","Load timeout for modules: "+o,null,o)).contextName=l.contextName,O(e);u&&each(a,function(e){!function n(o,a,s){var e=o.map.id;o.error?o.emit("error",o.error):(a[e]=!0,each(o.depMaps,function(e,t){var i=e.id,r=getOwn(p,i);!r||o.depMatched[t]||s[i]||(getOwn(a,i)?(o.defineDep(t,m[i]),o.check()):n(r,a,s))}),s[e]=!0)}(e,{},{})}),n&&!r||!s||!isBrowser&&!isWebWorker||d||(d=setTimeout(function(){d=0,R()},50)),i=!1}}function a(e){hasProp(m,e[0])||k(S(e[0],null,!0)).init(e[1],e[2])}function o(e,t,i,r){e.detachEvent&&!isOpera?r&&e.detachEvent(r,t):e.removeEventListener(i,t,!1)}function s(e){var t=e.currentTarget||e.srcElement;return o(t,l.onScriptLoad,"load","onreadystatechange"),o(t,l.onScriptError,"error"),{node:t,id:t&&t.getAttribute("data-requiremodule")}}function T(){var e;for(j();h.length;){if(null===(e=h.shift())[0])return O(makeError("mismatch","Mismatched anonymous define() module: "+e[e.length-1]));a(e)}l.defQueueMap={}}return c={require:function(e){return e.require?e.require:e.require=l.makeRequire(e.map)},exports:function(e){if(e.usingExports=!0,e.map.isDefine)return e.exports?m[e.map.id]=e.exports:e.exports=m[e.map.id]={}},module:function(e){return e.module?e.module:e.module={id:e.map.id,uri:e.map.url,config:function(){return getOwn(g.config,e.map.id)||{}},exports:e.exports||(e.exports={})}}},(e=function(e){this.events=getOwn(r,e.id)||{},this.map=e,this.shim=getOwn(g.shim,e.id),this.depExports=[],this.depMaps=[],this.depMatched=[],this.pluginMaps={},this.depCount=0}).prototype={init:function(e,t,i,r){r=r||{},this.inited||(this.factory=t,i?this.on("error",i):this.events.error&&(i=bind(this,function(e){this.emit("error",e)})),this.depMaps=e&&e.slice(0),this.errback=i,this.inited=!0,this.ignore=r.ignore,r.enabled||this.enabled?this.enable():this.check())},defineDep:function(e,t){this.depMatched[e]||(this.depMatched[e]=!0,this.depCount-=1,this.depExports[e]=t)},fetch:function(){if(!this.fetched){this.fetched=!0,l.startTime=(new Date).getTime();var e=this.map;if(!this.shim)return e.prefix?this.callPlugin():this.load();l.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],bind(this,function(){return e.prefix?this.callPlugin():this.load()}))}},load:function(){var e=this.map.url;n[e]||(n[e]=!0,l.load(this.map.id,e))},check:function(){if(this.enabled&&!this.enabling){var t,e,i=this.map.id,r=this.depExports,n=this.exports,o=this.factory;if(this.inited){if(this.error)this.emit("error",this.error);else if(!this.defining){if(this.defining=!0,this.depCount<1&&!this.defined){if(isFunction(o)){if(this.events.error&&this.map.isDefine||req.onError!==defaultOnError)try{n=l.execCb(i,o,r,n)}catch(e){t=e}else n=l.execCb(i,o,r,n);if(this.map.isDefine&&void 0===n&&((e=this.module)?n=e.exports:this.usingExports&&(n=this.exports)),t)return t.requireMap=this.map,t.requireModules=this.map.isDefine?[this.map.id]:null,t.requireType=this.map.isDefine?"define":"require",O(this.error=t)}else n=o;if(this.exports=n,this.map.isDefine&&!this.ignore&&(m[i]=n,req.onResourceLoad)){var a=[];each(this.depMaps,function(e){a.push(e.normalizedMap||e)}),req.onResourceLoad(l,this.map,a)}P(i),this.defined=!0}this.defining=!1,this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else hasProp(l.defQueueMap,i)||this.fetch()}},callPlugin:function(){var u=this.map,c=u.id,e=S(u.prefix);this.depMaps.push(e),M(e,"defined",bind(this,function(e){var o,t,i,r=getOwn(v,this.map.id),n=this.map.name,a=this.map.parentMap?this.map.parentMap.name:null,s=l.makeRequire(u.parentMap,{enableBuildCallback:!0});return this.map.unnormalized?(e.normalize&&(n=e.normalize(n,function(e){return q(e,a,!0)})||""),M(t=S(u.prefix+"!"+n,this.map.parentMap,!0),"defined",bind(this,function(e){this.map.normalizedMap=t,this.init([],function(){return e},null,{enabled:!0,ignore:!0})})),void((i=getOwn(p,t.id))&&(this.depMaps.push(t),this.events.error&&i.on("error",bind(this,function(e){this.emit("error",e)})),i.enable()))):r?(this.map.url=l.nameToUrl(r),void this.load()):((o=bind(this,function(e){this.init([],function(){return e},null,{enabled:!0})})).error=bind(this,function(e){this.inited=!0,(this.error=e).requireModules=[c],eachProp(p,function(e){0===e.map.id.indexOf(c+"_unnormalized")&&P(e.map.id)}),O(e)}),o.fromText=bind(this,function(e,t){var i=u.name,r=S(i),n=useInteractive;t&&(e=t),n&&(useInteractive=!1),k(r),hasProp(g.config,c)&&(g.config[i]=g.config[c]);try{req.exec(e)}catch(e){return O(makeError("fromtexteval","fromText eval for "+c+" failed: "+e,e,[c]))}n&&(useInteractive=!0),this.depMaps.push(r),l.completeLoad(i),s([i],o)}),void e.load(u.name,s,o,g))})),l.enable(e,this),this.pluginMaps[e.id]=e},enable:function(){(f[this.map.id]=this).enabled=!0,this.enabling=!0,each(this.depMaps,bind(this,function(e,t){var i,r,n;if("string"==typeof e){if(e=S(e,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap),this.depMaps[t]=e,n=getOwn(c,e.id))return void(this.depExports[t]=n(this));this.depCount+=1,M(e,"defined",bind(this,function(e){this.undefed||(this.defineDep(t,e),this.check())})),this.errback?M(e,"error",bind(this,this.errback)):this.events.error&&M(e,"error",bind(this,function(e){this.emit("error",e)}))}i=e.id,r=p[i],hasProp(c,i)||!r||r.enabled||l.enable(e,this)})),eachProp(this.pluginMaps,bind(this,function(e){var t=getOwn(p,e.id);t&&!t.enabled&&l.enable(e,this)})),this.enabling=!1,this.check()},on:function(e,t){var i=this.events[e];i||(i=this.events[e]=[]),i.push(t)},emit:function(e,t){each(this.events[e],function(e){e(t)}),"error"===e&&delete this.events[e]}},(l={config:g,contextName:u,registry:p,defined:m,urlFetched:n,defQueue:h,defQueueMap:{},Module:e,makeModuleMap:S,nextTick:req.nextTick,onError:O,configure:function(e){if(e.baseUrl&&"/"!==e.baseUrl.charAt(e.baseUrl.length-1)&&(e.baseUrl+="/"),"string"==typeof e.urlArgs){var i=e.urlArgs;e.urlArgs=function(e,t){return(-1===t.indexOf("?")?"?":"&")+i}}var r=g.shim,n={paths:!0,bundles:!0,config:!0,map:!0};eachProp(e,function(e,t){n[t]?(g[t]||(g[t]={}),mixin(g[t],e,!0,!0)):g[t]=e}),e.bundles&&eachProp(e.bundles,function(e,t){each(e,function(e){e!==t&&(v[e]=t)})}),e.shim&&(eachProp(e.shim,function(e,t){isArray(e)&&(e={deps:e}),!e.exports&&!e.init||e.exportsFn||(e.exportsFn=l.makeShimExports(e)),r[t]=e}),g.shim=r),e.packages&&each(e.packages,function(e){var t;t=(e="string"==typeof e?{name:e}:e).name,e.location&&(g.paths[t]=e.location),g.pkgs[t]=e.name+"/"+(e.main||"main").replace(currDirRegExp,"").replace(jsSuffixRegExp,"")}),eachProp(p,function(e,t){e.inited||e.map.unnormalized||(e.map=S(t,null,!0))}),(e.deps||e.callback)&&l.require(e.deps||[],e.callback)},makeShimExports:function(t){return function(){var e;return t.init&&(e=t.init.apply(global,arguments)),e||t.exports&&getGlobal(t.exports)}},makeRequire:function(o,a){function s(e,t,i){var r,n;return a.enableBuildCallback&&t&&isFunction(t)&&(t.__requireJsBuild=!0),"string"==typeof e?isFunction(t)?O(makeError("requireargs","Invalid require call"),i):o&&hasProp(c,e)?c[e](p[o.id]):req.get?req.get(l,e,o,s):(r=S(e,o,!1,!0).id,hasProp(m,r)?m[r]:O(makeError("notloaded",'Module name "'+r+'" has not been loaded yet for context: '+u+(o?"":". Use require([])")))):(T(),l.nextTick(function(){T(),(n=k(S(null,o))).skipMap=a.skipMap,n.init(e,t,i,{enabled:!0}),R()}),s)}return a=a||{},mixin(s,{isBrowser:isBrowser,toUrl:function(e){var t,i=e.lastIndexOf("."),r=e.split("/")[0];return-1!==i&&(!("."===r||".."===r)||1<i)&&(t=e.substring(i,e.length),e=e.substring(0,i)),l.nameToUrl(q(e,o&&o.id,!0),t,!0)},defined:function(e){return hasProp(m,S(e,o,!1,!0).id)},specified:function(e){return e=S(e,o,!1,!0).id,hasProp(m,e)||hasProp(p,e)}}),o||(s.undef=function(i){j();var e=S(i,o,!0),t=getOwn(p,i);t.undefed=!0,E(i),delete m[i],delete n[e.url],delete r[i],eachReverse(h,function(e,t){e[0]===i&&h.splice(t,1)}),delete l.defQueueMap[i],t&&(t.events.defined&&(r[i]=t.events),P(i))}),s},enable:function(e){getOwn(p,e.id)&&k(e).enable()},completeLoad:function(e){var t,i,r,n=getOwn(g.shim,e)||{},o=n.exports;for(j();h.length;){if(null===(i=h.shift())[0]){if(i[0]=e,t)break;t=!0}else i[0]===e&&(t=!0);a(i)}if(l.defQueueMap={},r=getOwn(p,e),!t&&!hasProp(m,e)&&r&&!r.inited){if(!(!g.enforceDefine||o&&getGlobal(o)))return w(e)?void 0:O(makeError("nodefine","No define call for "+e,null,[e]));a([e,n.deps||[],n.exportsFn])}R()},nameToUrl:function(e,t,i){var r,n,o,a,s,u,c=getOwn(g.pkgs,e);if(c&&(e=c),u=getOwn(v,e))return l.nameToUrl(u,t,i);if(req.jsExtRegExp.test(e))a=e+(t||"");else{for(r=g.paths,o=(n=e.split("/")).length;0<o;o-=1)if(s=getOwn(r,n.slice(0,o).join("/"))){isArray(s)&&(s=s[0]),n.splice(0,o,s);break}a=n.join("/"),a=("/"===(a+=t||(/^data\:|^blob\:|\?/.test(a)||i?"":".js")).charAt(0)||a.match(/^[\w\+\.\-]+:/)?"":g.baseUrl)+a}return g.urlArgs&&!/^blob\:/.test(a)?a+g.urlArgs(e,a):a},load:function(e,t){req.load(l,e,t)},execCb:function(e,t,i,r){return t.apply(r,i)},onScriptLoad:function(e){if("load"===e.type||readyRegExp.test((e.currentTarget||e.srcElement).readyState)){interactiveScript=null;var t=s(e);l.completeLoad(t.id)}},onScriptError:function(e){var i=s(e);if(!w(i.id)){var r=[];return eachProp(p,function(e,t){0!==t.indexOf("_@r")&&each(e.depMaps,function(e){if(e.id===i.id)return r.push(t),!0})}),O(makeError("scripterror",'Script error for "'+i.id+(r.length?'", needed by: '+r.join(", "):'"'),e,[i.id]))}}}).require=l.makeRequire(),l}function getInteractiveScript(){return interactiveScript&&"interactive"===interactiveScript.readyState||eachReverse(scripts(),function(e){if("interactive"===e.readyState)return interactiveScript=e}),interactiveScript}}(this,"undefined"==typeof setTimeout?void 0:setTimeout);<commit_msg>remove useless require.js<commit_after><|endoftext|>


<commit_before>/*! built for dogtalk 2013-09-26 */
angular.module("ngSockethubClient",[]).value("SockethubSettings",{conn:{host:"localhost",port:10550,path:"/sockethub",tls:!1,secret:"1234567890"},connected:!1,env:{logo:"/res/img/sockethub-logo.svg"},save:function(a,b){return this.verify(a,b)?(this[a]=b,this[a].port=parseInt(b.port),console.log("SH SAVE "+a+": ",this[a]),!0):(console.log("SH SAVE FAILED "+a+": ",this[a]),!1)},exists:function(a){this.verify(a,settings.conn)},verify:function(a,b){return b||(b=this[a]),b.host&&""!==b.host&&b.port&&""!==b.port&&b.path&&""!==b.path&&"boolean"==typeof b.tls&&b.secret&&""!==b.secret?!0:!1}}).factory("SH",["$rootScope","$q","$timeout","SockethubSettings",function(a,b,c,d){function e(){return l?l.connected:!1}function f(){return l?l.registered:!1}function g(d){var e=b.defer(),f=500;return function g(){d.testFunc()?(console.log("SH: calling: "+d.callFunc),l[d.callFunc].apply(l,d.callParams).then(function(b){a.$apply(e.resolve(b))},function(b){a.$apply(e.reject(b))})):(console.log("SH: delaying call "+f+"s"),3e4>f&&(f+=2*f),c(g,f))}(),e.promise}function h(c){console.log("ngSockethubClient.connect() ",c);var e=b.defer(),f="ws://";d.connected=!1,d.conn.tls&&(f="wss://");var g={};return c&&c.register&&(g={register:{secret:d.conn.secret}}),l=SockethubClient.connect(f+d.conn.host+":"+d.conn.port+d.conn.path,g),l.on("connected",function(){console.log("Sockethub connected"),d.connected=!0,m.connected.sockethub?a.$apply(m.connected.sockethub()):a.$apply(function(){e.resolve()})}),l.on("registered",function(){console.log("Sockethub connected & registered"),d.connected=!0,m.registered.sockethub?a.$apply(m.registered.sockethub()):a.$apply(function(){e.resolve()})}),l.on("registration-failed",function(b){console.log("Sockethub register failed ",b),a.$apply(function(){e.reject(b)})}),l.on("failed",function(b){console.log("Sockethub connection failed ",b),a.$apply(function(){e.reject("Failed connecting to sockethub at "+f+d.conn.host+":"+d.conn.port+d.conn.path)})}),l.on("disconnected",function(a){console.log("SH received disconnect(close) "+a),d.connected=!1}),l.on("message",function(b){b.platform&&m.message[b.platform]?(console.log("SH passing message to platform: "+b.platform),a.$apply(m.message[b.platform](b))):console.log("SH received message with nothing to call: ",b)}),l.on("unexpected-response",function(a){console.log("SH unexpected response: ",a)}),e.promise}function i(){var a=b.defer();return console.log("SH.register() called"),g({testFunc:e,callFunc:"register",callParams:[{secret:d.conn.secret}]}).then(a.resolve,a.reject),a.promise}function j(a,c,d,e){var h=b.defer(),i={};return i[c]={},i[c][d]=e,g({testFunc:f,callFunc:"set",callParams:[a,i]}).then(h.resolve,h.reject),h.promise}function k(a,c){var d=b.defer();return g({testFunc:f,callFunc:"sendObject",callParams:[a,c]}).then(d.resolve,d.reject),d.promise}var l,m={error:{},message:{},response:{},close:{},registered:{},connected:{}},n=function(a,b,c){m[b][a]=c};return{connect:h,register:i,isConnected:e,isRegistered:f,set:j,submit:k,on:n}}]).run(["$rootScope",function(a){a.$on("showModalSockethubSettings",function(a,b){backdrop_setting=!0,"object"==typeof b&&"undefined"!=typeof b.locked&&b.locked&&(backdrop_setting="static"),$("#modalSockethubSettings").modal({show:!0,keyboard:!0,backdrop:backdrop_setting})}),a.$on("closeModalSockethubSettings",function(){$("#modalSockethubSettings").modal("hide")})}]).directive("sockethubSettings",["SH","SockethubSettings","$rootScope",function(a,b,c){return{restrict:"A",template:'

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

    <form name="settingsSockethub" role="form" novalidate>      <fieldset>
          Hostname
            <input type="text" class="required form-control" name="host" placeholder="Enter hostname..." ng-model="settings.conn.host" required>

          Port
            <input type="text" class="required form-control" name="port" placeholder="Enter port..." ng-model="settings.conn.port" required>

          Path
            <input type="text" class="required form-control" name="path" placeholder="Enter path (if any)..." ng-model="settings.conn.path">

                      <input type="checkbox" name="tls" ng-model="settings.conn.tls"> TLS

          Secret
            <input type="text" class="required form-control" name="secret" placeholder="Enter secret..." ng-model="settings.conn.secret" required>

      </fieldset>

            <button class="btn btn-primary" ng-click="save(settings.conn)"                     ng-disabled="!settings.verify(\'conn\', settings.conn) || saving">Submit</button>

    </form>

',link:function(d){d.saving=!1,d.settings=b,d.save=function(e){d.saving=!0,b.save("conn",e),c.$broadcast("message",{message:"attempting to connect to sockethub",type:"info",timeout:!1}),a.connect({register:!0}).then(function(){d.saving=!1,console.log("connected to sockethub"),c.$broadcast("message",{message:"connected to sockethub",type:"success",timeout:!0}),$("#modalSockethubSettings").modal("hide")},function(a){d.saving=!1,console.log("error connection to sockethub: ",a),c.$broadcast("message",{message:a,type:"error",timeout:!1})})}}}}]);<commit_msg>test release<commit_after>/*! built for dogtalk 2013-09-26 */
angular.module("dogtalk",["ngSockethubClient","ngSockethubRemoteStorage","ngRemoteStorage","ngXMPPClient","ngMessages"]).config(["$routeProvider",function(a){a.when("/settings",{templateUrl:"settings.html",controller:"settingsCtrl"}).when("/",{templateUrl:"talk.html",controller:"talkCtrl"}).when("/talk/:address",{templateUrl:"talk.html",controller:"talkCtrl"}).otherwise({redirectTo:"/"})}]).run(["RemoteStorageConfig",function(a){a.modules=[["sockethub","rw",{cache:!1}],["messages","rw",{cache:!1}],["contacts","rw",{cache:!1}]]}]).run(["$rootScope","RS","$timeout",function(a,b,c){b.isConnected()||c(function(){b.isConnected()||a.$broadcast("message",{message:"remotestorage-connect",timeout:!1})},1e3)}]).run(["SockethubBootstrap",function(a){a.run({host:"silverbucket.net",port:"443",path:"/sockethub",tls:!0,secret:"1234567890"})}]).run(["SH","$rootScope","RS","XMPP","XMPPSettings",function(a,b,c,d){c.call("messages","getAccount",["xmpp","default"]).then(function(a){console.log("GOT XMPP CONFIG: ",a),void 0===a?(b.$broadcast("showModalSettingsXmpp",{message:"No existing XMPP configuration information found",locked:!1}),b.$broadcast("message",{message:"xmpp-connection",type:"error",timeout:!1})):d.connect(a).then(function(){console.log("xmpp connected")},function(a){b.$broadcast("showModalSettingsXmpp",{message:"Error connecting via XMPP "+a,locked:!1}),console.log("xmpp ERROR",a),b.$broadcast("message",{message:a,type:"error",timeout:!0})})},function(a){console.log("RS.call failed: ",a)})}]).controller("appCtrl",["$scope","$rootScope","$route","$location",function(a,b,c,d){b.$on("$routeChangeStart",function(){console.log("routeChangeStart: ",a,b,c,d)}),b.$on("$routeChangeSuccess",function(){console.log("routeChangeSuccess")}),b.$on("$routeChangeError",function(a,b,c,d){console.log("routeChangeError: ",d)})}]).controller("navCtrl",["$scope","$route","$routeParams","$location",function(a,b,c,d){a.navClass=function(a){var b=d.path().substring(1)||"home";return a===b?"active":""}}]).controller("settingsCtrl",["$scope","$route","$routeParams","$rootScope","SockethubSettings","XMPP","RS",function(a,b,c,d){a.sockethubSettings=function(){d.$broadcast("showModalSockethubSettings",{locked:!1})},a.xmppSettings=function(){d.$broadcast("showModalSettingsXmpp",{locked:!1})}}]).controller("talkCtrl",["$scope","$route","$routeParams","$location","XMPP","$rootScope","XMPPSettings",function(a,b,c,d,e,f,g){console.log("--- talkCtrl run"),a.model={presence:e.presence.data,contacts:e.contacts.data,settings:g,requests:e.requests.data},e.initListener(),a.model.currentAddress=c.address?c.address:"none",a.model.currentName=a.model.contacts[c.address]?a.model.contacts[c.address].name:"",a.model.currentConversation=a.model.contacts[c.address]?a.model.contacts[c.address].conversation:[],a.$watch("model.contacts",function(a){console.log("SCOPE WATCH CONTACTS : ",a)}),a.conversationSwitch=function(b){return console.log("---- talkCtrl.conversationSwitch("+b+")"),b!==c.address?"":(a.model.contacts[b]?(a.model.currentAddress=b,a.model.currentName=a.model.contacts[b].name,a.model.currentConversation=a.model.contacts[b].conversation,console.log("currentConversation: ",a.model.currentConversation)):console.log("talkCtrl.conversationSwitch() - not in history"),"active")},a.sendMsg=function(b){a.model.saving=!0,e.sendMsg(g.conn.actor,a.model.currentAddress,b).then(function(){a.model.sendText="",a.model.saving=!1},function(b){console.log("sendMsg error: "+b),a.model.saving=!1})},a.isFromMe=function(a){return g.conn.username===a?!0:!1},a.acceptBuddyRequest=function(b){return a.model.saving=!0,a.model.requests[b]?(console.log("settings;",g),e.requests.accept(g.conn.actor,b).then(function(){return a.model.saving=!1,delete a.model.requests[b],!0},function(){return a.model.saving=!1,!1}),void 0):(a.model.saving=!1,!1)}}]).controller("logCtrl",["$scope","$route","$routeParams","$location",function(a){a.model={message:"this is the log page fool!"}}]),angular.module("ngSockethubClient",[]).value("SockethubSettings",{conn:{host:"localhost",port:10550,path:"/sockethub",tls:!1,secret:"1234567890"},connected:!1,env:{logo:"/res/img/sockethub-logo.svg"},save:function(a,b){return this.verify(a,b)?(this[a]=b,this[a].port=parseInt(b.port),console.log("SH SAVE "+a+": ",this[a]),!0):(console.log("SH SAVE FAILED "+a+": ",this[a]),!1)},exists:function(a){this.verify(a,settings.conn)},verify:function(a,b){return b||(b=this[a]),b.host&&""!==b.host&&b.port&&""!==b.port&&b.path&&""!==b.path&&"boolean"==typeof b.tls&&b.secret&&""!==b.secret?!0:!1}}).factory("SH",["$rootScope","$q","$timeout","SockethubSettings",function(a,b,c,d){function e(){return l?l.connected:!1}function f(){return l?l.registered:!1}function g(d){var e=b.defer(),f=500;return function g(){d.testFunc()?(console.log("SH: calling: "+d.callFunc),l[d.callFunc].apply(l,d.callParams).then(function(b){a.$apply(e.resolve(b))},function(b){a.$apply(e.reject(b))})):(console.log("SH: delaying call "+f+"s"),3e4>f&&(f+=2*f),c(g,f))}(),e.promise}function h(c){console.log("ngSockethubClient.connect() ",c);var e=b.defer(),f="ws://";d.connected=!1,d.conn.tls&&(f="wss://");var g={};return c&&c.register&&(g={register:{secret:d.conn.secret}}),l=SockethubClient.connect(f+d.conn.host+":"+d.conn.port+d.conn.path,g),l.on("connected",function(){console.log("Sockethub connected"),d.connected=!0,m.connected.sockethub?a.$apply(m.connected.sockethub()):a.$apply(function(){e.resolve()})}),l.on("registered",function(){console.log("Sockethub connected & registered"),d.connected=!0,m.registered.sockethub?a.$apply(m.registered.sockethub()):a.$apply(function(){e.resolve()})}),l.on("registration-failed",function(b){console.log("Sockethub register failed ",b),a.$apply(function(){e.reject(b)})}),l.on("failed",function(b){console.log("Sockethub connection failed ",b),a.$apply(function(){e.reject("Failed connecting to sockethub at "+f+d.conn.host+":"+d.conn.port+d.conn.path)})}),l.on("disconnected",function(a){console.log("SH received disconnect(close) "+a),d.connected=!1}),l.on("message",function(b){b.platform&&m.message[b.platform]?(console.log("SH passing message to platform: "+b.platform),a.$apply(m.message[b.platform](b))):console.log("SH received message with nothing to call: ",b)}),l.on("unexpected-response",function(a){console.log("SH unexpected response: ",a)}),e.promise}function i(){var a=b.defer();return console.log("SH.register() called"),g({testFunc:e,callFunc:"register",callParams:[{secret:d.conn.secret}]}).then(a.resolve,a.reject),a.promise}function j(a,c,d,e){var h=b.defer(),i={};return i[c]={},i[c][d]=e,g({testFunc:f,callFunc:"set",callParams:[a,i]}).then(h.resolve,h.reject),h.promise}function k(a,c){var d=b.defer();return g({testFunc:f,callFunc:"sendObject",callParams:[a,c]}).then(d.resolve,d.reject),d.promise}var l,m={error:{},message:{},response:{},close:{},registered:{},connected:{}},n=function(a,b,c){m[b][a]=c};return{connect:h,register:i,isConnected:e,isRegistered:f,set:j,submit:k,on:n}}]).run(["$rootScope",function(a){a.$on("showModalSockethubSettings",function(a,b){backdrop_setting=!0,"object"==typeof b&&"undefined"!=typeof b.locked&&b.locked&&(backdrop_setting="static"),$("#modalSockethubSettings").modal({show:!0,keyboard:!0,backdrop:backdrop_setting})}),a.$on("closeModalSockethubSettings",function(){$("#modalSockethubSettings").modal("hide")})}]).directive("sockethubSettings",["SH","SockethubSettings","$rootScope",function(a,b,c){return{restrict:"A",template:'

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

    <form name="settingsSockethub" role="form" novalidate>      <fieldset>
          Hostname
            <input type="text" class="required form-control" name="host" placeholder="Enter hostname..." ng-model="settings.conn.host" required>

          Port
            <input type="text" class="required form-control" name="port" placeholder="Enter port..." ng-model="settings.conn.port" required>

          Path
            <input type="text" class="required form-control" name="path" placeholder="Enter path (if any)..." ng-model="settings.conn.path">

                      <input type="checkbox" name="tls" ng-model="settings.conn.tls"> TLS

          Secret
            <input type="text" class="required form-control" name="secret" placeholder="Enter secret..." ng-model="settings.conn.secret" required>

      </fieldset>

            <button class="btn btn-primary" ng-click="save(settings.conn)"                     ng-disabled="!settings.verify(\'conn\', settings.conn) || saving">Submit</button>

    </form>

',link:function(d){d.saving=!1,d.settings=b,d.save=function(e){d.saving=!0,b.save("conn",e),c.$broadcast("message",{message:"attempting to connect to sockethub",type:"info",timeout:!1}),a.connect({register:!0}).then(function(){d.saving=!1,console.log("connected to sockethub"),c.$broadcast("message",{message:"connected to sockethub",type:"success",timeout:!0}),$("#modalSockethubSettings").modal("hide")},function(a){d.saving=!1,console.log("error connection to sockethub: ",a),c.$broadcast("message",{message:a,type:"error",timeout:!1})})}}}}]);<|endoftext|>


<commit_before>import Ember from "ember";
import Promise from "liquid-fire/promise";
var capitalize = Ember.String.capitalize;

export default Ember.Mixin.create({
  growDuration: 250,
  growPixelsPerSecond: 200,
  growEasing: 'slide',

  transitionMap: Ember.inject.service('liquid-fire-transitions'),

  animateGrowth: function(elt, have, want) {
    this.get('transitionMap').incrementRunningTransitions();
    return Promise.all([
      this._adaptDimension(elt, 'width', have, want),
      this._adaptDimension(elt, 'height', have, want)
    ]).then(()=>{
      this.get('transitionMap').decrementRunningTransitions();
    });
  },

  _adaptDimension: function(elt, dimension, have, want) {
    var target = {};
    target['outer'+capitalize(dimension)] = [
      want[dimension],
      have[dimension],
    ];
    return Ember.$.Velocity(elt[0], target, {
      duration: this._durationFor(have[dimension], want[dimension]),
      queue: false,
      easing: this.get('growEasing')
    });
  },

  _durationFor: function(before, after) {
    return Math.min(this.get('growDuration'), 1000*Math.abs(before - after)/this.get('growPixelsPerSecond'));
  }

});
<commit_msg>use own defaults if we've been set to undef<commit_after>import Ember from "ember";
import Promise from "liquid-fire/promise";
var capitalize = Ember.String.capitalize;

export default Ember.Mixin.create({
  growDuration: 250,
  growPixelsPerSecond: 200,
  growEasing: 'slide',

  transitionMap: Ember.inject.service('liquid-fire-transitions'),

  animateGrowth: function(elt, have, want) {
    this.get('transitionMap').incrementRunningTransitions();
    return Promise.all([
      this._adaptDimension(elt, 'width', have, want),
      this._adaptDimension(elt, 'height', have, want)
    ]).then(()=>{
      this.get('transitionMap').decrementRunningTransitions();
    });
  },

  _adaptDimension: function(elt, dimension, have, want) {
    var target = {};
    target['outer'+capitalize(dimension)] = [
      want[dimension],
      have[dimension],
    ];
    return Ember.$.Velocity(elt[0], target, {
      duration: this._durationFor(have[dimension], want[dimension]),
      queue: false,
      easing: this.get('growEasing') || this.constructor.prototype.growEasing
    });
  },

  _durationFor: function(before, after) {
    return Math.min(this.get('growDuration') || this.constructor.prototype.growDuration, 1000*Math.abs(before - after)/(this.get('growPixelsPerSecond')) || this.constructor.prototype.growPixelsPerSecond);
  }

});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        GameDeals table highlighter
// @namespace   ohmanger
// @grant       GM_xmlhttpRequest
// @include     https://www.reddit.com/r/GameDeals/comments/*
// @require     https://code.jquery.com/jquery-2.2.4.min.js
// @updateURL   https://raw.githubusercontent.com/ohmanger/userscripts/master/gamedeals-table-highlighter.user.js
// @downloadURL https://raw.githubusercontent.com/ohmanger/userscripts/master/gamedeals-table-highlighter.user.js
// @version     1.1.7
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true);

var users = [
	'.author.id-t2_bukfv', // /u/dEnissay
	'.author.id-t2_b1jfp', // /u/Ignarius
	'.author.id-t2_dau7q', // /u/NCPereira
	'.author.id-t2_in61j', // /u/ABOOD-THE-PLAYER
	'.author.id-t2_1pry1', // /u/pantsu
	'.author.id-t2_2uod1', // /u/Custard
  	'.author.id-t2_4rd82', // /u/incontrollable
];

$( users.join(',') ).each( function( index ) {

	var table = $( this ).parent().parent().find( '.usertext-body table' );
	table.after( '<button class="gdth-get-status">Get Steam status</button>' );

});

$( '.sitetable' ).on( 'click', 'button.gdth-get-status', function( event ) {
	event.preventDefault();

	var table_rows = $( this ).siblings( 'table' ).find( 'tbody tr' );

	table_rows.each( function ( index ) {
		var tr = $(this),
		    app_url = tr.html().match( /http:\/\/store\.steampowered\.com\/app\/(\d*)\//ig );

		// Skip if no steam URL found
		if ( app_url === null ) {
			return 'continue';
		}

		GM_xmlhttpRequest ( {
			method:  "GET",
			url:     app_url[0],
			onload:  function ( response ) {
				var is_logged_in = response.responseText.indexOf( "Logout();" ) > -1;
				if ( is_logged_in ) {
					var in_library = response.responseText.indexOf( '
' ) > -1;

					if ( in_library ) {
						tr.css( 'background', 'lightgreen' );
					} else {
						var in_wishlist = response.responseText.indexOf( '<div id="add_to_wishlist_area_success"' ) === -1;
						if ( in_wishlist ) {
							tr.css( 'background', 'lightblue' );
						} else {
							tr.css( 'background', '' );
						}
					}
				}
			}
		});
	});
});
<commit_msg>Update jQuery to 3.1.1 slim<commit_after>// ==UserScript==
// @name        GameDeals table highlighter
// @namespace   ohmanger
// @grant       GM_xmlhttpRequest
// @include     https://www.reddit.com/r/GameDeals/comments/*
// @require     https://code.jquery.com/jquery-3.1.1.slim.min.js
// @updateURL   https://raw.githubusercontent.com/ohmanger/userscripts/master/gamedeals-table-highlighter.user.js
// @downloadURL https://raw.githubusercontent.com/ohmanger/userscripts/master/gamedeals-table-highlighter.user.js
// @version     1.1.8
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true);

var users = [
	'.author.id-t2_bukfv', // /u/dEnissay
	'.author.id-t2_b1jfp', // /u/Ignarius
	'.author.id-t2_dau7q', // /u/NCPereira
	'.author.id-t2_in61j', // /u/ABOOD-THE-PLAYER
	'.author.id-t2_1pry1', // /u/pantsu
	'.author.id-t2_2uod1', // /u/Custard
  	'.author.id-t2_4rd82', // /u/incontrollable
];

$( users.join(',') ).each( function( index ) {

	var table = $( this ).parent().parent().find( '.usertext-body table' );
	table.after( '<button class="gdth-get-status">Get Steam status</button>' );

});

$( '.sitetable' ).on( 'click', 'button.gdth-get-status', function( event ) {
	event.preventDefault();

	var table_rows = $( this ).siblings( 'table' ).find( 'tbody tr' );

	table_rows.each( function ( index ) {
		var tr = $(this),
		    app_url = tr.html().match( /http:\/\/store\.steampowered\.com\/app\/(\d*)\//ig );

		// Skip if no steam URL found
		if ( app_url === null ) {
			return 'continue';
		}

		GM_xmlhttpRequest ( {
			method:  "GET",
			url:     app_url[0],
			onload:  function ( response ) {
				var is_logged_in = response.responseText.indexOf( "Logout();" ) > -1;
				if ( is_logged_in ) {
					var in_library = response.responseText.indexOf( '
' ) > -1;

					if ( in_library ) {
						tr.css( 'background', 'lightgreen' );
					} else {
						var in_wishlist = response.responseText.indexOf( '<div id="add_to_wishlist_area_success"' ) === -1;
						if ( in_wishlist ) {
							tr.css( 'background', 'lightblue' );
						} else {
							tr.css( 'background', '' );
						}
					}
				}
			}
		});
	});
});
<|endoftext|>


<commit_before>/*
 * chesterGL - Simple 2D WebGL demo/library
 *
 * Copyright (c) 2010-2012 Rolando Abarca
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

goog.provide("chesterGL.BlockGroup");

goog.require("goog.vec.Mat4");
goog.require("chesterGL.Block");

/**
 * creates a new block group
 *
 * @constructor
 * @param {(string|null)=} texture An optional texture that will be shared with all children
 * @param {number=} noChildren The optional initial number of maxChidlren. Defaults to 10
 * @extends {chesterGL.Block}
 */
chesterGL.BlockGroup = function (texture, noChildren) {
	if (!chesterGL.webglMode) {
		throw "BlockGroup only works on WebGL mode";
	}
	// call "super"
	chesterGL.Block.call(this, null, chesterGL.Block.TYPE['BLOCKGROUP']);
	if (texture) {
		this.texture = texture;
		this.program = chesterGL.Block.PROGRAM['TEXTURE'];
	} else {
		this.program = chesterGL.Block.PROGRAM['DEFAULT'];
	}
	this.maxChildren = noChildren || 10;

	// create the buffers for the children
	this.createBuffers();
};
goog.inherits(chesterGL.BlockGroup, chesterGL.Block);

/**
 * The max number of children this blockgroup can hold (this is here for the buffer data)
 * @type {number}
 * @ignore
 */
chesterGL.BlockGroup.prototype.maxChildren = 0;

/**
 * @type {boolean}
 * @ignore
 */
chesterGL.BlockGroup.prototype.isChildDirty = false;

/**
 * @type {?WebGLBuffer}
 * @ignore
 */
chesterGL.BlockGroup.prototype.indexBuffer = null;

/**
 * @type {?Uint16Array}
 * @ignore
 */
chesterGL.BlockGroup.prototype.indexBufferData = null;

/**
 * Creates the buffers for the current maxChildren size
 * @param {Array|Float32Array=} oldBufferData
 * @param {Array|Uint16Array=} oldIndexData
 * @ignore
 */
chesterGL.BlockGroup.prototype.createBuffers = function (oldBufferData, oldIndexData) {
	var gl = chesterGL.gl;
	if (!this.glBuffer)
		this.glBuffer = gl.createBuffer();
	if (!this.indexBuffer)
		this.indexBuffer = gl.createBuffer();

	var glBufferData    = new Float32Array(chesterGL.Block.QUAD_SIZE * this.maxChildren);
	var indexBufferData = new Uint16Array(6 * this.maxChildren);
	if (oldBufferData) {
		glBufferData.set(oldBufferData);
	}
	if (oldIndexData) {
		indexBufferData.set(oldIndexData);
	}
	this.glBufferData = glBufferData;
	this.indexBufferData = indexBufferData;
};

/**
 * creates a block that can be added to this block group
 * @param {goog.vec.Vec4.Type} rect
 */
chesterGL.BlockGroup.prototype.createBlock = function (rect) {
	var b = new chesterGL.Block(rect, chesterGL.Block.TYPE['STANDALONE'], this);
	if (this.texture) {
		b.setTexture(this.texture);
	}
	return b;
};

/**
 * adds a child
 * @param {chesterGL.Block} block
 */
chesterGL.BlockGroup.prototype.addChild = function (block) {
	if (block.parent != this) {
		throw "Invalid child: can only add children created with BlockGroup.create";
	}
	if (this.children.length >= this.maxChildren) {
		// should resize the buffers
		this.maxChildren *= 2;
		this.createBuffers(this.glBufferData, this.indexBufferData);
	}
	if (!this.texture) {
		this.texture = block.texture;
	} else {
		if (this.texture != block.texture) {
			throw "Invalid child: only can add child with the same texture";
		}
	}
	this.children.push(block);

	var length = this.children.length;

	// just point the buffer data on the child and set the baseIndex
	block.baseBufferIndex = length-1;
	block.glBufferData    = this.glBufferData;
	this.isChildDirty = true;
};

/**
 * removes a block from the group
 * @param {chesterGL.Block} b
 */
chesterGL.BlockGroup.prototype.removeChild = function (b) {
	if (b.parent != this) {
		throw "Invalid child";
	}
	if (this._inVisit) {
		this._scheduledRemove.push(b);
	} else {
		var idx = this.children.indexOf(b);
		if (idx > 0) {
			this.children.splice(idx, 1);
			// for the rest of the children, mark them as dirty and reduce the baseBufferIndex
			for (var i=idx; i < this.totalChildren; i++) {
				var _b = this.children[i];
				_b.baseBufferIndex = i;
				_b.isTransformDirty = true;
				_b.isColorDirty = true;
			}
		}
		this.isChildDirty = true;
	}
};

/**
 * when the block list changes, the indices array must be recreated
 * @param {number} startIdx
 */
chesterGL.BlockGroup.prototype.recreateIndices = function (startIdx) {
	var lastIdx = (this.indexBufferData[startIdx*6 - 1] || -1) + 1;
	var total = Math.max(this.children.length, 1);
	for (var i = startIdx; i < total; i ++) {
		var idx = i*6;
		this.indexBufferData[idx + 0] = lastIdx    ; this.indexBufferData[idx + 1] = lastIdx + 1; this.indexBufferData[idx + 2] = lastIdx + 2;
		this.indexBufferData[idx + 3] = lastIdx + 2; this.indexBufferData[idx + 4] = lastIdx + 1; this.indexBufferData[idx + 5] = lastIdx + 3;
		lastIdx += 4;
	}
	var gl = chesterGL.gl;
	gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
	gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indexBufferData, gl.STATIC_DRAW);
};

/**
 * where the fun begins
 * @ignore
 */
chesterGL.BlockGroup.prototype.visit = function () {
	this._inVisit = true;
	if (this.update) {
		this.update(chesterGL.delta);
	}
	if (!this.visible) {
		this._inVisit = false;
		return;
	}
	this.transform();

	// this should be more like cocos2d: preserve the z-ordering
	var children = this.children;
	var len = children.length;
	for (var i=0; i < len; i++) {
		children[i].visit();
	}

	// re-bind the glBuffer (might have changed in the children visit)
	var gl = chesterGL.gl;
	gl.bindBuffer(gl.ARRAY_BUFFER, this.glBuffer);
	gl.bufferData(gl.ARRAY_BUFFER, this.glBufferData, gl.STATIC_DRAW);

	if (this.isChildDirty) {
		this.recreateIndices(0);
		this.isChildDirty = false;
	}
	// render this block group
	this.render();

	// reset our dirty markers
	this.isFrameDirty = this.isColorDirty = this.isTransformDirty = false;
	this._inVisit = false;

	var b;
	while ((b = this._scheduledRemove.shift())) {
		this.removeChild(b);
	}
};

/**
 * actually render the block group
 * @ignore
 */
chesterGL.BlockGroup.prototype.render = function () {
	var gl = chesterGL.gl;

	// select current shader
	var program = chesterGL.selectProgram(chesterGL.Block.PROGRAM_NAME[this.program]);
	var totalChildren = this.children.length;
	var texOff = 3 * 4,
		colorOff = texOff + 2 * 4,
		stride = chesterGL.Block.QUAD_SIZE;

	gl.bindBuffer(gl.ARRAY_BUFFER, this.glBuffer);

	gl.vertexAttribPointer(program.attribs['vertexPositionAttribute'], 3, gl.FLOAT, false, stride, 0);
	if (this.program == chesterGL.Block.PROGRAM['DEFAULT']) {
		// no extra attributes for the shader
	} else if (this.program == chesterGL.Block.PROGRAM['TEXTURE']) {
		var texture = chesterGL.getAsset('texture', this.texture);

		// pass the texture attributes
		gl.vertexAttribPointer(program.attribs['textureCoordAttribute'], 2, gl.FLOAT, false, stride, texOff);

		gl.activeTexture(gl.TEXTURE0);
		gl.bindTexture(gl.TEXTURE_2D, texture.tex);
		gl.uniform1i(program.samplerUniform, 0);
	}
	gl.vertexAttribPointer(program.attribs['vertexColorAttribute'], 4, gl.FLOAT, false, stride, colorOff);

	gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);

	// set the matrix uniform (the multiplied model view projection matrix)
	goog.vec.Mat4.multMat(chesterGL.pMatrix, this.mvMatrix, this.mvpMatrix);
	gl.uniformMatrix4fv(program.mvpMatrixUniform, false, this.mvpMatrix);
	// gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4 * this.children.length);
	gl.drawElements(gl.TRIANGLES, totalChildren * 6, gl.UNSIGNED_SHORT, 0);
};

// export the symbol
goog.exportSymbol('chesterGL.BlockGroup', chesterGL.BlockGroup);
// instance methods
goog.exportProperty(chesterGL.BlockGroup.prototype, 'createBlock', chesterGL.BlockGroup.prototype.createBlock);
goog.exportProperty(chesterGL.BlockGroup.prototype, 'addChild', chesterGL.BlockGroup.prototype.addChild);
goog.exportProperty(chesterGL.BlockGroup.prototype, 'removeChild', chesterGL.BlockGroup.prototype.removeChild);
<commit_msg>removes old comment<commit_after>/*
 * chesterGL - Simple 2D WebGL demo/library
 *
 * Copyright (c) 2010-2012 Rolando Abarca
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

goog.provide("chesterGL.BlockGroup");

goog.require("goog.vec.Mat4");
goog.require("chesterGL.Block");

/**
 * creates a new block group
 *
 * @constructor
 * @param {(string|null)=} texture An optional texture that will be shared with all children
 * @param {number=} noChildren The optional initial number of maxChidlren. Defaults to 10
 * @extends {chesterGL.Block}
 */
chesterGL.BlockGroup = function (texture, noChildren) {
	if (!chesterGL.webglMode) {
		throw "BlockGroup only works on WebGL mode";
	}
	// call "super"
	chesterGL.Block.call(this, null, chesterGL.Block.TYPE['BLOCKGROUP']);
	if (texture) {
		this.texture = texture;
		this.program = chesterGL.Block.PROGRAM['TEXTURE'];
	} else {
		this.program = chesterGL.Block.PROGRAM['DEFAULT'];
	}
	this.maxChildren = noChildren || 10;

	// create the buffers for the children
	this.createBuffers();
};
goog.inherits(chesterGL.BlockGroup, chesterGL.Block);

/**
 * The max number of children this blockgroup can hold (this is here for the buffer data)
 * @type {number}
 * @ignore
 */
chesterGL.BlockGroup.prototype.maxChildren = 0;

/**
 * @type {boolean}
 * @ignore
 */
chesterGL.BlockGroup.prototype.isChildDirty = false;

/**
 * @type {?WebGLBuffer}
 * @ignore
 */
chesterGL.BlockGroup.prototype.indexBuffer = null;

/**
 * @type {?Uint16Array}
 * @ignore
 */
chesterGL.BlockGroup.prototype.indexBufferData = null;

/**
 * Creates the buffers for the current maxChildren size
 * @param {Array|Float32Array=} oldBufferData
 * @param {Array|Uint16Array=} oldIndexData
 * @ignore
 */
chesterGL.BlockGroup.prototype.createBuffers = function (oldBufferData, oldIndexData) {
	var gl = chesterGL.gl;
	if (!this.glBuffer)
		this.glBuffer = gl.createBuffer();
	if (!this.indexBuffer)
		this.indexBuffer = gl.createBuffer();

	var glBufferData    = new Float32Array(chesterGL.Block.QUAD_SIZE * this.maxChildren);
	var indexBufferData = new Uint16Array(6 * this.maxChildren);
	if (oldBufferData) {
		glBufferData.set(oldBufferData);
	}
	if (oldIndexData) {
		indexBufferData.set(oldIndexData);
	}
	this.glBufferData = glBufferData;
	this.indexBufferData = indexBufferData;
};

/**
 * creates a block that can be added to this block group
 * @param {goog.vec.Vec4.Type} rect
 */
chesterGL.BlockGroup.prototype.createBlock = function (rect) {
	var b = new chesterGL.Block(rect, chesterGL.Block.TYPE['STANDALONE'], this);
	if (this.texture) {
		b.setTexture(this.texture);
	}
	return b;
};

/**
 * adds a child
 * @param {chesterGL.Block} block
 */
chesterGL.BlockGroup.prototype.addChild = function (block) {
	if (block.parent != this) {
		throw "Invalid child: can only add children created with BlockGroup.create";
	}
	if (this.children.length >= this.maxChildren) {
		// should resize the buffers
		this.maxChildren *= 2;
		this.createBuffers(this.glBufferData, this.indexBufferData);
	}
	if (!this.texture) {
		this.texture = block.texture;
	} else {
		if (this.texture != block.texture) {
			throw "Invalid child: only can add child with the same texture";
		}
	}
	this.children.push(block);

	var length = this.children.length;

	// just point the buffer data on the child and set the baseIndex
	block.baseBufferIndex = length-1;
	block.glBufferData    = this.glBufferData;
	this.isChildDirty = true;
};

/**
 * removes a block from the group
 * @param {chesterGL.Block} b
 */
chesterGL.BlockGroup.prototype.removeChild = function (b) {
	if (b.parent != this) {
		throw "Invalid child";
	}
	if (this._inVisit) {
		this._scheduledRemove.push(b);
	} else {
		var idx = this.children.indexOf(b);
		if (idx > 0) {
			this.children.splice(idx, 1);
			// for the rest of the children, mark them as dirty and reduce the baseBufferIndex
			for (var i=idx; i < this.totalChildren; i++) {
				var _b = this.children[i];
				_b.baseBufferIndex = i;
				_b.isTransformDirty = true;
				_b.isColorDirty = true;
			}
		}
		this.isChildDirty = true;
	}
};

/**
 * when the block list changes, the indices array must be recreated
 * @param {number} startIdx
 */
chesterGL.BlockGroup.prototype.recreateIndices = function (startIdx) {
	var lastIdx = (this.indexBufferData[startIdx*6 - 1] || -1) + 1;
	var total = Math.max(this.children.length, 1);
	for (var i = startIdx; i < total; i ++) {
		var idx = i*6;
		this.indexBufferData[idx + 0] = lastIdx    ; this.indexBufferData[idx + 1] = lastIdx + 1; this.indexBufferData[idx + 2] = lastIdx + 2;
		this.indexBufferData[idx + 3] = lastIdx + 2; this.indexBufferData[idx + 4] = lastIdx + 1; this.indexBufferData[idx + 5] = lastIdx + 3;
		lastIdx += 4;
	}
	var gl = chesterGL.gl;
	gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
	gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indexBufferData, gl.STATIC_DRAW);
};

/**
 * where the fun begins
 * @ignore
 */
chesterGL.BlockGroup.prototype.visit = function () {
	this._inVisit = true;
	if (this.update) {
		this.update(chesterGL.delta);
	}
	if (!this.visible) {
		this._inVisit = false;
		return;
	}
	this.transform();

	// this should be more like cocos2d: preserve the z-ordering
	var children = this.children;
	var len = children.length;
	for (var i=0; i < len; i++) {
		children[i].visit();
	}

	// re-bind the glBuffer (might have changed in the children visit)
	var gl = chesterGL.gl;
	gl.bindBuffer(gl.ARRAY_BUFFER, this.glBuffer);
	gl.bufferData(gl.ARRAY_BUFFER, this.glBufferData, gl.STATIC_DRAW);

	if (this.isChildDirty) {
		this.recreateIndices(0);
		this.isChildDirty = false;
	}
	// render this block group
	this.render();

	// reset our dirty markers
	this.isFrameDirty = this.isColorDirty = this.isTransformDirty = false;
	this._inVisit = false;

	var b;
	while ((b = this._scheduledRemove.shift())) {
		this.removeChild(b);
	}
};

/**
 * actually render the block group
 * @ignore
 */
chesterGL.BlockGroup.prototype.render = function () {
	var gl = chesterGL.gl;

	// select current shader
	var program = chesterGL.selectProgram(chesterGL.Block.PROGRAM_NAME[this.program]);
	var totalChildren = this.children.length;
	var texOff = 3 * 4,
		colorOff = texOff + 2 * 4,
		stride = chesterGL.Block.QUAD_SIZE;

	gl.bindBuffer(gl.ARRAY_BUFFER, this.glBuffer);

	gl.vertexAttribPointer(program.attribs['vertexPositionAttribute'], 3, gl.FLOAT, false, stride, 0);
	if (this.program == chesterGL.Block.PROGRAM['DEFAULT']) {
		// no extra attributes for the shader
	} else if (this.program == chesterGL.Block.PROGRAM['TEXTURE']) {
		var texture = chesterGL.getAsset('texture', this.texture);

		// pass the texture attributes
		gl.vertexAttribPointer(program.attribs['textureCoordAttribute'], 2, gl.FLOAT, false, stride, texOff);

		gl.activeTexture(gl.TEXTURE0);
		gl.bindTexture(gl.TEXTURE_2D, texture.tex);
		gl.uniform1i(program.samplerUniform, 0);
	}
	gl.vertexAttribPointer(program.attribs['vertexColorAttribute'], 4, gl.FLOAT, false, stride, colorOff);

	gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);

	// set the matrix uniform (the multiplied model view projection matrix)
	goog.vec.Mat4.multMat(chesterGL.pMatrix, this.mvMatrix, this.mvpMatrix);
	gl.uniformMatrix4fv(program.mvpMatrixUniform, false, this.mvpMatrix);
	gl.drawElements(gl.TRIANGLES, totalChildren * 6, gl.UNSIGNED_SHORT, 0);
};

// export the symbol
goog.exportSymbol('chesterGL.BlockGroup', chesterGL.BlockGroup);
// instance methods
goog.exportProperty(chesterGL.BlockGroup.prototype, 'createBlock', chesterGL.BlockGroup.prototype.createBlock);
goog.exportProperty(chesterGL.BlockGroup.prototype, 'addChild', chesterGL.BlockGroup.prototype.addChild);
goog.exportProperty(chesterGL.BlockGroup.prototype, 'removeChild', chesterGL.BlockGroup.prototype.removeChild);
<|endoftext|>


<commit_before>(function(angular) {
  'use strict';
  angular.module('chocoboRangePicker', [])
    .directive('chocoboRangePicker', [function() {

      String.prototype.capitalizeFirstLetter = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
      };

      Date.prototype.reverseFormat = function(tDate, locale) {
        if (locale === 'pt-BR' || locale === 'en-GB') {
          var formatDate = tDate.split('/');
          return new Date(formatDate[2], formatDate[1] - 1, formatDate[0]);
        }
        if (locale === 'de-DE') {
          var parts = tDate.match(/(\d+)/g);
          return new Date(parts[2], parts[1] - 1, parts[0]);
        }
        return new Date(tDate);
      };

      return {
        require: 'ngModel',
        restrict: 'AE',
        scope: {
          locale: '@',
          options: '='
        },
        link: function(scope, elem, attrs, ngModel) {

          /**
           * DATE MANIPULATION
           */

          // Date Operation Enumerator
          var DATEOPERATION = {
            DAY: 0,
            MONTH: 1,
            YEAR: 2
          };

          // Date Operation Function - Used to manipulate date
          function dateOperation(date, value, operation, createNewObject) {
            var newDate = date;

            if (typeof createNewObject !== 'undefined' ? createNewObject : false) {
              newDate = new Date(date.getTime());
            }

            if (operation === DATEOPERATION.DAY) {
              newDate.setDate(newDate.getDate() + value);
            } else if (operation === DATEOPERATION.MONTH) {
              newDate.setMonth(newDate.getMonth() + value);
            } else if (operation === DATEOPERATION.YEAR) {
              newDate.setFullYear(newDate.getFullYear() + value);
            }

            return newDate;
          }

          // Remove timepart of a date
          function dateWithoutTime(date) {
            date.setHours(0, 0, 0, 0);
            return date;
          }

          // Compare if two date are equals
          scope.isEqualsDate = function(a, b) {
            return dateWithoutTime(a).getTime() === dateWithoutTime(b).getTime();
          };

          // Check if a date is between of two dates
          scope.isBetweenDate = function(date, a, b) {
            return dateWithoutTime(date).getTime() >= dateWithoutTime(a).getTime() && dateWithoutTime(date).getTime() <= dateWithoutTime(b).getTime();
          };

          // Check if a date is before or equal
          scope.isBeforeOrEqual = function(a, b) {
            return dateWithoutTime(a).getTime() <= dateWithoutTime(b).getTime();
          };

          // Check if a date is after or equal
          scope.isAfterOrEqual = function(a, b) {
            return dateWithoutTime(a).getTime() >= dateWithoutTime(b).getTime();
          };

          /**
           * CALENDAR
           */

          function updateCalendar(calendar) {
            var calendarMonth = calendar.baseDate.getMonth();

            // Find the nearst start week day
            var start = new Date(calendar.baseDate.getTime());
            start.setDate(1);
            start.setDate(start.getDate() - start.getDay());

            // Find the last week after end of month
            var end = new Date(calendar.baseDate.getTime());
            end.setDate(1);
            end.setMonth(end.getMonth() + 1);
            end.setDate(0);
            end.setDate(end.getDate() + (6 - start.getDay()));

            calendar.weeks = [];

            var week = {};
            while(scope.isEqualsDate(start, end) === false) {
              week[start.getDay()] = {
                date: new Date(start.getTime()),
                calendarMonth: start.getMonth() === calendarMonth,
              };

              // End of a week reached
              if (start.getDay() === 6) {
                calendar.weeks.push(week);
                week = {};
              }

              dateOperation(start, 1, DATEOPERATION.DAY);
            }
          }

          // Go to the next month
          scope.nextMonth = function(calendar) {
            dateOperation(calendar.baseDate, 1, DATEOPERATION.MONTH);
            updateCalendar(calendar);
          };

          // Go to the previous month
          scope.previousMonth = function(calendar) {
            dateOperation(calendar.baseDate, -1, DATEOPERATION.MONTH);
            updateCalendar(calendar);
          };

          // Generate an array of weekdays
          scope.weekdays = function() {
            var date = new Date();

            // Get first day of week
            date.setDate(date.getDate() - date.getDay());

            // Create an array of localized weekday
            var weekList = [scope.localeWeekday(date)];
            for (var i = 0; i < 6; i++) {
              date.setDate(date.getDate() + 1);
              weekList.push(scope.localeWeekday(date));
            }

            return weekList;
          };

          // Method called when a date is selected
          scope.selectDate = function(calendar, date) {
            calendar.baseDate = new Date(date.getTime());
            calendar.selectedDate = new Date(date.getTime());

            updateCalendar(calendar);
            updateModel();
          };

          /**
           * Locale
           */

          scope.localeMonth = function(date) {
            return date.toLocaleDateString(attrs.locale, { month: 'long' }).capitalizeFirstLetter();
          };

          scope.localeYear = function(date) {
            return date.toLocaleDateString(attrs.locale, { year: 'numeric' }).capitalizeFirstLetter();
          };

          scope.localeWeekday = function(date) {
            return date.toLocaleDateString(attrs.locale, { weekday: 'long' }).capitalizeFirstLetter();
          };

          scope.localeDate = function(date) {
            return date.toLocaleDateString(attrs.locale, { day: '2-digit', month: '2-digit', year: 'numeric' });
          };

          /**
           * Variables - Initial configurations
           */

          var currentDate = new Date();
          currentDate.setHours(0, 0, 0, 0);

          scope.leftCalendar = {
            baseDate: new Date(currentDate.getTime()),
            selectedDate: new Date(currentDate.getTime()),
            weeks: []
          };
          updateCalendar(scope.leftCalendar);

          scope.rightCalendar = {
            baseDate: new Date(currentDate.getTime()),
            selectedDate: new Date(currentDate.getTime()),
            weeks: []
          };
          updateCalendar(scope.rightCalendar);

          /**
           * Modal
           */

          scope.openModal = function() {
            scope.isOpen = !scope.isOpen;
          };

          scope.isOpen = !scope.isOpen;

          scope.iconUrl = '/public/calendar.ico';

          /**
           * Model
           */

          // Method called to update ngModel for the parent controller
          function updateModel() {
            var start = new Date(scope.leftCalendar.selectedDate.getTime());
            var end = dateOperation(scope.rightCalendar.selectedDate, 1, DATEOPERATION.DAY, true);

            var days = [];
            while(scope.isEqualsDate(start, end) === false) {
              days.push(new Date(start.getTime()));
              dateOperation(start, 1, DATEOPERATION.DAY);
            }

            ngModel.$setViewValue(days);
            ngModel.$render();
          }

          /**
           * PERIODS
           */

          // Set a period of dates
          scope.setPeriod = function(start, end) {
            scope.leftCalendar.baseDate = new Date(start.getTime());
            scope.leftCalendar.selectedDate = new Date(start.getTime());
            updateCalendar(scope.leftCalendar);

            scope.rightCalendar.baseDate = new Date(end.getTime());
            scope.rightCalendar.selectedDate = new Date(end.getTime());
            updateCalendar(scope.rightCalendar);

            updateModel();
          };

          scope.selectYear = function() {
            scope.setPeriod(dateOperation(currentDate, -1, DATEOPERATION.YEAR, true), new Date(currentDate.getTime()));
          };

          scope.selectSemester = function() {
            scope.setPeriod(dateOperation(currentDate, -6, DATEOPERATION.MONTH, true), new Date(currentDate.getTime()));
          };

          scope.selectTrimester = function() {
            scope.setPeriod(dateOperation(currentDate, -3, DATEOPERATION.MONTH, true), new Date(currentDate.getTime()));
          };

          scope.selectMonth = function() {
            scope.setPeriod(dateOperation(currentDate, -1, DATEOPERATION.MONTH, true), new Date(currentDate.getTime()));
          };

          scope.selectWeek = function() {
            scope.setPeriod(dateOperation(currentDate, -7, DATEOPERATION.DAY, true), new Date(currentDate.getTime()));
          };

          scope.selectLastDay = function() {
            scope.setPeriod(dateOperation(currentDate, -1, DATEOPERATION.DAY, true), new Date(currentDate.getTime()));
          };

          scope.selectToday = function() {
            scope.setPeriod(new Date(currentDate.getTime()), new Date(currentDate.getTime()));
          };
        },
        replace: true,
        templateUrl: 'chocobo-range-picker.html'
      };
    }]);
})(angular);<commit_msg>Fixed issue #6 #8<commit_after>(function(angular) {
  'use strict';
  angular.module('chocoboRangePicker', [])
    .directive('chocoboRangePicker', [function() {

      String.prototype.capitalizeFirstLetter = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
      };

      Date.prototype.reverseFormat = function(tDate, locale) {
        if (locale === 'pt-BR' || locale === 'en-GB') {
          var formatDate = tDate.split('/');
          return new Date(formatDate[2], formatDate[1] - 1, formatDate[0]);
        }
        if (locale === 'de-DE') {
          var parts = tDate.match(/(\d+)/g);
          return new Date(parts[2], parts[1] - 1, parts[0]);
        }
        return new Date(tDate);
      };

      return {
        require: 'ngModel',
        restrict: 'AE',
        scope: {
          locale: '@',
          options: '='
        },
        link: function(scope, elem, attrs, ngModel) {

          /**
           * DATE MANIPULATION
           */

          // Date Operation Enumerator
          var DATEOPERATION = {
            DAY: 0,
            MONTH: 1,
            YEAR: 2
          };

          // Date Operation Function - Used to manipulate date
          function dateOperation(date, value, operation, createNewObject) {
            var newDate = date;

            if (typeof createNewObject !== 'undefined' ? createNewObject : false) {
              newDate = new Date(date.getTime());
            }

            if (operation === DATEOPERATION.DAY) {
              newDate.setDate(newDate.getDate() + value);
            } else if (operation === DATEOPERATION.MONTH) {
              newDate.setMonth(newDate.getMonth() + value);
            } else if (operation === DATEOPERATION.YEAR) {
              newDate.setFullYear(newDate.getFullYear() + value);
            }

            return newDate;
          }

          // Remove timepart of a date
          function dateWithoutTime(date) {
            date.setHours(0, 0, 0, 0);
            return date;
          }

          // Compare if two date are equals
          scope.isEqualsDate = function(a, b) {
            return dateWithoutTime(a).getTime() === dateWithoutTime(b).getTime();
          };

          // Check if a date is between of two dates
          scope.isBetweenDate = function(date, a, b) {
            return dateWithoutTime(date).getTime() >= dateWithoutTime(a).getTime() && dateWithoutTime(date).getTime() <= dateWithoutTime(b).getTime();
          };

          // Check if a date is before or equal
          scope.isBeforeOrEqual = function(a, b) {
            return dateWithoutTime(a).getTime() <= dateWithoutTime(b).getTime();
          };

          // Check if a date is after or equal
          scope.isAfterOrEqual = function(a, b) {
            return dateWithoutTime(a).getTime() >= dateWithoutTime(b).getTime();
          };

          /**
           * CALENDAR
           */

          function updateCalendar(calendar) {
            var calendarMonth = calendar.baseDate.getMonth();

            // Find the nearst start week day
            var start = new Date(calendar.baseDate.getTime());
            start.setDate(1);
            start.setDate(start.getDate() - start.getDay());

            // Find the last week after end of month
            var end = new Date(calendar.baseDate.getTime());
            end.setDate(1);
            end.setMonth(end.getMonth() + 1);
            end.setDate(0);
            end.setDate(end.getDate() + (6 - end.getDay()));

            calendar.weeks = [];

            var week = {};
            while(scope.isBeforeOrEqual(start, end)) {
              week[start.getDay()] = {
                date: new Date(start.getTime()),
                calendarMonth: start.getMonth() === calendarMonth,
              };

              // End of a week reached
              if (start.getDay() === 6) {
                calendar.weeks.push(week);
                week = {};
              }

              dateOperation(start, 1, DATEOPERATION.DAY);
            }
          }

          // Go to the next month
          scope.nextMonth = function(calendar) {
            dateOperation(calendar.baseDate, 1, DATEOPERATION.MONTH);
            updateCalendar(calendar);
          };

          // Go to the previous month
          scope.previousMonth = function(calendar) {
            dateOperation(calendar.baseDate, -1, DATEOPERATION.MONTH);
            updateCalendar(calendar);
          };

          // Generate an array of weekdays
          scope.weekdays = function() {
            var date = new Date();

            // Get first day of week
            date.setDate(date.getDate() - date.getDay());

            // Create an array of localized weekday
            var weekList = [scope.localeWeekday(date)];
            for (var i = 0; i < 6; i++) {
              date.setDate(date.getDate() + 1);
              weekList.push(scope.localeWeekday(date));
            }

            return weekList;
          };

          // Method called when a date is selected
          scope.selectDate = function(calendar, date) {
            calendar.baseDate = new Date(date.getTime());
            calendar.selectedDate = new Date(date.getTime());

            updateCalendar(calendar);
            updateModel();
          };

          /**
           * Locale
           */

          scope.localeMonth = function(date) {
            return date.toLocaleDateString(attrs.locale, { month: 'long' }).capitalizeFirstLetter();
          };

          scope.localeYear = function(date) {
            return date.toLocaleDateString(attrs.locale, { year: 'numeric' }).capitalizeFirstLetter();
          };

          scope.localeWeekday = function(date) {
            return date.toLocaleDateString(attrs.locale, { weekday: 'long' }).capitalizeFirstLetter();
          };

          scope.localeDate = function(date) {
            return date.toLocaleDateString(attrs.locale, { day: '2-digit', month: '2-digit', year: 'numeric' });
          };

          /**
           * Variables - Initial configurations
           */

          var currentDate = new Date();
          currentDate.setHours(0, 0, 0, 0);

          scope.leftCalendar = {
            baseDate: new Date(currentDate.getTime()),
            selectedDate: new Date(currentDate.getTime()),
            weeks: []
          };
          updateCalendar(scope.leftCalendar);

          scope.rightCalendar = {
            baseDate: new Date(currentDate.getTime()),
            selectedDate: new Date(currentDate.getTime()),
            weeks: []
          };
          updateCalendar(scope.rightCalendar);

          /**
           * Modal
           */

          scope.openModal = function() {
            scope.isOpen = !scope.isOpen;
          };

          scope.isOpen = !scope.isOpen;

          scope.iconUrl = '/public/calendar.ico';

          /**
           * Model
           */

          // Method called to update ngModel for the parent controller
          function updateModel() {
            var start = new Date(scope.leftCalendar.selectedDate.getTime());
            var end = dateOperation(scope.rightCalendar.selectedDate, 1, DATEOPERATION.DAY, true);

            var days = [];
            while(scope.isEqualsDate(start, end) === false) {
              days.push(new Date(start.getTime()));
              dateOperation(start, 1, DATEOPERATION.DAY);
            }

            ngModel.$setViewValue(days);
            ngModel.$render();
          }

          /**
           * PERIODS
           */

          // Set a period of dates
          scope.setPeriod = function(start, end) {
            scope.leftCalendar.baseDate = new Date(start.getTime());
            scope.leftCalendar.selectedDate = new Date(start.getTime());
            updateCalendar(scope.leftCalendar);

            scope.rightCalendar.baseDate = new Date(end.getTime());
            scope.rightCalendar.selectedDate = new Date(end.getTime());
            updateCalendar(scope.rightCalendar);

            updateModel();
          };

          scope.selectYear = function() {
            scope.setPeriod(dateOperation(currentDate, -1, DATEOPERATION.YEAR, true), new Date(currentDate.getTime()));
          };

          scope.selectSemester = function() {
            scope.setPeriod(dateOperation(currentDate, -6, DATEOPERATION.MONTH, true), new Date(currentDate.getTime()));
          };

          scope.selectTrimester = function() {
            scope.setPeriod(dateOperation(currentDate, -3, DATEOPERATION.MONTH, true), new Date(currentDate.getTime()));
          };

          scope.selectMonth = function() {
            scope.setPeriod(dateOperation(currentDate, -1, DATEOPERATION.MONTH, true), new Date(currentDate.getTime()));
          };

          scope.selectWeek = function() {
            scope.setPeriod(dateOperation(currentDate, -7, DATEOPERATION.DAY, true), new Date(currentDate.getTime()));
          };

          scope.selectLastDay = function() {
            scope.setPeriod(dateOperation(currentDate, -1, DATEOPERATION.DAY, true), new Date(currentDate.getTime()));
          };

          scope.selectToday = function() {
            scope.setPeriod(new Date(currentDate.getTime()), new Date(currentDate.getTime()));
          };
        },
        replace: true,
        templateUrl: 'chocobo-range-picker.html'
      };
    }]);
})(angular);<|endoftext|>


<commit_before>function BatchCommand(){

}

BatchCommand.OOL = "";

module.exports = BatchCommand;<commit_msg>design change<commit_after><|endoftext|>