define(['scripts/knockout-3.3.0','scripts/ACTComponent.js'], function(ko, ACTComponent) {

    function StartPageComponentViewModel(params, element) {
		this.base = new ACTComponent($(element), params);
		this.containerWidth = ko.observable(310);
		this.containerHeight = ko.observable(80);
		this.applications = ko.observableArray([]);
		this.dispSearch = ko.observable('block');
		this.showDev = ko.observable(false);
		this.showExt = ko.observable(true);
	
		this.base.onRefresh = function(obj) {
			var nRows = Math.floor(obj.Applications.length/obj.ColumnsCount);
			if (obj.Applications.length%obj.ColumnsCount>0) {
				nRows++;
			}
			this.containerWidth(obj.ColumnsCount*310);
			this.containerHeight(nRows*90);
			this.showDev(obj.ShowDev);
			this.showExt(obj.ShowExt);
			
			//this.dispSearch('none');
			addCarre = function(app, data) {
				var i = app.length;
				app[i] = data;
			};
			
			app = [];
			if (obj.ShowNew) {
				addCarre(app,{name: "New Project", backColor: "#b6d7a8", image: "images/new_project.png"});
			}
			if (obj.ShowOpen) {
				addCarre(app,{name: "Open Project", backColor: "#ea9999", image: "images/open_project.png"});
			}
			for (var i=0;i<obj.Applications.length;i++) {
				var w = obj.Applications[i];
				this.base.addCallback(w, "click", "Started", []);
				addCarre(app,{name: w.Title, description: w.Description, subtitle: w.SubTitle, click: w.click, backColor: "#cccccc", image: w.Icon, keywords: w.KeyWords.toLowerCase()});
			}

			this.applications(app);
		}.bind(this);		
		
		$('#startPageInputSearch').keyup(function () {
			var query = $('#startPageInputSearch').val().toLowerCase();
			var tab = query.split(" ");
			for (var j=0;j<this.applications().length;j++) {
				var app = this.applications()[j];
				var appElem = $($(".startPageCarre")[j])
				var ok = true;
				for (var i=0;i<tab.length;i++) {
					var s = tab[i].trim();
					if (app.keywords.indexOf(s)==-1) {
						appElem.css("display", "none");
						ok = false;
						break;
					}
				}
				if (ok) {
					appElem.css("display", "block");
				}
			}
		}.bind(this));
		
		this.base.addCallback(params.Model, "clickExt", "ExtClicked", []);
		this.base.addCallback(params.Model, "clickDev", "DevClicked", []);
		this.clickExt = params.Model.clickExt;
		this.clickDev = params.Model.clickDev;
		
		this.base.initialize();
		params.ready(true);
    }

	return {
		createViewModel: function(params, componentInfo) {
            return new StartPageComponentViewModel(params, componentInfo.element);
        }
	};

});

