<commit_before>window['ZuckitaDaGalera'] = window['Zuck'] = function (timeline, options) {
    'use strict';

    var d = document, zuck = this;
    if(typeof timeline == 'string') {
        timeline = d.getElementById(timeline);
    }

    var q = function (query) {
            return d.querySelectorAll(query)[0];
        },
        g = function (array, what) {
            if(array) {
                return array[what] || '';
            } else {
                return '';
            }
        },
        each = function (arr, func) {
            if(arr) {
                var total = arr.length;

                for (var i=0; i<total; i++) {
                    func(i, arr[i]);
                }
            }
        },
        setVendorVariable = function(ref, variable, value){
            var variables = [variable.toLowerCase(),'webkit'+variable,'MS'+variable,'o'+variable];

            each(variables, function (i, val) {
                ref[val] = value;
            });
        },
        addVendorEvents = function (el, func, event) {
            var events = [event.toLowerCase(),'webkit'+event,'MS'+event,'o'+event];
            var element = el;

            each(events, function (i, val) {
                el.addEventListener(val, func, false);
            });
        },
        onAnimationEnd = function (el, func) {
            addVendorEvents(el, func, 'AnimationEnd');
        },
        prepend = function (parent, child) {
            if(parent.firstChild) {
                parent.insertBefore(child, parent.firstChild);
            } else {
                parent.appendChild(child);
            }
        };

    var id = timeline.id,
        optionsDefault = {
            'skin': 'snapgram',
            'avatars': true,
            'stories': [],
            'expiresIn': 24,
            'backButton': true,
            'backNative': false,
            'autoFullScreen': false,
            'saveRead': function (storyId, storyItemId, status) {

            },
        },
        option = function (name, prop) {
            if(prop) {
                if(options[name]) {
                    return options[name][prop] || optionsDefault[name][prop];
                } else {
                    return optionsDefault[name][prop];
                }
            } else {
                return options[name] || optionsDefault[name];
            }
        };

    if(!window['ZuckModal']) {
        window['ZuckModal'] = function () {
            var opened = false;
            var modalContainer = g('#zuck-modal');

            if(!modalContainer) {
                modalContainer = d.createElement('div');
                modalContainer.id = 'zuck-modal';
                modalContainer.innerHTML = '

';
                modalContainer.style.display = 'none';
                onAnimationEnd(modalContainer, function () {
                    //zuck.nextItem();
                });

                d.body.appendChild(modalContainer);
            }

            var modalContent = q('#zuck-modal-content');
            var createStoryViewer = function(storyData, currentItem, className){
                if(!storyData){
                    return false;
                }

                var htmlItems = '',
                    pointerItems = '',
                    storyId = g(storyData, 'id'),
                    slides = d.createElement('div');

                slides.className = 'slides';
                each(g(storyData, 'items'), function (i, item) {

                    pointerItems += '';
                    htmlItems += '
'+
                                    ((g(item, 'type')==='video')?'<video src="'+g(item, 'src')+'" '+g(item, 'type')+'>':'')+
                                '
';
                });

                slides.innerHTML = htmlItems;

                var storyViewer = d.createElement('div');
                storyViewer.className = 'story-viewer '+className+' '+((className!='viewing')?'stopped':'');
                storyViewer.setAttribute('data-story-id', storyId);

                var html = '
'+
                                '
'+
                                    ''+
                                    '
'+
                                        ''+g(storyData, 'name')+''+
                                        '1 min ago'+
                                    '
'+
                                '
'+
                                '
'+
                                    '1 min ago'+
                                    '
×
'+
                                '
'+
                           '
'+
                           '

'+pointerItems+'

';
                storyViewer.innerHTML = html;

                var touchStart = function(e){
                    e.preventDefault();

                    storyViewer.timer = setTimeout(function(){
                        storyViewer.classList.add('fingerDown');
                        if(storyViewer.classList.contains('fingerDown')){
                            storyViewer.classList.add('paused');

                            var video = zuck.internalData['currentVideoElement'];
                            if(video){
                               try {
                                   video.pause();
                               } catch (e){

                               }
                            }
                        }
                    }, 200);
                };

                var touchEnd = function(e){
                    e.preventDefault();

                    if(storyViewer.timer){
                        clearInterval(storyViewer.timer);
                    }

                    if(storyViewer.classList.contains('fingerDown')){
                        storyViewer.classList.remove('fingerDown');
                    } else {
                        zuck.nextItem();
                    }

                    storyViewer.classList.remove('paused');

                    var video = zuck.internalData['currentVideoElement'];
                    if(video){
                       try {
                           video.play();
                       } catch (e){

                       }
                    }
                };

                slides.addEventListener('touchstart', touchStart);
                slides.addEventListener('touchend', touchEnd);

                slides.addEventListener('mousedown', touchStart);
                slides.addEventListener('mouseup', touchEnd);

                storyViewer.appendChild(slides);

                each(storyViewer.querySelectorAll('.slides-pointers [data-index] > b'), function (i, el) {
                    console.log(el);
                    onAnimationEnd(el, function () {
                        zuck.nextItem();
                    });
                });

                modalContent.appendChild(storyViewer);
            };

            return {
                'show': function (storyId, page) {
                    var storyData = zuck.data[storyId];
                    var currentItem = storyData.currentItem || 0;

                    zuck.internalData['currentStory'] = storyId;
                    zuck.internalData['currentStoryItem'] = currentItem;

                    if(option('backNative')) {
                        location.hash = '#!'+id;
                    }

                    if(currentItem > 0){
                        var previousItemData = getStoryMorningGlory('previous');
                        createStoryViewer(previousItemData, currentItem, 'previous');
                    }

                    createStoryViewer(storyData, currentItem, 'viewing');

                    if(currentItem<=storyData.items.length){
                        var nextItemData = getStoryMorningGlory('next');
                        createStoryViewer(nextItemData, currentItem, 'next');
                    }

                    modalContainer.style.display = 'block';
                },

                'close': function () {
                    modalContainer.style.display = 'none';
                }
            };
        };
    }

    var modal = new ZuckModal();
    var parseItems = function (story) {
            var storyId = story.getAttribute('data-id');
            var storyItems = d.querySelectorAll('#'+id+' [data-id="'+storyId+'"] .items > li');
            var items = [];

            each(storyItems, function (i, el) {
                var a = el.firstElementChild;
                var img = a.firstElementChild;

                items.push({
                    'src': a.getAttribute('href'),
                    'length': a.getAttribute('data-length'),
                    'type': a.getAttribute('data-type'),
                    'time': a.getAttribute('data-time'),
                    'link': a.getAttribute('data-link'),
                    'preview': img.getAttribute('src')
                });
            });

            console.log('add data', storyItems, items);

            zuck.data[storyId].items = items;
        },

        parseStory = function (story) {
            var storyId = story.getAttribute('data-id');

            try {
                zuck.data[storyId] = {
                    'id': storyId, //story id
                    'photo': story.getAttribute('data-photo'), //story photo (or user photo)
                    'name': story.firstElementChild.lastElementChild.innerText,
                    'link': story.firstElementChild.getAttribute('href'),
                    'lastUpdated': story.getAttribute('data-last-updated'),
                    'items': []
                };
            } catch (e) {
                zuck.data[storyId] = {
                    'items': []
                };
            }

            story.onclick = function (e) {
                e.preventDefault();

                modal.show(storyId);
            };
        },

        getStoryMorningGlory = function(what) { //my wife told me to stop singing Wonderwall. I SAID MAYBE.
            var currentStory = zuck.internalData['currentStory']; // _\|/_
            var whatEl = what+'ElementSibling'; //this was proposital

            if(currentStory){
               var foundStory = q('#'+id+' [data-id="'+currentStory+'"]')[whatEl];

               if(foundStory){
                    var storyId = foundStory.getAttribute('data-id');

                    return zuck.data[storyId] || false;
               }
            }

            return false;
        };

    zuck.data = {};
    zuck.internalData = {};

    zuck.add = function (data, append) {
        var storyId = g(data, 'id');
        var story = q('#'+id+' [data-id="'+storyId+'"]');
        var html = '';
        var items = g(data, 'items');

        zuck.data[storyId] = {};

        if(!story) {
            story = d.createElement('div');
            story.setAttribute('data-id', storyId);
            story.setAttribute('data-photo', g(data, 'photo'));
            story.setAttribute('data-last-updated', g(data, 'lastUpdated'));

            story.className = 'story';

            html = ''+
                        ''+
                        ''+g(data, 'name')+''+
                    ''+
                    '

';
            story.innerHTML = html;

            parseStory(story);
            if(append) {
                timeline.appendChild(story);
            } else {
                prepend(timeline, story);
            }

            each(items, function (i, item) {
                zuck.addItem(storyId, item, append);
            });
        }
    };

    zuck.next = function () {
        var next = getStoryMorningGlory('next');

        if(false){
            modal.close();
        }
    };

    zuck.addItem = function (storyId, data, append) {
        var story = q('#'+id+' > [data-id="'+storyId+'"]');
        var li = d.createElement('li');

        li.className = g(data, 'seem')?'seem':'';
        li.setAttribute('data-id', g(data, 'id'));

        li.innerHTML = ''+
                            ''+
                        '';

        var el = story.querySelectorAll('.items')[0];
        if(append) {
            el.appendChild(li);
        } else {
            prepend(el, li);
        }

        parseItems(story);
    };

    zuck.removeItem = function (storyId, itemId) {
        var item = q('#'+id+' > [data-id="'+storyId+'"] [data-id="'+itemId+'"]');

        timeline.parentNode.removeChild(item);
    };

    zuck.nextItem = function () {
        var currentStory = zuck.internalData['currentStory'];
        var currentItem = zuck.internalData['currentStoryItem'];

        var storyViewer = q('#zuck-modal .story-viewer[data-story-id="'+currentStory+'"]');

        var currentItemElements = storyViewer.querySelectorAll('[data-index="'+currentItem+'"]');
        var currentPointer = currentItemElements[0];
        var currentItemElement = currentItemElements[1];

        var nextItem = currentItem + 1;
        var nextItemElements = storyViewer.querySelectorAll('[data-index="'+nextItem+'"]');
        var nextPointer = nextItemElements[0];
        var nextItemElement = nextItemElements[1];

        if(storyViewer&&nextPointer&&nextItemElement){
            currentPointer.classList.remove('active');
            currentPointer.classList.add('seem');
            currentItemElement.classList.remove('active');
            currentItemElement.classList.add('seem');

            nextPointer.classList.remove('seem');
            nextPointer.classList.add('active');
            nextItemElement.classList.remove('seem');
            nextItemElement.classList.add('active');

            zuck.internalData['currentStoryItem']++;
            if(nextItemElement.getAttribute('data-type')=='video'){
                var video = nextItemElement.getElementsByTagName('video')[0];
                if(video.duration){
                    setVendorVariable(nextPointer.getElementsByTagName('b')[0].style, 'AnimationDuration', video.duration+'s');
                }

                zuck.internalData['currentVideoElement'] = video;

                video.play();
            } else {
                zuck.internalData['currentVideoElement'] = false;
            }
        } else if(storyViewer){
            zuck.next();
        }
    };

    zuck.reload = function (data) {

    };

    var init = function () {
        console.log('init', option('stories'));

        if(q('#'+id+' .story')) {
            each(timeline.querySelectorAll('.story'), function (i, story) {
                parseStory(story, true);
            });
        }

        each(option('stories'), function (i, item) {
            zuck.add(item, true);
        });

        var avatars = (option('avatars'))?'user-icon':'story-preview';
        timeline.className = 'stories '+avatars+' '+option('skin');

        return zuck;
    };

    return init();
};
<commit_msg>Touch slider<commit_after>window['ZuckitaDaGalera'] = window['Zuck'] = function (timeline, options) {
    'use strict';

    var d = document, zuck = this;
    if(typeof timeline == 'string') {
        timeline = d.getElementById(timeline);
    }

    var q = function (query) {
            return d.querySelectorAll(query)[0];
        },
        g = function (array, what) {
            if(array) {
                return array[what] || '';
            } else {
                return '';
            }
        },
        each = function (arr, func) {
            if(arr) {
                var total = arr.length;

                for (var i=0; i<total; i++) {
                    func(i, arr[i]);
                }
            }
        },
        setVendorVariable = function(ref, variable, value){
            var variables = [variable.toLowerCase(),'webkit'+variable,'MS'+variable,'o'+variable];

            each(variables, function (i, val) {
                ref[val] = value;
            });
        },
        addVendorEvents = function (el, func, event) {
            var events = [event.toLowerCase(),'webkit'+event,'MS'+event,'o'+event];
            var element = el;

            each(events, function (i, val) {
                el.addEventListener(val, func, false);
            });
        },
        onAnimationEnd = function (el, func) {
            addVendorEvents(el, func, 'AnimationEnd');
        },
        prepend = function (parent, child) {
            if(parent.firstChild) {
                parent.insertBefore(child, parent.firstChild);
            } else {
                parent.appendChild(child);
            }
        },
        getElIndex = function(el) {
            for (var i = 1; el = el.previousElementSibling; i++) {
                return i;
            }

            return 0;
        };

    var id = timeline.id,
        optionsDefault = {
            'skin': 'snapgram',
            'avatars': true,
            'stories': [],
            'expiresIn': 24,
            'backButton': true,
            'backNative': false,
            'autoFullScreen': false,
            'saveRead': function (storyId, storyItemId, status) {

            },
        },
        option = function (name, prop) {
            if(prop) {
                if(options[name]) {
                    return options[name][prop] || optionsDefault[name][prop];
                } else {
                    return optionsDefault[name][prop];
                }
            } else {
                return options[name] || optionsDefault[name];
            }
        };

    if(!window['ZuckModal']) {
        window['ZuckModal'] = function () {
            var opened = false;
            var modalContainer = g('#zuck-modal');

            if(!modalContainer) {
                modalContainer = d.createElement('div');
                modalContainer.id = 'zuck-modal';
                modalContainer.innerHTML = '

';
                modalContainer.style.display = 'none';
                onAnimationEnd(modalContainer, function () {
                    //zuck.nextItem();
                });

                d.body.appendChild(modalContainer);
            }

            var modalContent = q('#zuck-modal-content');
            var createStoryViewer = function(storyData, className){
                if(!storyData){
                    return false;
                }

                var htmlItems = '',
                    pointerItems = '',
                    storyId = g(storyData, 'id'),
                    slides = d.createElement('div'),
                    currentItem = zuck.internalData['currentStoryItem'];

                slides.className = 'slides';
                each(g(storyData, 'items'), function (i, item) {

                    pointerItems += '';
                    htmlItems += '
'+
                                    ((g(item, 'type')==='video')?'<video src="'+g(item, 'src')+'" '+g(item, 'type')+'>':'')+
                                '
';
                });

                slides.innerHTML = htmlItems;

                var storyViewer = d.createElement('div');
                storyViewer.className = 'story-viewer '+className+' '+((className!='viewing')?'stopped':'');
                storyViewer.setAttribute('data-story-id', storyId);

                var html = '
'+
                                '
'+
                                    ''+
                                    '
'+
                                        ''+g(storyData, 'name')+''+
                                        '1 min ago'+
                                    '
'+
                                '
'+
                                '
'+
                                    '1 min ago'+
                                    '
×
'+
                                '
'+
                           '
'+
                           '

'+pointerItems+'

';
                storyViewer.innerHTML = html;

                var touchStart = function(e){
                    e.preventDefault();

                    slides.touchStartX =  e.touches[0].pageX;
                    slides.slideWidth = q('#zuck-modal .story-viewer').offsetWidth;
                    slides.index = getElIndex(q('#zuck-modal .story-viewer.viewing'));
                    slides.previous  = q('#zuck-modal .story-viewer.previous');
                    slides.viewing = q('#zuck-modal .story-viewer.viewing');
                    slides.next = q('#zuck-modal .story-viewer.next');

                    storyViewer.timer = setTimeout(function(){
                        storyViewer.classList.add('fingerDown');
                        if(storyViewer.classList.contains('fingerDown')){
                            storyViewer.classList.add('paused');

                            var video = zuck.internalData['currentVideoElement'];
                            if(video){
                               try {
                                   video.pause();
                               } catch (e){

                               }
                            }
                        }
                    }, 200);
                };

                var touchEnd = function(e){
                    e.preventDefault();

                    if(storyViewer.timer){
                        clearInterval(storyViewer.timer);
                    }

                    if(storyViewer.classList.contains('fingerDown')){
                        storyViewer.classList.remove('fingerDown');
                    } else {
                        zuck.nextItem();
                    }

                    storyViewer.classList.remove('paused');

                    var video = zuck.internalData['currentVideoElement'];
                    if(video){
                       try {
                           video.play();
                       } catch (e){

                       }
                    }

                    if(slides.moveX){
                        var absMove = Math.abs(slides.index*slides.slideWidth - slides.moveX);
                        if (absMove > slides.slideWidth/2) {
                            if (slides.moveX > slides.index*slides.slideWidth && slides.index < 2) {
                                slides.index++;
                            } else if (slides.moveX < slides.index*slides.slideWidth && slides.index > 0) {
                                slides.index--;
                            }
                        }

                        var previousIndex = (slides.index * slides.slideWidth);
                        var viewingIndex = ((slides.index*slides.slideWidth) - slides.slideWidth);
                        var nextIndex = ((slides.index*slides.slideWidth) - (slides.slideWidth * 2));

                        if(slides.previous){
                            slides.previous.style.transform = 'translate3d(' + (slides.index * slides.slideWidth)  + 'px,0,0)';
                        }

                        slides.viewing.style.transform = 'translate3d(' + ((slides.index*slides.slideWidth) - slides.slideWidth) + 'px,0,0)';

                        if(slides.next){
                            slides.next.style.transform = 'translate3d(' + ((slides.index*slides.slideWidth) - (slides.slideWidth * 2)) + 'px,0,0)';
                        }

                        if(previousIndex==0){
                           console.log('previous');
                        } else if (nextIndex==0){
                           console.log('next');
                        }
                    }
                };

                var touchMove = function(e){
                    slides.touchMoveX =  e.touches[0].pageX;
                    slides.moveX = slides.slideWidth + (slides.touchStartX - slides.touchMoveX);

                    if(slides.previous){
                        slides.previous.style.transform = 'translate3d(' + ((slides.moveX * -1)) + 'px,0,0)';
                    }

                    slides.viewing.style.transform = 'translate3d(' + ((slides.moveX * -1) + slides.slideWidth) + 'px,0,0)';

                    if(slides.next){
                        slides.next.style.transform = 'translate3d(' + ((slides.moveX * -1) + (slides.slideWidth * 2)) + 'px,0,0)';
                    }
                };

                slides.addEventListener('touchstart', touchStart);
                slides.addEventListener('touchmove', touchMove);
                slides.addEventListener('touchend', touchEnd);

                slides.addEventListener('mousedown', touchStart);
                slides.addEventListener('mouseup', touchEnd);

                storyViewer.appendChild(slides);

                each(storyViewer.querySelectorAll('.slides-pointers [data-index] > b'), function (i, el) {
                    console.log(el);
                    onAnimationEnd(el, function () {
                        zuck.nextItem();
                    });
                });

                modalContent.appendChild(storyViewer);
            };

            return {
                'show': function (storyId, page) {
                    var storyData = zuck.data[storyId];
                    var currentItem = storyData['currentItem'] || 0;

                    zuck.internalData['currentStory'] = storyId;
                    zuck.internalData['currentStoryItem'] = currentItem;

                    if(option('backNative')) {
                        location.hash = '#!'+id;
                    }

                    var previousItemData = getStoryMorningGlory('previous');
                    if(previousItemData){
                       createStoryViewer(previousItemData, 'previous');
                    }

                    createStoryViewer(storyData, 'viewing');

                    var nextItemData = getStoryMorningGlory('next');
                    if(nextItemData){
                        createStoryViewer(nextItemData, 'next');
                    }

                    modalContainer.style.display = 'block';
                },

                'close': function () {
                    modalContainer.style.display = 'none';
                }
            };
        };
    }

    var modal = new ZuckModal();
    var parseItems = function (story) {
            var storyId = story.getAttribute('data-id');
            var storyItems = d.querySelectorAll('#'+id+' [data-id="'+storyId+'"] .items > li');
            var items = [];

            each(storyItems, function (i, el) {
                var a = el.firstElementChild;
                var img = a.firstElementChild;

                items.push({
                    'src': a.getAttribute('href'),
                    'length': a.getAttribute('data-length'),
                    'type': a.getAttribute('data-type'),
                    'time': a.getAttribute('data-time'),
                    'link': a.getAttribute('data-link'),
                    'preview': img.getAttribute('src')
                });
            });

            console.log('add data', storyItems, items);

            zuck.data[storyId].items = items;
        },

        parseStory = function (story) {
            var storyId = story.getAttribute('data-id');

            try {
                zuck.data[storyId] = {
                    'id': storyId, //story id
                    'photo': story.getAttribute('data-photo'), //story photo (or user photo)
                    'name': story.firstElementChild.lastElementChild.innerText,
                    'link': story.firstElementChild.getAttribute('href'),
                    'lastUpdated': story.getAttribute('data-last-updated'),
                    'items': []
                };
            } catch (e) {
                zuck.data[storyId] = {
                    'items': []
                };
            }

            story.onclick = function (e) {
                e.preventDefault();

                modal.show(storyId);
            };
        },

        getStoryMorningGlory = function(what) { //my wife told me to stop singing Wonderwall. I SAID MAYBE.
            var currentStory = zuck.internalData['currentStory']; // _\|/_
            var whatEl = what+'ElementSibling'; //this was proposital

            if(currentStory){
               var foundStory = q('#'+id+' [data-id="'+currentStory+'"]')[whatEl];

               if(foundStory){
                    var storyId = foundStory.getAttribute('data-id');

                    return zuck.data[storyId] || false;
               }
            }

            return false;
        };

    zuck.data = {};
    zuck.internalData = {};

    zuck.add = function (data, append) {
        var storyId = g(data, 'id');
        var story = q('#'+id+' [data-id="'+storyId+'"]');
        var html = '';
        var items = g(data, 'items');

        zuck.data[storyId] = {};

        if(!story) {
            story = d.createElement('div');
            story.setAttribute('data-id', storyId);
            story.setAttribute('data-photo', g(data, 'photo'));
            story.setAttribute('data-last-updated', g(data, 'lastUpdated'));

            story.className = 'story';

            html = ''+
                        ''+
                        ''+g(data, 'name')+''+
                    ''+
                    '

';
            story.innerHTML = html;

            parseStory(story);
            if(append) {
                timeline.appendChild(story);
            } else {
                prepend(timeline, story);
            }

            each(items, function (i, item) {
                zuck.addItem(storyId, item, append);
            });
        }
    };

    zuck.next = function () {
        var next = getStoryMorningGlory('next');

        if(false){
            modal.close();
        }
    };

    zuck.addItem = function (storyId, data, append) {
        var story = q('#'+id+' > [data-id="'+storyId+'"]');
        var li = d.createElement('li');

        li.className = g(data, 'seem')?'seem':'';
        li.setAttribute('data-id', g(data, 'id'));

        li.innerHTML = ''+
                            ''+
                        '';

        var el = story.querySelectorAll('.items')[0];
        if(append) {
            el.appendChild(li);
        } else {
            prepend(el, li);
        }

        parseItems(story);
    };

    zuck.removeItem = function (storyId, itemId) {
        var item = q('#'+id+' > [data-id="'+storyId+'"] [data-id="'+itemId+'"]');

        timeline.parentNode.removeChild(item);
    };

    zuck.nextItem = function () {
        var currentStory = zuck.internalData['currentStory'];
        var currentItem = zuck.internalData['currentStoryItem'];

        var storyViewer = q('#zuck-modal .story-viewer[data-story-id="'+currentStory+'"]');

        var currentItemElements = storyViewer.querySelectorAll('[data-index="'+currentItem+'"]');
        var currentPointer = currentItemElements[0];
        var currentItemElement = currentItemElements[1];

        var nextItem = currentItem + 1;
        var nextItemElements = storyViewer.querySelectorAll('[data-index="'+nextItem+'"]');
        var nextPointer = nextItemElements[0];
        var nextItemElement = nextItemElements[1];

        if(storyViewer&&nextPointer&&nextItemElement){
            currentPointer.classList.remove('active');
            currentPointer.classList.add('seem');
            currentItemElement.classList.remove('active');
            currentItemElement.classList.add('seem');

            nextPointer.classList.remove('seem');
            nextPointer.classList.add('active');
            //nextItemElement.classList.remove('stopped');
            nextItemElement.classList.remove('seem');
            nextItemElement.classList.add('active');

            zuck.internalData['currentStoryItem']++;
            if(nextItemElement.getAttribute('data-type')=='video'){
                var video = nextItemElement.getElementsByTagName('video')[0];
                if(video.duration){
                    setVendorVariable(nextPointer.getElementsByTagName('b')[0].style, 'AnimationDuration', video.duration+'s');
                }

                zuck.internalData['currentVideoElement'] = video;

                video.play();
            } else {
                zuck.internalData['currentVideoElement'] = false;
            }
        } else if(storyViewer){
            zuck.next();
        }
    };

    zuck.reload = function (data) {

    };

    var init = function () {
        console.log('init', option('stories'));

        if(q('#'+id+' .story')) {
            each(timeline.querySelectorAll('.story'), function (i, story) {
                parseStory(story, true);
            });
        }

        each(option('stories'), function (i, item) {
            zuck.add(item, true);
        });

        var avatars = (option('avatars'))?'user-icon':'story-preview';
        timeline.className = 'stories '+avatars+' '+option('skin');

        return zuck;
    };

    return init();
};
<|endoftext|>


<commit_before>var fs = require('fs')
var unzip = require("unzip")
var path = require('path');
var FileHound = require("fileHound")

var root = process.cwd() + '\\'

var searchDirectory = root
var outPutDirectory = root + '\\';

var zips = getZips(searchDirectory);
extract(zips);
var files = FileHound.create().paths(outPutDirectory).ext('.dll').find()

files.then(getSameNamedDlls);

var duplicates = [];

function getSameNamedDlls(files) {
    var dlls = [];

    files.forEach(function (file) {
        var dll = { path: file, name: path.basename(file), properties: fs.statSync(file) }
        dlls.push(dll)
    })

    var actions = dlls.map(getVersion);
    var results = Promise.all(actions); // pass array of promises
    results.then(function(dlls){

        dlls.forEach(function (dll) {
           for (var i = 0; i < dlls.length; i++){
               if (duplicates.find(x => x.path === dll.path) != null) {continue;} //Dll already in dups
               if (dll.name !== dlls[i].name){continue;} // skip if not named the same
               if (dll.path === dlls[i].path){continue;} //skip if same dll
               if (dll.version === dlls[i].version){continue;} //skip if same dll
               duplicates.push(dll)
           }
    })
    duplicates.forEach(d => console.log(d.path + ' | ' + d.version))
});}

function getVersion(dll){
    const shell = require('node-powershell');
    var ps = new shell({
    executionPolicy: 'Bypass',
           noProfile: true,
           debugMsg: false
    });

    ps.addCommand('[System.Diagnostics.FileVersionInfo]::GetVersionInfo("'+ dll.path + '").ProductVersion')
    return ps.invoke()
        .then(version => {
        dll.version = version;
        ps.dispose()
        return new Promise(resolve => resolve(dll))
        })
        .catch(err => {
        console.log(err);
         ps.dispose()
    })
}

function getZips(directory) {
    var zips = [];
    var files = fs.readdirSync(directory);
    for (var i in files) {
        if (path.extname(files[i]) === ".zip") {
            zips.push(files[i])
        }
    }
    return zips;
}

function extract(zip) {
    zips.forEach(function (zip) {
        var combined = searchDirectory + zip;
        var fileNameNoExt = zip.replace('.zip', "");
        fs.createReadStream(combined).pipe(unzip.Extract({ path: outPutDirectory + fileNameNoExt }));
    }, this);
}

<commit_msg>forced unzipping sync proc<commit_after>var fs = require('fs')
var unzip = require("unzip")
var path = require('path');
var FileHound = require("fileHound")

var root = process.cwd() + '\\'

var searchDirectory = "C:\\temp\\Dep 3089\\"
var outPutDirectory = "C:\\temp\\Dep 3089\\"

var zips = getZips(searchDirectory);

var unzippedCount = 0;
extract(0);

function checkVers() {
    var files = FileHound.create().paths(outPutDirectory).ext('.dll').find()
    files.then(getSameNamedDlls);
}

var duplicates = [];

function getSameNamedDlls(files) {
    var dlls = [];

    files.forEach(function (file) {
        var dll = { path: file, name: path.basename(file), properties: fs.statSync(file) }
        dlls.push(dll)
    })

dlls.sort(function(a, b) {
    var textA = a.name
    var textB = b.name
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

    var actions = dlls.map(getVersion);
    var results = Promise.all(actions); // pass array of promises
    results.then(function (dlls) {

        dlls.forEach(function (dll) {
            for (var i = 0; i < dlls.length; i++) {
                if (duplicates.find(x => x.path === dll.path) != null) { continue; } //Dll already in dups
                if (dll.name !== dlls[i].name) { continue; } // skip if not named the same
                if (dll.path === dlls[i].path) { continue; } //skip if same dll
                if (dll.version === dlls[i].version) { continue; } //skip if same dll
                duplicates.push(dll)
            }
        })
        duplicates.forEach(d => console.log(d.path + ' | ' + d.version))
    });
}

function getVersion(dll) {
    const shell = require('node-powershell');
    var ps = new shell({
        executionPolicy: 'Bypass',
        noProfile: true,
        debugMsg: false
    });

    ps.addCommand('[System.Diagnostics.FileVersionInfo]::GetVersionInfo("' + dll.path + '").ProductVersion')
    return ps.invoke()
        .then(version => {
            dll.version = version;
            ps.dispose()
            return new Promise(resolve => resolve(dll))
        })
        .catch(err => {
            console.log(err);
            ps.dispose()
        })
}

function getZips(directory) {
    var zips = [];
    var files = fs.readdirSync(directory);
    for (var i in files) {
        if (path.extname(files[i]) === ".zip") {
            zips.push(files[i])
        }
    }
    return zips;
}

function extract() {
    var zip = zips[unzippedCount]
    var combined = searchDirectory + zip;
    var fileNameNoExt = zip.replace('.zip', "");
    fs.createReadStream(combined).pipe(unzip.Extract({ path: outPutDirectory + fileNameNoExt })).on('close', function (e) {
        CheckNextUnzip();
    })
}

function CheckNextUnzip() {
    unzippedCount++;
    if (unzippedCount >= zips.length) {
        checkVers()
    } else {
        extract()
    }
}

<|endoftext|>


<commit_before>const fetch = require('node-fetch');
const { URL } = require('url');
const { Parser } = require('xml2js');
const parser = new Parser();

const sites = require('./sites');

class Kaori {
	constructor(customSites = {}) {
		this.sites = Object.assign(customSites, sites);
	}

	_resolveSite(resolvable) {
		if (typeof resolvable !== 'string') return false;
		resolvable = resolvable.toLowerCase();
		for (const site of Object.keys(this.sites)) {
			if (site === resolvable || this.sites[site].aliases.includes(resolvable)) return site;
		}
		return false;
	}

	search(site, { tags = [], limit = 1, random = false } = {}) {
		return new Promise((resolve, reject) => {
			if (!this._resolveSite(site)) return reject(new Error('This site is not supported.'));
			if (!(tags instanceof Array)) return reject(new Error('Tags have to be an Array.'));
			if (typeof limit !== 'number' && !Number.isNaN(limit)) return reject(new Error('Limit has to be a number.'));

			site = this._resolveSite(site);
			limit = parseInt(limit);
			return resolve(this._searchPosts(site, { tags, limit, random }));
		});
	}

	_searchPosts(site, { tags, limit, random }) {
		return new Promise((resolve, reject) => {
			const endpoint = this.sites[site].endpoint;
			const options = { headers: { 'User-Agent': 'Kaori, an npm module for boorus.' } };
			if (!random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else if (random && sites[site].random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}+order:random&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=100`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(parsed => this._shuffle(parsed))
					.then(shuffled => resolve(this._commonify(shuffled)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			}
		});
	}

	_commonify(images) {
		return new Promise((resolve, reject) => {
			if (typeof images[0] === 'undefined') return reject(new Error('Commonify didn\'t recieve any images.'));
			return this._xml2json(images)
				.then(res => this._common(res))
				.then(image => resolve(image))
				.catch(error => reject(new Error(error)));
		});
	}

	_xml2json(images) {
		return new Promise((resolve, reject) => {
			if (typeof images !== 'object') {
				return parser.parseString(images, (err, res) => {
					if (err) return reject(new Error(err));
					if (typeof res.posts.post === 'undefined') return resolve([]);
					else return resolve(res.posts.post.map(val => val.$));
				});
			} else {
				return resolve(images);
			}
		});
	}

	_common(images) {
		return new Promise(resolve => {
			if (images === []) return resolve([]);
			for (const image of Object.keys(images)) {
				const key = images[image];
				key.common = {
					fileURL: key.file_url.startsWith('/data')
						? `https://danbooru.donmai.us${key.file_url}`
						: !key.file_url.startsWith('http')
							? `https:${key.file_url}`
							: new URL(key.file_url).href,
					id: key.id.toString(),
					tags: typeof key.tags !== 'undefined'
						? key.tags.split(' ').filter(val => val !== '')
						: key.tag_string.split(' ').filter(val => val !== ''),
					score: parseInt(key.score),
					source: key.source,
					rating: key.rating
				};
			}
			return resolve(images);
		});
	}

	_shuffle(array) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			const temp = array[i];
			array[i] = array[j];
			array[j] = temp;
		}
		return array;
	}
}

module.exports = Kaori;
<commit_msg>Update useragent<commit_after>const fetch = require('node-fetch');
const { URL } = require('url');
const { Parser } = require('xml2js');
const parser = new Parser();

const sites = require('./sites');
const { version } = require('./package');

class Kaori {
	constructor(customSites = {}) {
		this.sites = Object.assign(customSites, sites);
	}

	_resolveSite(resolvable) {
		if (typeof resolvable !== 'string') return false;
		resolvable = resolvable.toLowerCase();
		for (const site of Object.keys(this.sites)) {
			if (site === resolvable || this.sites[site].aliases.includes(resolvable)) return site;
		}
		return false;
	}

	search(site, { tags = [], limit = 1, random = false } = {}) {
		return new Promise((resolve, reject) => {
			if (!this._resolveSite(site)) return reject(new Error('This site is not supported.'));
			if (!(tags instanceof Array)) return reject(new Error('Tags have to be an Array.'));
			if (typeof limit !== 'number' && !Number.isNaN(limit)) return reject(new Error('Limit has to be a number.'));

			site = this._resolveSite(site);
			limit = parseInt(limit);
			return resolve(this._searchPosts(site, { tags, limit, random }));
		});
	}

	_searchPosts(site, { tags, limit, random }) {
		return new Promise((resolve, reject) => {
			const endpoint = this.sites[site].endpoint;
			const userAgent = `Kaori, a npm module for boorus. v${version} (https://github.com/iCrawl/Kaori/)`;
			const options = { headers: { 'User-Agent': userAgent } };
			if (!random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else if (random && sites[site].random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}+order:random&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=100`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(parsed => this._shuffle(parsed))
					.then(shuffled => resolve(this._commonify(shuffled)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			}
		});
	}

	_commonify(images) {
		return new Promise((resolve, reject) => {
			if (typeof images[0] === 'undefined') return reject(new Error('Commonify didn\'t recieve any images.'));
			return this._xml2json(images)
				.then(res => this._common(res))
				.then(image => resolve(image))
				.catch(error => reject(new Error(error)));
		});
	}

	_xml2json(images) {
		return new Promise((resolve, reject) => {
			if (typeof images !== 'object') {
				return parser.parseString(images, (err, res) => {
					if (err) return reject(new Error(err));
					if (typeof res.posts.post === 'undefined') return resolve([]);
					else return resolve(res.posts.post.map(val => val.$));
				});
			} else {
				return resolve(images);
			}
		});
	}

	_common(images) {
		return new Promise(resolve => {
			if (images === []) return resolve([]);
			for (const image of Object.keys(images)) {
				const key = images[image];
				key.common = {
					fileURL: key.file_url.startsWith('/data')
						? `https://danbooru.donmai.us${key.file_url}`
						: !key.file_url.startsWith('http')
							? `https:${key.file_url}`
							: new URL(key.file_url).href,
					id: key.id.toString(),
					tags: typeof key.tags !== 'undefined'
						? key.tags.split(' ').filter(val => val !== '')
						: key.tag_string.split(' ').filter(val => val !== ''),
					score: parseInt(key.score),
					source: key.source,
					rating: key.rating
				};
			}
			return resolve(images);
		});
	}

	_shuffle(array) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			const temp = array[i];
			array[i] = array[j];
			array[j] = temp;
		}
		return array;
	}
}

module.exports = Kaori;
<|endoftext|>


<commit_before>var compose = require('ksf/utils/compose');
var Elmt = require('./Element');
var _ContentDelegate = require('./_ContentDelegate');

module.exports = compose(_ContentDelegate, function() {
	this._content = new Elmt().style({
		whiteSpace: 'nowrap',
		overflow: 'hidden',
		textOverflow: 'ellipsis',
	});
	this._vAlign = 'middle';
}, {
	value: function(value) {
		this._content.prop('textContent', (typeof value === 'string' ? value : ''));
		return this;
	},
	hAlign: function(hAlign) {
		this._content.styleProp('textAlign', hAlign);
		return this;
	},
	vAlign: function(vAlign) {
		this._vAlign = vAlign;
		this._applyVAlign();
		return this;
	},
	_applyVAlign: function() {
		this._content.styleProp('lineHeight', null);
		this._content.styleProp('padding-top', null);
		if (this._vAlign === 'bottom') {
			this._content.styleProp('padding-top', 'calc(' + this._content.height() + 'px - 1em)');
		} else if (this._vAlign === 'middle') {
			this._content.styleProp('lineHeight', this._content.height() + 'px');
		}
	},
	height: function(height) {
		if (arguments.length) {
			this._content.height(height);
			this._applyVAlign();
			return this;
		} else {
			return this._content.height();
		}
	},
	color: function(color) {
		this._content.styleProp('color', color);
		return this;
	},
	font: function(font) {
		if (typeof font === 'string') {
			this._content.styleProp('font', font);
		} else {
			font.family && this._content.styleProp('fontFamily', font.family);
			this._content.style({
				fontWeight: font.weight,
				fontSize: font.size,
				fontStyle: font.style,
			});
		}
		return this;
	}
});
<commit_msg>Improved Label bottom-positioning<commit_after>var compose = require('ksf/utils/compose');
var Elmt = require('./Element');
var _ContentDelegate = require('./_ContentDelegate');

module.exports = compose(_ContentDelegate, function() {
	this._content = new Elmt().style({
		whiteSpace: 'nowrap',
		overflow: 'hidden',
		textOverflow: 'ellipsis',
	});
	this._vAlign = 'middle';
}, {
	value: function(value) {
		this._content.prop('textContent', (typeof value === 'string' ? value : ''));
		return this;
	},
	hAlign: function(hAlign) {
		this._content.styleProp('textAlign', hAlign);
		return this;
	},
	vAlign: function(vAlign) {
		this._vAlign = vAlign;
		this._applyVAlign();
		return this;
	},
	_applyVAlign: function() {
		this._content.styleProp('lineHeight', null);
		this._content.styleProp('padding-top', null);
		if (this._vAlign === 'bottom') {
			// no clean way to bottom-align a single-line text without using an extra container node
			// best compromise I could find is the following, adding padding-top with a line-height of 1.1 (so that characters "legs", like q, p, etc. are not cut for most fonts)
			this._content.styleProp('padding-top', 'calc(' + this._content.height() + 'px - 1.1em)');
			this._content.styleProp('lineHeight', '1.1');
		} else if (this._vAlign === 'middle') {
			this._content.styleProp('lineHeight', this._content.height() + 'px');
		}
	},
	height: function(height) {
		if (arguments.length) {
			this._content.height(height);
			this._applyVAlign();
			return this;
		} else {
			return this._content.height();
		}
	},
	color: function(color) {
		this._content.styleProp('color', color);
		return this;
	},
	font: function(font) {
		if (typeof font === 'string') {
			this._content.styleProp('font', font);
		} else {
			font.family && this._content.styleProp('fontFamily', font.family);
			this._content.style({
				fontWeight: font.weight,
				fontSize: font.size,
				fontStyle: font.style,
			});
		}
		return this;
	}
});
<|endoftext|>


<commit_before>(function () {
    'use strict';
    angular
        .module('ion-location', [
            'ionic',
            'gettext'
        ])
        .directive('ionLocation', function (gettextCatalog, $ionicModal, GeoService) {
            return {
                restrict: 'A',
                scope   : {
                    location: '='
                },
                link    : function ($scope, element) {

                    function init() {
                        $scope.search             = {};
                        $scope.search.suggestions = [];
                        $scope.search.query       = '';
                    };

                    function selectPlace(place_id) {
                        GeoService
                            .getDetails(place_id)
                            .then(function (location) {

                                console.info(location);

                                var address = GeoService
                                    .parseAddress(location);

                                $scope.location = {
                                    number  : address.number,
                                    street  : address.street,
                                    district: address.district,
                                    city    : address.city,
                                    state   : address.state,
                                    country : address.country,
                                    zipcode : address.zipcode,
                                    coords  : address.geo,
                                    image   : address.image,
                                    resume  : address.resume
                                };

                                console.log($scope.location);
                                $scope.closeModalLocation();
                            });
                    }

                    element.bind('focus', function () {
                        init();
                        console.log('Start');

                        var translate = {
                            string1: gettextCatalog.getString('My Location'),
                            string2: gettextCatalog.getString('Search')
                        }

                        $scope.modalLocation = $ionicModal.fromTemplate('<ion-modal-view>' +
                            '<ion-header-bar class="bar bar-positive item-input-inset">' +
                            '<button class="button button-clear button-icon ion-pinpoint" ng-click="findMe()"></button>' +
                            '' +
                            '<input type="search" ng-model="search.query" placeholder="{{ \'Search\' | translate }}">' +
                            '<button class="button button-clear button-icon ion-ios-close-empty" ng-click="closeModalLocation()"></button>' +
                            '</ion-header-bar>' +
                            '<ion-content padding="false">' +
                            '<ion-list>' +
                            '<ion-item ng-click="findMe()" ng-hide="search.suggestions.length">{{ \'My Location\' | translate }}</ion-item>' +
                            '<ion-item ng-repeat="suggestion in search.suggestions" ng-click="choosePlace(suggestion)" ng-bind="suggestion.description"></ion-item>' +
                            '<ion-item class="item-divider"></ion-item>' +
                            '</ion-list>' +
                            '</ion-content>' +
                            '</ion-modal-view>', {
                                scope          : $scope,
                                focusFirstInput: true
                            }
                        )
                        ;

                        $scope.modalLocation.show();

                        $scope.closeModalLocation = function () {
                            $scope.modalLocation.hide();
                            $scope.modalLocation.remove();
                        };

                        $scope.$watch('search.query', function (newValue) {
                            if (newValue) {
                                GeoService
                                    .searchAddress(newValue)
                                    .then(function (result) {
                                        console.log(result);
                                        $scope.search.suggestions = result;
                                    });
                            }
                        });

                        $scope.findMe = function () {
                            GeoService
                                .findMe()
                                .then(function (location) {
                                    console.log(location);

                                    selectPlace(location.results[0].place_id)

                                });
                        };

                        $scope.choosePlace = function (place) {

                            selectPlace(place.place_id)

                        };

                    });

                }
            };
        })
        .factory('GeoService', function ($http, $window, $cordovaGeolocation, Loading, $timeout, $q) {
            /**
             'street_address', //indicates a precise street address.
             'route', //indicates a named route (such as "US 101").
             'intersection', //indicates a major intersection, usually of two major roads.
             'political', //indicates a political entity. Usually, this type indicates a polygon of some civil administration.
             'country', //indicates the national political entity, and is typically the highest order type returned by the Geocoder.
             'administrative_area_level_1', //indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels.
             'administrative_area_level_2', //indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.
             'administrative_area_level_3', //indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
             'colloquial_area', //indicates a commonly-used alternative name for the entity.
             'locality', //indicates an incorporated city or town political entity.
             'sublocality', //indicates an first-order civil entity below a locality
             'neighborhood', //indicates a named neighborhood
             'premise', //indicates a named location, usually a building or collection of buildings with a common name
             'subpremise', //indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name
             'postal_code', //indicates a postal code as used to address postal mail within the country.
             'natural_feature', //indicates a prominent natural feature.
             'airport', //indicates an airport.
             'park', //indicates a named park.
             'point_of_interest', //indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category such as "Empire State Building" or "Statue of Liberty."

             //In addition to the above, address components may exhibit the following types:

             'post_box', //indicates a specific postal box.
             'street_number', //indicates the precise street number.
             'floor indicates', //the floor of a building address.
             'room indicates'; //the room of a building address.'
             */
            var options             = {types: ['geocode']};
            var autocompleteService = new $window.google.maps.places.AutocompleteService();
            var detailsService      = new $window.google.maps.places.PlacesService($window.document.createElement('input'), options);
            var componentForm       = {
                street_number              : 'long_name',
                //number
                route                      : 'long_name',
                //street
                locality                   : 'long_name',
                // district
                sublocality                : 'long_name',
                // district
                neighborhood               : 'long_name',
                //state
                political                  : 'long_name',
                //state
                administrative_area_level_1: 'long_name',
                //state
                country                    : 'long_name',
                //country
                postal_code                : 'long_name'  //zipcode
            };
            var componentFormName   = {
                street_number              : 'number',
                //number
                route                      : 'street',
                //street
                locality                   : 'city',
                // district
                administrative_area_level_1: 'state',
                //state
                country                    : 'country',
                //country
                postal_code                : 'zipcode',
                //zipcode
                neighborhood               : 'district'  //zipcode
            };

            var data = {
                coords: {},
                src   : ''
            };

            function getLocation() {
                // Pega a Localização da Pessoa
                Loading.start();
                var defer = $q.defer();

                if (data.location) {
                    $timeout(function () {
                        defer.resolve(data.location);
                        Loading.end();
                    }, 1000);
                } else {
                    var posOptions = {
                        timeout           : 10000,
                        enableHighAccuracy: false
                    };
                    $cordovaGeolocation
                        .getCurrentPosition(posOptions)
                        .then(function (position) {
                            console.log('Fez a requisição', position);

                            data.location = {
                                latitude : position.coords.latitude,
                                longitude: position.coords.longitude
                            };
                            Loading.end();
                            defer.resolve(data.location);
                        }, function (err) {
                            // error
                            console.log('Error na geolocalização', err);
                            Loading.end();
                            defer.reject(err);
                        });
                }

                return defer.promise;
            }

            function findMe() {
                var defer = $q.defer();

                getLocation()
                    .then(function (pos) {
                        console.log(pos);
                        getGoogleAddress(pos.latitude, pos.longitude)
                            .success(function (resp) {
                                console.log(resp);
                                defer.resolve(resp);
                            })
                            .error(logErr);
                    })
                return defer.promise;
            };

            function logErr(error) {
                console.log(error);
            };
            function getGoogleAddress(lat, lng) {
                return $http.get('http://maps.google.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&sensor=true').success(function (data) {
                    data.address_normal = data.results[0].formatted_address;
                    data.address        = address(data.results[0].address_components);
                    data.src            = imagem(lat, lng, 18, 500, 300);
                });
            };
            function address(address) {
                if (!address) {
                    return false;
                }
                return {
                    numero  : address[0].short_name,
                    rua     : address[1].long_name,
                    bairro  : address[2].short_name,
                    cidade  : address[3].short_name,
                    estado  : address[5].long_name,
                    uf      : address[5].short_name,
                    pais    : address[6].long_name,
                    paisCode: address[6].short_name,
                    cep     : address[7].short_name
                };
            }

            function imagem(lat, lng, zoom, w, h) {
                return 'http://maps.google.com/maps/api/staticmap?center=' + lat + ',' + lng + '&zoom=' + zoom + '&size=' + w + 'x' + h + '&maptype=roadmap&sensor=true';
            }

            function parseAddress(place) {
                console.log(place);
                var address = {
                    resume: '',
                    geo   : {
                        latitude : (place.geometry.location.k) ? place.geometry.location.k : place.geometry.location.G,
                        longitude: (place.geometry.location.D) ? place.geometry.location.D : place.geometry.location.K
                    }
                };
                var image   = src(address.geo.latitude, address.geo.longitude, 16, 900, 200);
                for (var i = 0; i < place.address_components.length; i++) {
                    var addressType = place.address_components[i].types[0];
                    if (componentForm[addressType]) {
                        var val                                 = place.address_components[i][componentForm[addressType]];
                        address[componentFormName[addressType]] = val;
                    }
                }
                address.street = address.street + ', ' + address.number;
                address.image  = image;
                address.resume = address.street + ' - ' + address.city + ', ' + address.state + ', ' + address.country;
                return address;
            };
            function searchAddress(input) {
                var deferred = $q.defer();
                autocompleteService.getQueryPredictions({input: input}, function (result) {
                    deferred.resolve(result);
                });
                return deferred.promise;
            };
            function getDetails(placeId) {
                var deferred = $q.defer();
                detailsService.getDetails({placeId: placeId}, function (result) {
                    deferred.resolve(result);
                });
                return deferred.promise;
            };
            function src(lat, lng, zoom, w, h) {
                var link = 'http://maps.googleapis.com/maps/api/staticmap?center=' + lat + ',' + lng + '&zoom=' + zoom + '&scale=1&size=' + w + 'x' + h + '&maptype=roadmap&format=jpg&visual_refresh=true&markers=size:small%7Ccolor:0xff2600%7Clabel:0%7C' + lat + ',' + lng + '&sensor=true';
                console.log(link);
                return link;
            };
            return {
                src          : src,
                getDetails   : getDetails,
                searchAddress: searchAddress,
                parseAddress : parseAddress,
                findMe       : findMe

            }
        });
})();<commit_msg>Fix Geolocation thanks Francesco Messina<commit_after>(function () {
    'use strict';
    angular
        .module('ion-location', [
            'ionic',
            'gettext'
        ])
        .directive('ionLocation', function (gettextCatalog, $ionicModal, GeoService) {
            return {
                restrict: 'A',
                scope   : {
                    location: '='
                },
                link    : function ($scope, element) {

                    function init() {
                        $scope.search             = {};
                        $scope.search.suggestions = [];
                        $scope.search.query       = '';
                    };

                    function selectPlace(place_id) {
                        GeoService
                            .getDetails(place_id)
                            .then(function (location) {

                                console.info(location);

                                var address = GeoService
                                    .parseAddress(location);

                                $scope.location = {
                                    number  : address.number,
                                    street  : address.street,
                                    district: address.district,
                                    city    : address.city,
                                    state   : address.state,
                                    country : address.country,
                                    zipcode : address.zipcode,
                                    coords  : address.geo,
                                    image   : address.image,
                                    resume  : address.resume
                                };

                                console.log($scope.location);
                                $scope.closeModalLocation();
                            });
                    }

                    element.bind('focus', function () {
                        init();
                        console.log('Start');

                        var translate = {
                            string1: gettextCatalog.getString('My Location'),
                            string2: gettextCatalog.getString('Search')
                        }

                        $scope.modalLocation = $ionicModal.fromTemplate('<ion-modal-view>' +
                            '<ion-header-bar class="bar bar-positive item-input-inset">' +
                            '<button class="button button-clear button-icon ion-pinpoint" ng-click="findMe()"></button>' +
                            '' +
                            '<input type="search" ng-model="search.query" placeholder="{{ \'Search\' | translate }}">' +
                            '<button class="button button-clear button-icon ion-ios-close-empty" ng-click="closeModalLocation()"></button>' +
                            '</ion-header-bar>' +
                            '<ion-content padding="false">' +
                            '<ion-list>' +
                            '<ion-item ng-click="findMe()" ng-hide="search.suggestions.length">{{ \'My Location\' | translate }}</ion-item>' +
                            '<ion-item ng-repeat="suggestion in search.suggestions" ng-click="choosePlace(suggestion)" ng-bind="suggestion.description"></ion-item>' +
                            '<ion-item class="item-divider"></ion-item>' +
                            '</ion-list>' +
                            '</ion-content>' +
                            '</ion-modal-view>', {
                                scope          : $scope,
                                focusFirstInput: true
                            }
                        )
                        ;

                        $scope.modalLocation.show();

                        $scope.closeModalLocation = function () {
                            $scope.modalLocation.hide();
                            $scope.modalLocation.remove();
                        };

                        $scope.$watch('search.query', function (newValue) {
                            if (newValue) {
                                GeoService
                                    .searchAddress(newValue)
                                    .then(function (result) {
                                        console.log(result);
                                        $scope.search.suggestions = result;
                                    });
                            }
                        });

                        $scope.findMe = function () {
                            GeoService
                                .findMe()
                                .then(function (location) {
                                    console.log(location);

                                    selectPlace(location.results[0].place_id)

                                });
                        };

                        $scope.choosePlace = function (place) {

                            selectPlace(place.place_id)

                        };

                    });

                }
            };
        })
        .factory('GeoService', function ($http, $window, $cordovaGeolocation, Loading, $timeout, $q) {
            /**
             'street_address', //indicates a precise street address.
             'route', //indicates a named route (such as "US 101").
             'intersection', //indicates a major intersection, usually of two major roads.
             'political', //indicates a political entity. Usually, this type indicates a polygon of some civil administration.
             'country', //indicates the national political entity, and is typically the highest order type returned by the Geocoder.
             'administrative_area_level_1', //indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels.
             'administrative_area_level_2', //indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.
             'administrative_area_level_3', //indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
             'colloquial_area', //indicates a commonly-used alternative name for the entity.
             'locality', //indicates an incorporated city or town political entity.
             'sublocality', //indicates an first-order civil entity below a locality
             'neighborhood', //indicates a named neighborhood
             'premise', //indicates a named location, usually a building or collection of buildings with a common name
             'subpremise', //indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name
             'postal_code', //indicates a postal code as used to address postal mail within the country.
             'natural_feature', //indicates a prominent natural feature.
             'airport', //indicates an airport.
             'park', //indicates a named park.
             'point_of_interest', //indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category such as "Empire State Building" or "Statue of Liberty."

             //In addition to the above, address components may exhibit the following types:

             'post_box', //indicates a specific postal box.
             'street_number', //indicates the precise street number.
             'floor indicates', //the floor of a building address.
             'room indicates'; //the room of a building address.'
             */
            var options             = {types: ['geocode']};
            var autocompleteService = new $window.google.maps.places.AutocompleteService();
            var detailsService      = new $window.google.maps.places.PlacesService($window.document.createElement('input'), options);
            var componentForm       = {
                street_number              : 'long_name',
                //number
                route                      : 'long_name',
                //street
                locality                   : 'long_name',
                // district
                sublocality                : 'long_name',
                // district
                neighborhood               : 'long_name',
                //state
                political                  : 'long_name',
                //state
                administrative_area_level_1: 'long_name',
                //state
                country                    : 'long_name',
                //country
                postal_code                : 'long_name'  //zipcode
            };
            var componentFormName   = {
                street_number              : 'number',
                //number
                route                      : 'street',
                //street
                locality                   : 'city',
                // district
                administrative_area_level_1: 'state',
                //state
                country                    : 'country',
                //country
                postal_code                : 'zipcode',
                //zipcode
                neighborhood               : 'district'  //zipcode
            };

            var data = {
                coords: {},
                src   : ''
            };

            function getLocation() {
                // Pega a Localização da Pessoa
                Loading.start();
                var defer = $q.defer();

                if (data.location) {
                    $timeout(function () {
                        defer.resolve(data.location);
                        Loading.end();
                    }, 1000);
                } else {
                    var posOptions = {
                        timeout           : 10000,
                        enableHighAccuracy: false
                    };
                    $cordovaGeolocation
                        .getCurrentPosition(posOptions)
                        .then(function (position) {
                            console.log('Fez a requisição', position);

                            data.location = {
                                latitude : position.coords.latitude,
                                longitude: position.coords.longitude
                            };
                            Loading.end();
                            defer.resolve(data.location);
                        }, function (err) {
                            // error
                            console.log('Error na geolocalização', err);
                            Loading.end();
                            defer.reject(err);
                        });
                }

                return defer.promise;
            }

            function findMe() {
                var defer = $q.defer();

                getLocation()
                    .then(function (pos) {
                        console.log(pos);
                        getGoogleAddress(pos.latitude, pos.longitude)
                            .success(function (resp) {
                                resp.geolocation = pos;
                                console.log(resp);
                                defer.resolve(resp);
                            })
                            .error(logErr);
                    })
                return defer.promise;
            };

            function logErr(error) {
                console.log(error);
            };
            function getGoogleAddress(lat, lng) {
                return $http.get('http://maps.google.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&sensor=true').success(function (data) {
                    data.address_normal = data.results[0].formatted_address;
                    data.address        = address(data.results[0].address_components);
                    data.src            = imagem(lat, lng, 18, 500, 300);
                });
            };
            function address(address) {
                if (!address) {
                    return false;
                }
                return {
                    numero  : address[0].short_name,
                    rua     : address[1].long_name,
                    bairro  : address[2].short_name,
                    cidade  : address[3].short_name,
                    estado  : address[5].long_name,
                    uf      : address[5].short_name,
                    pais    : address[6].long_name,
                    paisCode: address[6].short_name,
                    cep     : address[7].short_name
                };
            }

            function imagem(lat, lng, zoom, w, h) {
                return 'http://maps.google.com/maps/api/staticmap?center=' + lat + ',' + lng + '&zoom=' + zoom + '&size=' + w + 'x' + h + '&maptype=roadmap&sensor=true';
            }

            function parseAddress(place) {
                console.log(place);
                var address = {
                    resume: '',
                    geo   : {
                        latitude : (place.geometry.location.k) ? place.geometry.location.k : place.geometry.location.G,
                        longitude: (place.geometry.location.D) ? place.geometry.location.D : place.geometry.location.K
                    }
                };
                var image   = src(address.geo.latitude, address.geo.longitude, 16, 900, 200);
                for (var i = 0; i < place.address_components.length; i++) {
                    var addressType = place.address_components[i].types[0];
                    if (componentForm[addressType]) {
                        var val                                 = place.address_components[i][componentForm[addressType]];
                        address[componentFormName[addressType]] = val;
                    }
                }
                address.street = address.street + ', ' + address.number;
                address.image  = image;
                address.resume = address.street + ' - ' + address.city + ', ' + address.state + ', ' + address.country;
                return address;
            };
            function searchAddress(input) {
                var deferred = $q.defer();
                autocompleteService.getQueryPredictions({input: input}, function (result) {
                    deferred.resolve(result);
                });
                return deferred.promise;
            };
            function getDetails(placeId) {
                var deferred = $q.defer();
                detailsService.getDetails({placeId: placeId}, function (result) {
                    deferred.resolve(result);
                });
                return deferred.promise;
            };
            function src(lat, lng, zoom, w, h) {
                var link = 'http://maps.googleapis.com/maps/api/staticmap?center=' + lat + ',' + lng + '&zoom=' + zoom + '&scale=1&size=' + w + 'x' + h + '&maptype=roadmap&format=jpg&visual_refresh=true&markers=size:small%7Ccolor:0xff2600%7Clabel:0%7C' + lat + ',' + lng + '&sensor=true';
                console.log(link);
                return link;
            };
            return {
                src          : src,
                getDetails   : getDetails,
                searchAddress: searchAddress,
                parseAddress : parseAddress,
                findMe       : findMe

            }
        });
})();<|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;

// for battery level to work, you have to turn it
// on first otherwise it will report -1.  if you
// add a battery listener, it will turn it on for you
// automagically
var needUpdate = false;
Titanium.Platform.batteryMonitoring = true;

win.addEventListener('close',function()
{
	// turn it off, no need to waste the battery
	Titanium.Platform.batteryMonitoring = false;
	Titanium.Platform.removeEventListener('battery');
});

function batteryStateToString(state)
{
	switch (state)
	{
		case Titanium.Platform.BATTERY_STATE_UNKNOWN:
			return 'unknown';
		case Titanium.Platform.BATTERY_STATE_UNPLUGGED:
			return 'unplugged';
		case Titanium.Platform.BATTERY_STATE_CHARGING:
			return 'charging';
		case Titanium.Platform.BATTERY_STATE_FULL:
			return 'full';
	}
	return '???';
}

var l1 = Titanium.UI.createLabel({
	text:'name/osname:' + Titanium.Platform.name+'/'+Titanium.Platform.osname,
	top:10,
	left:10,
	width:'auto',
	font:{fontSize:14},
	color:'#777',
	height:'auto'
});

win.add(l1);

var l2 = Titanium.UI.createLabel({
	text:'model:' + Titanium.Platform.model,
	top:30,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l2);

var l3 = Titanium.UI.createLabel({
	text:'version:' + Titanium.Platform.version,
	top:50,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l3);

var l4 = Titanium.UI.createLabel({
	text:'architecture:' + Titanium.Platform.architecture,
	top:70,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l4);

var l5 = Titanium.UI.createLabel({
	text:'macaddress:' + Titanium.Platform.macaddress,
	top:90,
	left:10,
	width:'auto',
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l5);

var l6 = Titanium.UI.createLabel({
	text:'processor count:' + Titanium.Platform.processorCount,
	top:110,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l6);

var l7 = Titanium.UI.createLabel({
	text:'username:' + Titanium.Platform.username,
	top:130,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l7);

// NOTE: Needs to be tested on a physical device to get an accurate value;
// may select the wrong interface on non-mobile devices.
var l8 = Titanium.UI.createLabel({
	text:'address:' + Titanium.Platform.address,
	top:150,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l8);

var l9 = Titanium.UI.createLabel({
	text:'ostype:' + Titanium.Platform.ostype,
	top:170,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l9);

if (Titanium.Platform.batteryState == Ti.Platform.BATTERY_STATE_UNKNOWN) {
	needUpdate = true;
}

var l11 = Titanium.UI.createLabel({
	text:'battery state:' + batteryStateToString(Titanium.Platform.batteryState),
	top:190,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l11);

var l12 = Titanium.UI.createLabel({
	text:'battery level:' + Titanium.Platform.batteryLevel,
	top:210,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l12);

var l13 = Titanium.UI.createLabel({
	text:'display width-x-height:' + Titanium.Platform.displayCaps.platformWidth + 'x' + Titanium.Platform.displayCaps.platformHeight,
	top:230,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l13);

var l15 = Titanium.UI.createLabel({
	text:'display density:' + Titanium.Platform.displayCaps.density,
	top:250,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l15);

var l16 = Titanium.UI.createLabel({
	text:'display dpi:' + Titanium.Platform.displayCaps.dpi,
	top:270,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l16);

var l17 = Titanium.UI.createLabel({
	text:'available memory:' + Titanium.Platform.availableMemory,
	top:290,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l17);

var l18 = Titanium.UI.createLabel({
	text:'is24HourTimeFormat:' + Titanium.Platform.is24HourTimeFormat(),
	top:310,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l18);

var b = Titanium.UI.createButton({
	title:'Open URL',
	height:30,
	width:200,
	top:330
});
win.add(b);
var openURL=1;
b.addEventListener('click', function()
{
	var url;
	switch(openURL % 3)
	{
		case 0:
			url = 'http://www.google.com';
			b.title='Open URL (web)';
			break;
		case 1:
			url = 'tel:4043332222';
			b.title='Open URL (tel)';
			break;
		case 2:
			url = 'sms:4043332222';
			b.title='Open URL (sms)';
			break;
	}
	if (Titanium.Platform.name != 'android') {
		if (!Titanium.Platform.canOpenURL(url)) {
			Ti.API.warn("Can't open url: "+url);
		}
	}
	Titanium.Platform.openURL(url);
	openURL++;
});

//
// BATTERY STATE CHANGE EVENT
//
Titanium.Platform.addEventListener('battery', function(e)
{
	if (needUpdate) {
		l11.text = 'battery state:' + batteryStateToString(e.state);
		l12.text = 'battery level:' + e.level;
	} else {
		//TODO: based on various reports from the google, you only get battery state changes
		//at 5% intervals.... to test this, you gotta unplug and leave your phone sitting for awhile
		var message = 'Battery Notification\n\nLevel: ' + e.level + ', State: '+batteryStateToString(e.state);
		Titanium.UI.createAlertDialog({title:'Platform', message:message}).show();
	}
});

Titanium.API.info("Current Phone Locale is "+Titanium.Platform.locale);
Titanium.API.info("OS name is " + Titanium.Platform.osname);

if (Titanium.Platform.osname == 'iphone' || Titanium.Platform.osname == 'ipad') {
	Titanium.API.info("Data network: " + Titanium.Platform.dataAddress);
	Titanium.API.info("Netmask: " + Titanium.Platform.netmask);
	Titanium.API.info("runtime: " + Titanium.Platform.runtime);
}
<commit_msg>[timob-6009]  Update for review comments<commit_after>var win = Titanium.UI.currentWindow;

// for battery level to work, you have to turn it
// on first otherwise it will report -1.  if you
// add a battery listener, it will turn it on for you
// automagically
var needUpdate = false;
Titanium.Platform.batteryMonitoring = true;

win.addEventListener('close',function()
{
	// turn it off, no need to waste the battery
	Titanium.Platform.batteryMonitoring = false;
	Titanium.Platform.removeEventListener('battery');
});

function batteryStateToString(state)
{
	switch (state)
	{
		case Titanium.Platform.BATTERY_STATE_UNKNOWN:
			return 'unknown';
		case Titanium.Platform.BATTERY_STATE_UNPLUGGED:
			return 'unplugged';
		case Titanium.Platform.BATTERY_STATE_CHARGING:
			return 'charging';
		case Titanium.Platform.BATTERY_STATE_FULL:
			return 'full';
	}
	return '???';
}

var l1 = Titanium.UI.createLabel({
	text:'name/osname:' + Titanium.Platform.name+'/'+Titanium.Platform.osname,
	top:10,
	left:10,
	width:'auto',
	font:{fontSize:14},
	color:'#777',
	height:'auto'
});

win.add(l1);

var l2 = Titanium.UI.createLabel({
	text:'model:' + Titanium.Platform.model,
	top:30,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l2);

var l3 = Titanium.UI.createLabel({
	text:'version:' + Titanium.Platform.version,
	top:50,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l3);

var l4 = Titanium.UI.createLabel({
	text:'architecture:' + Titanium.Platform.architecture,
	top:70,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l4);

var l5 = Titanium.UI.createLabel({
	text:'macaddress:' + Titanium.Platform.macaddress,
	top:90,
	left:10,
	width:'auto',
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l5);

var l6 = Titanium.UI.createLabel({
	text:'processor count:' + Titanium.Platform.processorCount,
	top:110,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l6);

var l7 = Titanium.UI.createLabel({
	text:'username:' + Titanium.Platform.username,
	top:130,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l7);

// NOTE: Needs to be tested on a physical device to get an accurate value;
// may select the wrong interface on non-mobile devices.
var l8 = Titanium.UI.createLabel({
	text:'address:' + Titanium.Platform.address,
	top:150,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l8);

var l9 = Titanium.UI.createLabel({
	text:'ostype:' + Titanium.Platform.ostype,
	top:170,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l9);

if (Titanium.Platform.batteryState == Ti.Platform.BATTERY_STATE_UNKNOWN) {
	needUpdate = true;
}

var l11 = Titanium.UI.createLabel({
	text:'battery state:' + batteryStateToString(Titanium.Platform.batteryState),
	top:190,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l11);

var l12 = Titanium.UI.createLabel({
	text:'battery level:' + Titanium.Platform.batteryLevel,
	top:210,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l12);

var l13 = Titanium.UI.createLabel({
	text:'display width-x-height:' + Titanium.Platform.displayCaps.platformWidth + 'x' + Titanium.Platform.displayCaps.platformHeight,
	top:230,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l13);

var l15 = Titanium.UI.createLabel({
	text:'display density:' + Titanium.Platform.displayCaps.density,
	top:250,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l15);

var l16 = Titanium.UI.createLabel({
	text:'display dpi:' + Titanium.Platform.displayCaps.dpi,
	top:270,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l16);

var l17 = Titanium.UI.createLabel({
	text:'available memory:' + Titanium.Platform.availableMemory,
	top:290,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l17);

var l18 = Titanium.UI.createLabel({
	text:'is24HourTimeFormat:' + Titanium.Platform.is24HourTimeFormat(),
	top:310,
	left:10,
	width:300,
	height:'auto',
	font:{fontSize:14},
	color:'#777'
});

win.add(l18);

var b = Titanium.UI.createButton({
	title:'Open URL',
	height:30,
	width:200,
	top:330
});
win.add(b);
var openURL=1;
b.addEventListener('click', function()
{
	var url;
	switch(openURL % 3)
	{
		case 0:
			url = 'http://www.google.com';
			b.title='Open URL (web)';
			break;
		case 1:
			url = 'tel:4043332222';
			b.title='Open URL (tel)';
			break;
		case 2:
			url = 'sms:4043332222';
			b.title='Open URL (sms)';
			break;
	}
	if (Titanium.Platform.name != 'android') {
		if (!Titanium.Platform.canOpenURL(url)) {
			Ti.API.warn("Can't open url: "+url);
		}
	}
	Titanium.Platform.openURL(url);
	openURL++;
});

//
// BATTERY STATE CHANGE EVENT
//
Titanium.Platform.addEventListener('battery', function(e)
{
	if (needUpdate) {
		l11.text = 'battery state:' + batteryStateToString(e.state);
		l12.text = 'battery level:' + e.level;
	} else {
		//TODO: based on various reports from the google, you only get battery state changes
		//at 5% intervals.... to test this, you gotta unplug and leave your phone sitting for awhile
		var message = 'Battery Notification\n\nLevel: ' + e.level + ', State: '+batteryStateToString(e.state);
		Titanium.UI.createAlertDialog({title:'Platform', message:message}).show();
	}
});

Titanium.API.info("Current Phone Locale is "+Titanium.Platform.locale);
Titanium.API.info("OS name is " + Titanium.Platform.osname);
Titanium.API.info("Runtime: " + Titanium.Platform.runtime);

if (Titanium.Platform.osname == 'iphone' || Titanium.Platform.osname == 'ipad') {
	Titanium.API.info("Data network: " + Titanium.Platform.dataAddress);
	Titanium.API.info("Netmask: " + Titanium.Platform.netmask);
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt

frappe.ui.form.on('Bank Guarantee', {
	refresh: function(frm) {
		cur_frm.set_query("account_name", function() {
			return {
				"filters": {
					"account_type": "Bank",
					"is_group": 0
				}
			};
		});
		cur_frm.set_query("project", function() {
			return {
				"filters": {
					"customer": cur_frm.doc.customer
				}
			};
		});
	},
	start_date: function(frm) {
		end_date = frappe.datetime.add_days(cur_frm.doc.start_date, cur_frm.doc.validity - 1);
		cur_frm.set_value("end_date", end_date);
	},
	validity: function(frm) {
		end_date = frappe.datetime.add_days(cur_frm.doc.start_date, cur_frm.doc.validity - 1);
		cur_frm.set_value("end_date", end_date);
	}
});

// $.extend(cur_frm.cscript, {
// 	start_date: function(doc, dt, dn) {
// 		var me = this;
// 		end_date =
// 			frappe.datetime.add_days(this.frm.doc.start_date, this.frm.doc.validity - 1);
// 		this.frm.set_value("end_date", end_date);
// 	},
// 	validity: function(doc, dt, dn) {
// 		var me = this;
// 		end_date =
// 			frappe.datetime.add_days(this.frm.doc.start_date, this.frm.doc.validity - 1);
// 		this.frm.set_value("end_date", end_date);
// 	}
// });<commit_msg>Remove commented out code<commit_after>// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt

frappe.ui.form.on('Bank Guarantee', {
	refresh: function(frm) {
		cur_frm.set_query("account_name", function() {
			return {
				"filters": {
					"account_type": "Bank",
					"is_group": 0
				}
			};
		});
		cur_frm.set_query("project", function() {
			return {
				"filters": {
					"customer": cur_frm.doc.customer
				}
			};
		});
	},
	start_date: function(frm) {
		end_date = frappe.datetime.add_days(cur_frm.doc.start_date, cur_frm.doc.validity - 1);
		cur_frm.set_value("end_date", end_date);
	},
	validity: function(frm) {
		end_date = frappe.datetime.add_days(cur_frm.doc.start_date, cur_frm.doc.validity - 1);
		cur_frm.set_value("end_date", end_date);
	}
});<|endoftext|>