<commit_before>var args = arguments[0] || {};

var piApi   = require('pi'),
    data    = require('data'),
    ui      = require('ui');

var eventData = data.get('eventData'), selectedEvent = data.get('event');

function generateEventWindow(event) {

    if (! event) {
        $.eventNavigationWindow.close();

        return;
    }

    eventData = event;

    var windowReference = null;

    // General styles
    if (Titanium.Platform.osname == 'android') {
        $.eventNavigationWindow.setTitle(event.title);
        $.eventScrollView.setBackgroundColor(event.styles.background);

    } else {
        $.eventWindow.setTitle(event.title);
        $.eventScrollView.setBackgroundColor(event.styles.background);

        windowReference = $.eventNavigationWindow;
    }

    data.set('windowReference', windowReference);

    var image = Ti.UI.createImageView({
       image: event.image,
       width: '100%'
    });

    $.logoContainer.add(image);

    eventData.logoImageView = image;

    image.addEventListener("load", initEventLayout);

    var label 	= '';
    	pageId 	= 0,
    	j 		= null;

    var tabButtonQuantity = event.tabs_order.length;

    /* Menu */

    for (var item in event.order) {
    	if (event.order[item].substring(0, 5) == 'page_') {
    		pageId = event.order[item].match('[0-9]+')[0];

    		for (j in event.pages) {

    			if (event.pages[j].id != pageId) {
    				continue;
    			}

                addEventMenuItem({
                    icon: event.pages[j].icon,
                    label: event.pages[j].title,
                    onClick: function(e) {
                        var page    = null,
                            title   = e.source.getTitle();

                        for (var i in eventData.pages) {
                            if (eventData.pages[i].title == title) {
                                page = eventData.pages[i];

                                break;
                            }
                        }

                        data.set('page', page);

                        var window = Alloy.createController('page').getView();

                        if (Titanium.Platform.osname == 'android') {
                            window.open({
                                modal: true
                            });
                        } else {
                            $.eventNavigationWindow.openWindow(window, { animated:true });
                        }
                    }
                });

            }
    	}

    	//************************************** MENU ITEMS  **************************************
        switch (event.order[item]) {
            case "news":
                if (event.news_label) {
                    addEventMenuItem({
                        icon: event.news_icon,
                        label: event.news_label,
                        controller: 'news'
                    });
                }
            break;

            case "home":
	            addEventMenuItem({
	                icon: event.home_icon,
	                label: 'Inicio',
	                onClick: function () {
	                    $.eventNavigationWindow.close();
	                }
	            });
            break;

            case "form":
                if (event.form) {
                    label = event.form_label || 'Inscripción online';

                    addEventMenuItem({
                        icon: event.form_icon,
                        label: label,
                        controller: 'form'
                    });
                }
            break;

            case "certificate":
                if (event.certificate) {
                    label = event.certificate_label || 'Certificación web';

                    addEventMenuItem({
                        icon: event.certificate_icon,
                        label: label,
                        'controller': 'certificate'
                    });
                }
            break;

            case "favorites":
                if (event.favorites_label) {
                    label = event.favorites_label || 'Favoritos';

                    addEventMenuItem({
                        icon: event.favorites_icon,
                        label: label,
                        controller: 'favorite'
                    }, tabButtonQuantity);
                }
            break;

            case "link":
                if (event.link_url) {
                    label = event.link_label || 'Link';

                    addEventMenuItem({
                        icon: event.link_icon,
                        label: label,
                        'controller': 'link'
                    });
                }
            break;

            case "accommodations":
                if (event.accommodations_label) {
                    label = event.accommodations_label || 'Alojamientos';

                    addEventMenuItem({
                        icon: event.accommodations_icon,
                        label: label,
                        controller: 'accommodations'
                    });
                }
            break;

            case "map":
                if (event.map_label) {
                    label = event.map_label || 'Ubicación';

                    addEventMenuItem({
                        icon: event.map_icon,
                        label: label,
                        controller: 'map'
                    });
                }
            break;

            case "agenda":
                if (event.agenda_label) {
                    label = event.agenda_label || 'Agenda';

                    addEventMenuItem({
                        icon: event.agenda_icon,
                        label: label,
                        controller: 'agenda'
                    }, tabButtonQuantity);
                }
            break;
        }
    }

    //************************************** TAB ITEMS  **************************************
    for (var item in event.tabs_order) {
    	if (event.tabs_order[item].substring(0, 5) == 'page_') {
    		pageId = event.tabs_order[item].match('[0-9]+')[0];

    		for (j in event.pages) {

    			if (event.pages[j].id != pageId) {
    				continue;
    			}

                addEventTabItem({
                    icon: event.pages[j].icon,
                    label: event.pages[j].title,
                    onClick: function(e) {
                        var page    = null,
                            title   = e.source.getTitle();

                        for (var i in eventData.pages) {
                            if (eventData.pages[i].title == title) {
                                page = eventData.pages[i];

                                break;
                            }
                        }

                        data.set('page', page);

                        var window = Alloy.createController('page').getView();

                        if (Titanium.Platform.osname == 'android') {
                            window.open({
                                modal: true
                            });
                        } else {
                            $.eventNavigationWindow.openWindow(window, { animated:true });
                        }
                    }
                }, tabButtonQuantity);

            }
    	}

        switch (event.tabs_order[item]) {
            case "form":
                if (event.news_label) {
                    addEventTabItem({
                        icon: event.news_icon,
                        label: event.news_label,
                        controller: 'news'
                    }, tabButtonQuantity);
                }
            break;

            case "home":
	            addEventTabItem({
	                icon: event.home_icon,
	                label: 'Inicio',
	                onClick: function () {
	                    $.eventNavigationWindow.close();
	                }
	            }, tabButtonQuantity);
            break;

            case "form":
                if (event.form) {
                    label = event.form_label || 'Inscripción online';

                    addEventTabItem({
                        icon: event.form_icon,
                        label: label,
                        controller: 'form'
                    }, tabButtonQuantity);
                }
            break;

            case "certificate":
                if (event.certificate) {
                    label = event.certificate_label || 'Certificación web';

                    addEventTabItem({
                        icon: event.certificate_icon,
                        label: label,
                        'controller': 'certificate'
                    }, tabButtonQuantity);
                }
            break;

            case "favorites":
                if (event.agenda_label) {
                    label = event.favorites_label || 'Favoritos';

                    addEventTabItem({
                        icon: event.favorites_icon,
                        label: label,
                        controller: 'favorite'
                    }, tabButtonQuantity);
                }
            break;

            case "link":
                if (event.link_url) {
                    label = event.link_label || 'Link';

                    addEventTabItem({
                        icon: event.link_icon,
                        label: label,
                        'controller': 'link'
                    }, tabButtonQuantity);
                }
            break;

            case "accommodations":
                if (event.accommodations_label) {
                    label = event.accommodations_label || 'Alojamientos';

                    addEventTabItem({
                        icon: event.accommodations_icon,
                        label: label,
                        controller: 'accommodations'
                    }, tabButtonQuantity);
                }
            break;

            case "map":
                if (event.map_label) {
                    label = event.map_label || 'Ubicación';

                    addEventTabItem({
                        icon: event.map_icon,
                        label: label,
                        controller: 'map'
                    }, tabButtonQuantity);
                }
            break;

            case "agenda":
                if (event.agenda_label) {
                    label = event.agenda_label || 'Agenda';

                    addEventTabItem({
                        icon: event.agenda_icon,
                        label: label,
                        controller: 'agenda'
                    }, tabButtonQuantity);
                }
            break;
        }
    }

    $.eventView.add(Ti.UI.createView({
        height: 10,
        width: '100%',
        left: 0,
        top: 0
    }));
}

var isFirstButton = true;

generateEventWindow(eventData);

function addEventMenuItem(item) {
    item = ui.processItemConfig(item, eventData);

    var button = Titanium.UI.createButton({
        title: item.label,
        width: Ti.UI.FILL,
        height: 40,
        textAlign: 'left',
        backgroundColor: 'transparent',
        borderColor: 'transparent',
        borderWidth: 0,
        color: eventData.styles.button_foreground,
        top: 0,
        left: 0
    });

    var icon = Ti.UI.createImageView({
        image: '/icons' + item.icon,
        width: 30,
        height: 30,
        left: 10,
        top: 5
    });

    var viewWidth   = toDP(Titanium.Platform.displayCaps.platformWidth) - 40,
        viewLeft    = 20;

    var topPosition = (isFirstButton == true) ? 20 : 10;

    isFirstButton = false;

    var view = Titanium.UI.createView({
        borderRadius: 5,
        layout: 'horizontal',
        top: topPosition,
        left: viewLeft,
        width: viewWidth,
        height: 40,
        backgroundColor: eventData.styles.button_background
    });

    view.add(icon);
    view.add(button);

    if (item.controller) {
        button.addEventListener('click', function () {
            var window = Alloy.createController(item.controller).getView();

            if (Titanium.Platform.osname == 'android') {
                window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(window, { animated:true });
            }
        });
    }
    else if (item.onClick) {
        button.addEventListener('click', item.onClick);
    } else if (item.window) {
        button.addEventListener('click', function () {

            if (Titanium.Platform.osname == 'android') {
                item.window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(item.window, { animated:true });
            }
        });
    }

    $.eventView.add(view);
}

function initEventLayout() {
	var event 		= eventData,
		height 		= toDP(Ti.Platform.displayCaps.platformHeight),
		width 		= toDP(Ti.Platform.displayCaps.platformWidth),
		logoHeight	= 0,
		blob 		= null;

	var headerHeight = 60;

	blob = eventData.logoImageView.toBlob();
    if (blob) {

    	logoHeight = (width - 40) * pxToDP(blob.height) / pxToDP(blob.width);

        eventData.logoImageView.setWidth( width - 40);
        eventData.logoImageView.setHeight( logoHeight);
    }

	if (event.tabs_order.length > 0) {
		$.eventScrollView.setHeight(
			height - logoHeight - 120 - headerHeight
		);

		$.tabContainer.setBackgroundColor(event.styles.tab_background);
	} else {
		$.eventScrollView.setHeight(
			height - logoHeight - 40 - headerHeight
		);

		$.tabContainer.hide();
	}

	$.eventScrollView.setTop( logoHeight + 40 );
}

var fistButtonAdded = false;

function addEventTabItem(item, tabButtonQuantity) {
    item = ui.processItemConfig(item, eventData);

	var width = Math.floor(toDP(Ti.Platform.displayCaps.platformWidth) /  tabButtonQuantity) - (tabButtonQuantity - 1);

	var button = Titanium.UI.createView({
		layout: 'vertical',
        width: width,
        height: 80,
        backgroundColor: 'transparent',
        borderColor: 'transparent',
        borderWidth: 0
    });

    var icon = Ti.UI.createImageView({
        image: '/icons' + item.icon,
        width: 30,
        height: 30,
        top: 15
    });

    var view = Titanium.UI.createView({
        layout: 'composite',
        top: 0,
        width: '100%',
        height: Ti.UI.SIZE,
        backgroundColor: 'transparent'
    });

    var label = Ti.UI.createLabel({
    	text: item.label,
    	width: '100%',
    	textAlign: 'center',
    	color: eventData.styles.tab_forecolor,
    	top: 5,
    	font: {
    		fontSize: 12
    	}
    });

    view.add(icon);

    button.add(view);
    button.add(label);

    if (item.controller) {
        button.addEventListener('click', function () {
            var window = Alloy.createController(item.controller).getView();

            if (Titanium.Platform.osname == 'android') {
                window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(window, { animated:true });
            }
        });
    }
    else if (item.onClick) {
        button.addEventListener('click', item.onClick);
    } else if (item.window) {
        button.addEventListener('click', function () {

            if (Titanium.Platform.osname == 'android') {
                item.window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(item.window, { animated:true });
            }
        });
    }

    if (fistButtonAdded) {
    	var line = Titanium.UI.createView({
			layout: 'vertical',
	        width: 1,
	        top: 5,
	        height: 70,
	        backgroundColor: '#eeeeee',
	    });

	    $.tabContainer.add(line);
    }

    fistButtonAdded = true;

    $.tabContainer.add(button);
}

function toDP(dp) {
    if (Titanium.Platform.osname == 'android') {
        return pxToDP(dp);
    }

    return dp;
}

function pxToDP(px) {
    return (px / (Titanium.Platform.displayCaps.dpi / 160));
}

// Event UI reusable functions
function createEventWindow(title, backgroundColor) {
    return Titanium.UI.createWindow({
        backgroundColor: backgroundColor,
        layout: 'vertical',
        title: title
    });
}

function searchItem(items, id) {
    var item = null;

    for (var i in items) {
        if (typeof items[i] != 'object') {
            continue;
        } else if (isNaN(parseInt(i))) {
            item = searchItem(items[i], id);

            if (item) {
                return item;
            }
        } else {
            if ((items[i].id) && (items[i].id == id)) {
                return items[i];
            }
        }
    }

    return null;
}
<commit_msg>Fix news tab adding.<commit_after>var args = arguments[0] || {};

var piApi   = require('pi'),
    data    = require('data'),
    ui      = require('ui');

var eventData = data.get('eventData'), selectedEvent = data.get('event');

function generateEventWindow(event) {

    if (! event) {
        $.eventNavigationWindow.close();

        return;
    }

    eventData = event;

    var windowReference = null;

    // General styles
    if (Titanium.Platform.osname == 'android') {
        $.eventNavigationWindow.setTitle(event.title);
        $.eventScrollView.setBackgroundColor(event.styles.background);

    } else {
        $.eventWindow.setTitle(event.title);
        $.eventScrollView.setBackgroundColor(event.styles.background);

        windowReference = $.eventNavigationWindow;
    }

    data.set('windowReference', windowReference);

    var image = Ti.UI.createImageView({
       image: event.image,
       width: '100%'
    });

    $.logoContainer.add(image);

    eventData.logoImageView = image;

    image.addEventListener("load", initEventLayout);

    var label 	= '';
    	pageId 	= 0,
    	j 		= null;

    var tabButtonQuantity = event.tabs_order.length;

    /* Menu */

    for (var item in event.order) {
    	if (event.order[item].substring(0, 5) == 'page_') {
    		pageId = event.order[item].match('[0-9]+')[0];

    		for (j in event.pages) {

    			if (event.pages[j].id != pageId) {
    				continue;
    			}

                addEventMenuItem({
                    icon: event.pages[j].icon,
                    label: event.pages[j].title,
                    onClick: function(e) {
                        var page    = null,
                            title   = e.source.getTitle();

                        for (var i in eventData.pages) {
                            if (eventData.pages[i].title == title) {
                                page = eventData.pages[i];

                                break;
                            }
                        }

                        data.set('page', page);

                        var window = Alloy.createController('page').getView();

                        if (Titanium.Platform.osname == 'android') {
                            window.open({
                                modal: true
                            });
                        } else {
                            $.eventNavigationWindow.openWindow(window, { animated:true });
                        }
                    }
                });

            }
    	}

    	//************************************** MENU ITEMS  **************************************
        switch (event.order[item]) {
            case "news":
                if (event.news_label) {
                    addEventMenuItem({
                        icon: event.news_icon,
                        label: event.news_label,
                        controller: 'news'
                    });
                }
            break;

            case "home":
	            addEventMenuItem({
	                icon: event.home_icon,
	                label: 'Inicio',
	                onClick: function () {
	                    $.eventNavigationWindow.close();
	                }
	            });
            break;

            case "form":
                if (event.form) {
                    label = event.form_label || 'Inscripción online';

                    addEventMenuItem({
                        icon: event.form_icon,
                        label: label,
                        controller: 'form'
                    });
                }
            break;

            case "certificate":
                if (event.certificate) {
                    label = event.certificate_label || 'Certificación web';

                    addEventMenuItem({
                        icon: event.certificate_icon,
                        label: label,
                        'controller': 'certificate'
                    });
                }
            break;

            case "favorites":
                if (event.favorites_label) {
                    label = event.favorites_label || 'Favoritos';

                    addEventMenuItem({
                        icon: event.favorites_icon,
                        label: label,
                        controller: 'favorite'
                    }, tabButtonQuantity);
                }
            break;

            case "link":
                if (event.link_url) {
                    label = event.link_label || 'Link';

                    addEventMenuItem({
                        icon: event.link_icon,
                        label: label,
                        'controller': 'link'
                    });
                }
            break;

            case "accommodations":
                if (event.accommodations_label) {
                    label = event.accommodations_label || 'Alojamientos';

                    addEventMenuItem({
                        icon: event.accommodations_icon,
                        label: label,
                        controller: 'accommodations'
                    });
                }
            break;

            case "map":
                if (event.map_label) {
                    label = event.map_label || 'Ubicación';

                    addEventMenuItem({
                        icon: event.map_icon,
                        label: label,
                        controller: 'map'
                    });
                }
            break;

            case "agenda":
                if (event.agenda_label) {
                    label = event.agenda_label || 'Agenda';

                    addEventMenuItem({
                        icon: event.agenda_icon,
                        label: label,
                        controller: 'agenda'
                    }, tabButtonQuantity);
                }
            break;
        }
    }

    //************************************** TAB ITEMS  **************************************
    for (var item in event.tabs_order) {
    	if (event.tabs_order[item].substring(0, 5) == 'page_') {
    		pageId = event.tabs_order[item].match('[0-9]+')[0];

    		for (j in event.pages) {

    			if (event.pages[j].id != pageId) {
    				continue;
    			}

                addEventTabItem({
                    icon: event.pages[j].icon,
                    label: event.pages[j].title,
                    onClick: function(e) {
                        var page    = null,
                            title   = e.source.getTitle();

                        for (var i in eventData.pages) {
                            if (eventData.pages[i].title == title) {
                                page = eventData.pages[i];

                                break;
                            }
                        }

                        data.set('page', page);

                        var window = Alloy.createController('page').getView();

                        if (Titanium.Platform.osname == 'android') {
                            window.open({
                                modal: true
                            });
                        } else {
                            $.eventNavigationWindow.openWindow(window, { animated:true });
                        }
                    }
                }, tabButtonQuantity);

            }
    	}

        switch (event.tabs_order[item]) {
            case "news":
                if (event.news_label) {
                    addEventTabItem({
                        icon: event.news_icon,
                        label: event.news_label,
                        controller: 'news'
                    }, tabButtonQuantity);
                }
            break;

            case "home":
	            addEventTabItem({
	                icon: event.home_icon,
	                label: 'Inicio',
	                onClick: function () {
	                    $.eventNavigationWindow.close();
	                }
	            }, tabButtonQuantity);
            break;

            case "form":
                if (event.form) {
                    label = event.form_label || 'Inscripción online';

                    addEventTabItem({
                        icon: event.form_icon,
                        label: label,
                        controller: 'form'
                    }, tabButtonQuantity);
                }
            break;

            case "certificate":
                if (event.certificate) {
                    label = event.certificate_label || 'Certificación web';

                    addEventTabItem({
                        icon: event.certificate_icon,
                        label: label,
                        'controller': 'certificate'
                    }, tabButtonQuantity);
                }
            break;

            case "favorites":
                if (event.agenda_label) {
                    label = event.favorites_label || 'Favoritos';

                    addEventTabItem({
                        icon: event.favorites_icon,
                        label: label,
                        controller: 'favorite'
                    }, tabButtonQuantity);
                }
            break;

            case "link":
                if (event.link_url) {
                    label = event.link_label || 'Link';

                    addEventTabItem({
                        icon: event.link_icon,
                        label: label,
                        'controller': 'link'
                    }, tabButtonQuantity);
                }
            break;

            case "accommodations":
                if (event.accommodations_label) {
                    label = event.accommodations_label || 'Alojamientos';

                    addEventTabItem({
                        icon: event.accommodations_icon,
                        label: label,
                        controller: 'accommodations'
                    }, tabButtonQuantity);
                }
            break;

            case "map":
                if (event.map_label) {
                    label = event.map_label || 'Ubicación';

                    addEventTabItem({
                        icon: event.map_icon,
                        label: label,
                        controller: 'map'
                    }, tabButtonQuantity);
                }
            break;

            case "agenda":
                if (event.agenda_label) {
                    label = event.agenda_label || 'Agenda';

                    addEventTabItem({
                        icon: event.agenda_icon,
                        label: label,
                        controller: 'agenda'
                    }, tabButtonQuantity);
                }
            break;
        }
    }

    $.eventView.add(Ti.UI.createView({
        height: 10,
        width: '100%',
        left: 0,
        top: 0
    }));
}

var isFirstButton = true;

generateEventWindow(eventData);

function addEventMenuItem(item) {
    item = ui.processItemConfig(item, eventData);

    var button = Titanium.UI.createButton({
        title: item.label,
        width: Ti.UI.FILL,
        height: 40,
        textAlign: 'left',
        backgroundColor: 'transparent',
        borderColor: 'transparent',
        borderWidth: 0,
        color: eventData.styles.button_foreground,
        top: 0,
        left: 0
    });

    var icon = Ti.UI.createImageView({
        image: '/icons' + item.icon,
        width: 30,
        height: 30,
        left: 10,
        top: 5
    });

    var viewWidth   = toDP(Titanium.Platform.displayCaps.platformWidth) - 40,
        viewLeft    = 20;

    var topPosition = (isFirstButton == true) ? 20 : 10;

    isFirstButton = false;

    var view = Titanium.UI.createView({
        borderRadius: 5,
        layout: 'horizontal',
        top: topPosition,
        left: viewLeft,
        width: viewWidth,
        height: 40,
        backgroundColor: eventData.styles.button_background
    });

    view.add(icon);
    view.add(button);

    if (item.controller) {
        button.addEventListener('click', function () {
            var window = Alloy.createController(item.controller).getView();

            if (Titanium.Platform.osname == 'android') {
                window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(window, { animated:true });
            }
        });
    }
    else if (item.onClick) {
        button.addEventListener('click', item.onClick);
    } else if (item.window) {
        button.addEventListener('click', function () {

            if (Titanium.Platform.osname == 'android') {
                item.window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(item.window, { animated:true });
            }
        });
    }

    $.eventView.add(view);
}

function initEventLayout() {
	var event 		= eventData,
		height 		= toDP(Ti.Platform.displayCaps.platformHeight),
		width 		= toDP(Ti.Platform.displayCaps.platformWidth),
		logoHeight	= 0,
		blob 		= null;

	var headerHeight = 60;

	blob = eventData.logoImageView.toBlob();
    if (blob) {

    	logoHeight = (width - 40) * pxToDP(blob.height) / pxToDP(blob.width);

        eventData.logoImageView.setWidth( width - 40);
        eventData.logoImageView.setHeight( logoHeight);
    }

	if (event.tabs_order.length > 0) {
		$.eventScrollView.setHeight(
			height - logoHeight - 120 - headerHeight
		);

		$.tabContainer.setBackgroundColor(event.styles.tab_background);
	} else {
		$.eventScrollView.setHeight(
			height - logoHeight - 40 - headerHeight
		);

		$.tabContainer.hide();
	}

	$.eventScrollView.setTop( logoHeight + 40 );
}

var fistButtonAdded = false;

function addEventTabItem(item, tabButtonQuantity) {
    item = ui.processItemConfig(item, eventData);

	var width = Math.floor(toDP(Ti.Platform.displayCaps.platformWidth) /  tabButtonQuantity) - (tabButtonQuantity - 1);

	var button = Titanium.UI.createView({
		layout: 'vertical',
        width: width,
        height: 80,
        backgroundColor: 'transparent',
        borderColor: 'transparent',
        borderWidth: 0
    });

    var icon = Ti.UI.createImageView({
        image: '/icons' + item.icon,
        width: 30,
        height: 30,
        top: 15
    });

    var view = Titanium.UI.createView({
        layout: 'composite',
        top: 0,
        width: '100%',
        height: Ti.UI.SIZE,
        backgroundColor: 'transparent'
    });

    var label = Ti.UI.createLabel({
    	text: item.label,
    	width: '100%',
    	textAlign: 'center',
    	color: eventData.styles.tab_forecolor,
    	top: 5,
    	font: {
    		fontSize: 12
    	}
    });

    view.add(icon);

    button.add(view);
    button.add(label);

    if (item.controller) {
        button.addEventListener('click', function () {
            var window = Alloy.createController(item.controller).getView();

            if (Titanium.Platform.osname == 'android') {
                window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(window, { animated:true });
            }
        });
    }
    else if (item.onClick) {
        button.addEventListener('click', item.onClick);
    } else if (item.window) {
        button.addEventListener('click', function () {

            if (Titanium.Platform.osname == 'android') {
                item.window.open({
                    modal: true
                });
            } else {
                $.eventNavigationWindow.openWindow(item.window, { animated:true });
            }
        });
    }

    if (fistButtonAdded) {
    	var line = Titanium.UI.createView({
			layout: 'vertical',
	        width: 1,
	        top: 5,
	        height: 70,
	        backgroundColor: '#eeeeee',
	    });

	    $.tabContainer.add(line);
    }

    fistButtonAdded = true;

    $.tabContainer.add(button);
}

function toDP(dp) {
    if (Titanium.Platform.osname == 'android') {
        return pxToDP(dp);
    }

    return dp;
}

function pxToDP(px) {
    return (px / (Titanium.Platform.displayCaps.dpi / 160));
}

// Event UI reusable functions
function createEventWindow(title, backgroundColor) {
    return Titanium.UI.createWindow({
        backgroundColor: backgroundColor,
        layout: 'vertical',
        title: title
    });
}

function searchItem(items, id) {
    var item = null;

    for (var i in items) {
        if (typeof items[i] != 'object') {
            continue;
        } else if (isNaN(parseInt(i))) {
            item = searchItem(items[i], id);

            if (item) {
                return item;
            }
        } else {
            if ((items[i].id) && (items[i].id == id)) {
                return items[i];
            }
        }
    }

    return null;
}
<|endoftext|>


<commit_before>function entrar(e) {
    var url = "http://sheltered-mesa-1621.herokuapp.com/api/sessions";
    var json;
    var xhr = Ti.Network.createHTTPClient({
    	onload: function(e){
    		json = JSON.parse(this.responseText);
    		Ti.App.Properties.setString('token', json.token);
    		alert(json.token);
    	},
    	onerror: function(e){
    		alert('error');
    	},
    	timeout:5000
    });
    xhr.open('POST',url);
    xhr.send({
    	email: $.username.getValue(),
    	password: $.password.getValue()
    });
}

function username_focus(e) {
    $.username.setBorderColor("#ffae00");
}

function username_blur(e) {
    $.username.setBorderColor("#aaa");
}

function password_focus(e) {
    $.password.setBorderColor("#ffae00");
}

function password_blur(e) {
    $.password.setBorderColor("#aaa");
}

$.index.open();
<commit_msg>namechange<commit_after>function entrar(e) {
    var url = "http://sheltered-mesa-1621.herokuapp.com/api/sessions";
    var json;
    var xhr = Ti.Network.createHTTPClient({
    	onload: function(e){
    		json = JSON.parse(this.responseText);
    		Ti.App.Properties.setString('token', json.token);
    		alert(json.token);
    	},
    	onerror: function(e){
    		alert('error');
    	},
    	timeout:5000
    });
    xhr.open('POST',url);
    xhr.send({
    	email: $.username.getValue(),
    	password: $.password.getValue()
    });
}

function username_focus(e) {
    $.username.setBorderColor("#ffae00");
}

function username_blur(e) {
    $.username.setBorderColor("#aaa");
}

function password_focus(e) {
    $.password.setBorderColor("#ffae00");
}

function password_blur(e) {
    $.password.setBorderColor("#aaa");
}

$.login.open();
<|endoftext|>


<commit_before>var movieApp = angular.module('movieApp', ['MovieModel']);

// Index: http://localhost/views/recipe/index.html

movieApp.controller('IndexCtrl', function ($scope, MovieRestangular) {

  // Helper function for opening new webviews
  $scope.open = function() {
    webView = new steroids.views.WebView("/views/recipe/index.html");
    steroids.layers.push(webView);
  };

  // Fetch all objects from the local JSON (see app/models/recipe.js)
  RecipeRestangular.all('movie').getList().then(function(movies){
    $scope.movies = movies;
  });

  // -- Native navigation
  steroids.view.navigationBar.show("Moviesss");

});<commit_msg>stuff<commit_after>var movieApp = angular.module('movieApp', ['MovieModel']);

// Index: http://localhost/views/recipe/index.html

movieApp.controller('IndexCtrl', function ($scope, MovieRestangular) {

  // Helper function for opening new webviews
  $scope.open = function() {
    webView = new steroids.views.WebView("/views/recipe/index.html");
    steroids.layers.push(webView);
  };

  // Fetch all objects from the local JSON (see app/models/recipe.js)
MovieRestangular.all('movie').getList().then(function(movies){
    $scope.movies = movies;
  });

  // -- Native navigation
  steroids.view.navigationBar.show("Moviesss");

});<|endoftext|>


<commit_before>/*jslint node: true */

'use strict';

var async = require('async');
var request = require('request');
var provider = require('../services/provider');
var torrent = require('../services/torrent');

exports.index = function (req, res, next) {
    var current = Number(req.params.page || 1);
    request
        .get({
            url: provider.movie('list_movies.json'),
            json: true,
            qs: {
                page: current,
                sort_by: 'download_count',
                order_by: 'desc'
            }
        }, function (err, response, body) {
            if (err)
                return next(err);

            var data = body.data;
            var movies = data.movies;
            var total_pages = Math.round(data.movie_count / data.limit);
            var pagination = [];
            var total_pagination = current + data.limit;

            for (var i = current; i < total_pagination; i++) {
                if (i < total_pages)
                    pagination.push('/movies/' + i);
            }

            return res.render('dashboard/index', {
                movies: movies,
                pagination: pagination,
                current: current
            });
        });
};

exports.show = function (req, res, next) {
    var movie_id = req.params.id;

    async.parallel({
        movie: function (cb) {
            request
                .get({
                    url: provider.movie('movie_details.json'),
                    json: true,
                    qs: {
                        movie_id: movie_id,
                        with_images: true,
                        with_cast: true
                    }
                }, function (err, response, body) {
                    if (err)
                        return cb(err);

                    return cb(null, body.data)
                });
        },
        comments: function (cb) {
            request
                .get({
                    url: provider.movie('movie_comments.json'),
                    json: true,
                    qs: {
                        movie_id: movie_id
                    }
                }, function (err, response, body) {
                    if (err)
                        return cb(err);
                    var data = body.data;
                    return cb(null, {
                        list: data.comments,
                        count: data.comment_count
                    });
                });
        },
        suggestions: function (cb) {
            request
                .get({
                    url: provider.movie('movie_suggestions.json'),
                    json: true,
                    qs: {
                        movie_id: movie_id
                    }
                }, function (err, response, body) {
                    if (err)
                        return cb(err);

                    return cb(null, body.data.movie_suggestions);
                });
        }
    }, function (err, results) {
        if (err)
            return next(err);

        var template = 'movie/stream';
        var movie = results.movie;
        var tor = movie.torrents[0];
        var magnet = torrent.magnetize({
            name: movie.title_long,
            hash: tor.hash
        });

        var dataRender = {
            title: movie.title,
            synopsis: movie.description_full,
            poster: movie.images.large_screenshot_image1,
            magnet: magnet,
            rating: movie.rating,
            comments: results.comments,
            suggestions: results.suggestions,
            peers: tor.peers,
            seeds: tor.seeds,
            ratio: (tor.seeds / tor.peers)
        }

        request
            .get({
                url: provider.subtitles().url + movie.imdb_code,
                json: true
            }, function (err, response, body) {
                if (!err && response.statusCode === 200 && !!body && body.success) {
                    dataRender.subs = body.subs;
                    return res.render(template, dataRender);
                }

                request
                    .get({
                        url: provider.subtitles().mirrorUrl + movie.imdb_code,
                        json: true
                    }, function (err, response, body) {
                        if (err || response.statusCode >= 400 || !body || !body.success) {
                            return next(err);
                        }

                        dataRender.subs = body.subs;
                        return res.render(template, dataRender);
                    });
            });
    });
};<commit_msg>added redis movies<commit_after>/*jslint node: true */

'use strict';

var async = require('async');
var request = require('request');
var provider = require('../services/provider');
var torrent = require('../services/torrent');
var redis = require('../services/redis');
var client = redis.getClient();

var _renderMovies = function (res, current, data) {
    var movies = data.movies;
    var total_pages = Math.round(data.movie_count / data.limit);
    var total_pagination = current + data.limit;

    var pagination = [];
    for (var i = current; i < total_pagination; i++) {
        if (i < total_pages)
            pagination.push('/movies/' + i);
    }

    return res.render('dashboard/index', {
        movies: movies,
        pagination: pagination,
        current: current
    });
}

exports.index = function (req, res, next) {
    var current = Number(req.params.page || 1);
    var key = 'movies-' + current;
    client.get(key, function (err, data) {
        if (err)
            return next(err);

        if (data)
            return _renderMovies(res, current, JSON.parse(data));

        request
            .get({
                url: provider.movie('list_movies.json'),
                json: true,
                qs: {
                    page: current,
                    sort_by: 'download_count',
                    order_by: 'desc'
                }
            }, function (err, response, body) {
                if (err)
                    return next(err);

                var data = body.data;
                client.set(key, JSON.stringify(data));
                client.expire(key, (5 * 60));

                return _renderMovies(res, current, data);
            });
    });
};

exports.show = function (req, res, next) {
    var movie_id = req.params.id;

    async.parallel({
        movie: function (cb) {
            request
                .get({
                    url: provider.movie('movie_details.json'),
                    json: true,
                    qs: {
                        movie_id: movie_id,
                        with_images: true,
                        with_cast: true
                    }
                }, function (err, response, body) {
                    if (err)
                        return cb(err);

                    return cb(null, body.data)
                });
        },
        comments: function (cb) {
            request
                .get({
                    url: provider.movie('movie_comments.json'),
                    json: true,
                    qs: {
                        movie_id: movie_id
                    }
                }, function (err, response, body) {
                    if (err)
                        return cb(err);
                    var data = body.data;
                    return cb(null, {
                        list: data.comments,
                        count: data.comment_count
                    });
                });
        },
        suggestions: function (cb) {
            request
                .get({
                    url: provider.movie('movie_suggestions.json'),
                    json: true,
                    qs: {
                        movie_id: movie_id
                    }
                }, function (err, response, body) {
                    if (err)
                        return cb(err);

                    return cb(null, body.data.movie_suggestions);
                });
        }
    }, function (err, results) {
        if (err)
            return next(err);

        var template = 'movie/stream';
        var movie = results.movie;
        var tor = movie.torrents[0];
        var magnet = torrent.magnetize({
            name: movie.title_long,
            hash: tor.hash
        });

        var dataRender = {
            title: movie.title,
            synopsis: movie.description_full,
            poster: movie.images.large_screenshot_image1,
            magnet: magnet,
            rating: movie.rating,
            comments: results.comments,
            suggestions: results.suggestions,
            peers: tor.peers,
            seeds: tor.seeds,
            ratio: (tor.seeds / tor.peers)
        }

        request
            .get({
                url: provider.subtitles().url + movie.imdb_code,
                json: true
            }, function (err, response, body) {
                if (!err && response.statusCode === 200 && !!body && body.success) {
                    dataRender.subs = body.subs;
                    return res.render(template, dataRender);
                }

                request
                    .get({
                        url: provider.subtitles().mirrorUrl + movie.imdb_code,
                        json: true
                    }, function (err, response, body) {
                        if (err || response.statusCode >= 400 || !body || !body.success) {
                            return next(err);
                        }

                        dataRender.subs = body.subs;
                        return res.render(template, dataRender);
                    });
            });
    });
};<|endoftext|>


<commit_before>var Middleware = require('../middleware/middleware');
var Routing    = require('./routing');
var routes     = require('../config/routes');

var Requester = {

  /**
  * Init Default object for routing
  */
  initDefault: function(defaults) {
    this.defaults = defaults;
  },

  /**
  * Create a new route
  * @params router Object Express router object
  * @params path   String route path
  * @params route  Object route infos (method, action, controller etc...)
  * @params io     Object Socket.io object
  */
  createRoute: function(router, path, route, io) {
    // Init the route object
    if (!this.defaults)
      this.defaults = {};

    this.route = this.initRoute(path, route);

    this.initRouter(router, this.route, io);
  },

  initRoute: function(path, route) {

    // Adding path in route object
    route.path = path;

    // Set the method
    route.method = this.initMethod(route.method);

    // Set controller
    route.controller = this.initController(route.controller, route.action);

    // Set middlewares
    route.middlewares = this.initMiddleware(route.middlewares, route.auth);

    return route;
  },

  initMiddleware: function(middlewares, auth) {
    // If there is middlewares
    if (middlewares) {
      // Foreach middleware we push it in middlewares
      for (m in middlewares) {
          middlewares[m] = Middleware[middlewares[m]];
      }
    }
    else if (this.defaults.middlewares) {
      var middlewares = [];
      for (m in this.defaults.middlewares) {
          middlewares[m] = Middleware[this.defaults.middlewares[m]];
      }
    }else
      middlewares = [];

    // Check auth middleware
    if(auth)
      middlewares.unshift(Middleware['auth']);

    return middlewares;
  },

  /**
  * Set the controller
  * @return null || controller object
  */
  initController: function(controller, action) {
    // If action is a function there is no controller
    if (typeof action == 'function') {
      return null;
    }
    else {
      // If there is a controller return the module
      if (controller) {
        return require('../controllers/' + controller);

      // If there is a default controller
      }
      else if (this.defaults.controller) {
        return require('../controllers/' + this.defaults.controller);

      // No controller
      }
      else {
        return null;
      }
    }
  },

  /**
  * Set the method
  * @return String the method
  */
  initMethod: function(method) {
    if (method) {
      method = method.toLowerCase();
      if (['get', 'post', 'put', 'delete'].indexOf(method) > -1)
        return method;
    }
    else if (this.defaults.method) {
      return this.defaults.method.toLowerCase();
    }

    // default
    return 'get';

  },

  /**
  * Create a new Express Router instance
  */
  initRouter: function(router, route, io) {
    Routing(router, route, io);
  }
};

module.exports = function(router, io) {

  if (routes['default'])
    Requester.initDefault(routes['default']);

  for (var r in routes) {
    if (r != 'default') {
      Requester.createRoute(router, r, routes[r], io);
    }
  }

  router.all('*', function(req, res, next) {
    res.status(404).send({status: 404, message: 'No ressources find. Please read the doc.'});
  });
};
<commit_msg>add default auth<commit_after>var Middleware = require('../middleware/middleware');
var Routing    = require('./routing');
var routes     = require('../config/routes');

var Requester = {

  /**
  * Init Default object for routing
  */
  initDefault: function(defaults) {
    this.defaults = defaults;
  },

  /**
  * Create a new route
  * @params router Object Express router object
  * @params path   String route path
  * @params route  Object route infos (method, action, controller etc...)
  * @params io     Object Socket.io object
  */
  createRoute: function(router, path, route, io) {
    // Init the route object
    if (!this.defaults)
      this.defaults = {};

    this.route = this.initRoute(path, route);

    this.initRouter(router, this.route, io);
  },

  initRoute: function(path, route) {

    // Adding path in route object
    route.path = path;

    // Set the method
    route.method = this.initMethod(route.method);

    // Set controller
    route.controller = this.initController(route.controller, route.action);

    // Set middlewares
    route.middlewares = this.initMiddleware(route.middlewares, route.auth);

    return route;
  },

  initMiddleware: function(middlewares, auth) {
    // If there is middlewares
    if (middlewares) {
      // Foreach middleware we push it in middlewares
      for (m in middlewares) {
          middlewares[m] = Middleware[middlewares[m]];
      }
    }
    else if (this.defaults.middlewares) {
      var middlewares = [];
      for (m in this.defaults.middlewares) {
          middlewares[m] = Middleware[this.defaults.middlewares[m]];
      }
    }else
      middlewares = [];

    // Check auth middleware
    if(auth)
      middlewares.unshift(Middleware['auth']);
    else if (this.defaults.auth === true && auth !== false)
      middlewares.unshift(Middleware['auth']);

    return middlewares;
  },

  /**
  * Set the controller
  * @return null || controller object
  */
  initController: function(controller, action) {
    // If action is a function there is no controller
    if (typeof action == 'function') {
      return null;
    }
    else {
      // If there is a controller return the module
      if (controller) {
        return require('../controllers/' + controller);
      }
      // If there is a default controller
      else if (this.defaults.controller) {
        return require('../controllers/' + this.defaults.controller);
      }
      // No controller
      else {
        return null;
      }
    }
  },

  /**
  * Set the method
  * @return String the method
  */
  initMethod: function(method) {
    if (method) {
      method = method.toLowerCase();
      if (['get', 'post', 'put', 'delete'].indexOf(method) > -1)
        return method;
    }
    else if (this.defaults.method) {
      return this.defaults.method.toLowerCase();
    }

    // Default
    return 'get';

  },

  /**
  * Create a new Express Router instance
  */
  initRouter: function(router, route, io) {
    Routing(router, route, io);
  }
};

module.exports = function(router, io) {

  if (routes['default'])
    Requester.initDefault(routes['default']);

  for (var r in routes) {
    if (r != 'default')
      Requester.createRoute(router, r, routes[r], io);
  }

  router.all('*', function(req, res, next) {
    res.status(404).send({status: 404, message: 'No ressources find. Please read the doc.'});
  });
};
<|endoftext|>


<commit_before>chatApp.controller('ChatController', ['$scope',	'$location', 'ChatService', 'MessagesObserver',
	function ($scope, $location, ChatService, MessagesObserver) {

		// Authenticated?
		if (!ChatService.authenticatedUser)
			return $location.path("/login");

		$scope.currentUser = ChatService.authenticatedUser;
		$scope.users = [];
		$scope.chats = [];
		$scope.selectedChat = null;
		$scope.selectedUser = null;

		$scope.selectUser = function (user) {
			$scope.selectedUser = user;
			$scope.selectedChat = $scope.openChat($scope.currentUser, user);
		};

		$scope.openChat = function (sender, recipient) {

			if (!sender || !recipient || recipient.muted)
				return null;

			var chat = $scope.findChat(sender, recipient);

			// Create a new chat if it doesn't exist
			if (!chat) {
				chat = {
					sender : sender,
					recipient : recipient,
					messages : [],
					lastMessageReceived : null,
					recieveMessage : function (message) {
						console.log('Chat recieves message: ' + message.id);

						var lastMessage = _.last(chat.messages);

						// First message or newest message
						if (chat.messages.length === 0 || lastMessage.id < message.id) {
							chat.messages.push(message);
							return;
						}

						// Ensure messages are sorted chronological
						for (var i = 0; i < chat.messages.length; i++) {
							var currentMessage = chat.messages[i];

							// Allready got the message
							if (currentMessage.id === message.id)
								return;

							if (message.id < currentMessage.id) {
								// Add message before currentMessage
								chat.messages.splice(i, 0, message);
								return;
							}
						}
					}
				};

				// Subscribe to messages observer
				MessagesObserver.subscribe(chat, chat.recipient.name, chat.sender.name, chat.recieveMessage);
				MessagesObserver.subscribe(chat, chat.sender.name, chat.recipient.name, chat.recieveMessage);

				$scope.chats.push(chat);
			}

			// Reset user's new messsages list
			chat.recipient.newMessages = null;

			$scope.selectedChat = chat;

			return chat;
		};

		$scope.closeChat = function (chat) {
			$scope.chats = _.without($scope.chats, chat);

			// Unsubscribe from messages observer
			MessagesObserver.unsubscribe(chat, chat.recipient.name, $scope.currentUser.name);
			MessagesObserver.unsubscribe(chat, $scope.currentUser.name, chat.recipient.name);

			if ($scope.selectedChat === chat) {
				// Set selection to first chat's user
				var firstChat = $scope.chats[0],
					user = firstChat ? firstChat.user : null;

				$scope.selectUser(user);
			}
		};

		$scope.sendMessage = function (chat, text) {
			if (!chat)
				return;

			ChatService.sendMessage(chat.recipient, text);
		};

		$scope.toggleMute = function (user) {
			user.muted = !user.muted;

			// if user gets muted, close its chat
			if (user.muted) {
				$scope.closeChat($scope.findChat($scope.currentUser, user));
			}
		};

		$scope.findUser = function (name) {
			return _.find($scope.users, function (user) { return user.name === name; });
		};

		$scope.findChat = function (sender, recipient) {
			return _.find($scope.chats, function (chat) { return chat.sender === sender && chat.recipient === recipient; });
		};

		$scope.logout = function () {

			destroy();

			$location.path("/login");
		};

		function addUser(user) {
			// Don't add me
			if (user.name === $scope.currentUser.name)
				return;

			$scope.users.push(user);
		}

		function recieveMessage(message) {
			var sender = $scope.findUser(message.sender),
				selectedUser = $scope.selectedUser;

			// If message is new, add it to the user's newMessages
			if (!sender.lastMessageReceived || sender.lastMessageReceived.id < message.id) {

				// Only update newMessages when sender is not selectedUser
				if (!selectedUser || sender.name !== selectedUser.name) {

					if (!sender.newMessages)
						sender.newMessages = [];

					sender.newMessages.push(message);
				}

				// Update
				sender.lastMessageReceived = message;
			}
		}

		function init() {
			ChatService.getUsers()
				.success(function (users) {
					_.each(users, addUser);

					// Subscribe to messages observer
					MessagesObserver.subscribe(this, undefined, $scope.currentUser.name, recieveMessage);
				});
		}

		function destroy() {
			// Close all chats
			_.each($scope.chats, function (chat) { $scope.closeChat(chat); });

			// Unsubscribe
			MessagesObserver.unsubscribe(this, undefined, $scope.currentUser.name);

			ChatService.logout();
		}

		init();
    }
]);<commit_msg>Minor changes<commit_after>chatApp.controller('ChatController', ['$scope',	'$location', 'ChatService', 'MessagesObserver',
	function ($scope, $location, ChatService, MessagesObserver) {

		// Authenticated?
		if (!ChatService.authenticatedUser)
			return $location.path("/login");

		$scope.currentUser = ChatService.authenticatedUser;
		$scope.users = [];
		$scope.chats = [];
		$scope.selectedChat = null;
		$scope.selectedUser = null;

		$scope.selectUser = function (user) {
			$scope.selectedUser = user;
			$scope.selectedChat = $scope.openChat($scope.currentUser, user);
		};

		$scope.openChat = function (sender, recipient) {

			if (!sender || !recipient || recipient.muted)
				return null;

			var chat = $scope.findChat(sender, recipient);

			// Create a new chat if it doesn't exist
			if (!chat) {
				chat = {
					sender : sender,
					recipient : recipient,
					messages : [],
					lastMessageReceived : null,
					recieveMessage : function (message) {
						console.log('Chat recieves message: ' + message.id);

						var lastMessage = _.last(chat.messages);

						// First message or newest message
						if (chat.messages.length === 0 || lastMessage.id < message.id) {
							chat.messages.push(message);
							return;
						}

						// Ensure messages are sorted chronological
						for (var i = 0; i < chat.messages.length; i++) {
							var currentMessage = chat.messages[i];

							// Allready got the message
							if (currentMessage.id === message.id)
								return;

							if (message.id < currentMessage.id) {
								// Add message before currentMessage
								chat.messages.splice(i, 0, message);
								return;
							}
						}
					}
				};

				// Subscribe to messages observer
				MessagesObserver.subscribe(chat, chat.recipient.name, chat.sender.name, chat.recieveMessage);
				MessagesObserver.subscribe(chat, chat.sender.name, chat.recipient.name, chat.recieveMessage);

				$scope.chats.push(chat);
			}

			// Reset user's new messsages list
			chat.recipient.newMessages = null;

			$scope.selectedChat = chat;

			return chat;
		};

		$scope.closeChat = function (chat) {
			$scope.chats = _.without($scope.chats, chat);

			// Unsubscribe from messages observer
			MessagesObserver.unsubscribe(chat, chat.recipient.name, $scope.currentUser.name);
			MessagesObserver.unsubscribe(chat, $scope.currentUser.name, chat.recipient.name);

			if ($scope.selectedChat === chat) {
				// Set selection to first chat's user
				var firstChat = $scope.chats[0],
					user = firstChat ? firstChat.user : null;

				$scope.selectUser(user);
			}
		};

		$scope.sendMessage = function (chat, text) {
			if (!chat)
				return;

			ChatService.sendMessage(chat.recipient, text);
		};

		$scope.toggleMute = function (user) {
			var chat = $scope.findChat($scope.currentUser, user);

			user.muted = !user.muted;

			// if user gets muted, close its chat
			if (user.muted && chat) {
				$scope.closeChat(chat);
			}
		};

		$scope.findUser = function (name) {
			return _.find($scope.users, function (user) { return user.name === name; });
		};

		$scope.findChat = function (sender, recipient) {
			return _.find($scope.chats, function (chat) { return chat.sender === sender && chat.recipient === recipient; });
		};

		$scope.logout = function () {

			destroy();

			$location.path("/login");
		};

		function addUser(user) {
			// Don't add me
			if (user.name === $scope.currentUser.name)
				return;

			$scope.users.push(user);
		}

		function recieveMessage(message) {
			var sender = $scope.findUser(message.sender),
				selectedUser = $scope.selectedUser;

			// If message is new, add it to the user's newMessages
			if (!sender.lastMessageReceived || sender.lastMessageReceived.id < message.id) {

				// Only update newMessages when sender is not selectedUser
				if (!selectedUser || sender.name !== selectedUser.name) {

					if (!sender.newMessages)
						sender.newMessages = [];

					sender.newMessages.push(message);
				}

				// Update
				sender.lastMessageReceived = message;
			}
		}

		function init() {
			ChatService.getUsers()
				.success(function (users) {
					_.each(users, addUser);

					// Subscribe to messages observer
					MessagesObserver.subscribe(this, undefined, $scope.currentUser.name, recieveMessage);
				});
		}

		function destroy() {
			// Close all chats
			_.each($scope.chats, function (chat) { $scope.closeChat(chat); });

			// Unsubscribe
			MessagesObserver.unsubscribe(this, undefined, $scope.currentUser.name);

			ChatService.logout();
		}

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