﻿StopsFilter = createSingleton(StopsFilter = {});

StopsFilter.prototype.init = function(args) {
     /*
        preset          : Preset values to be used 
		onChange		: Handler to be invoked on-change
		list			: List minimum fares grouped-by stops
    */

	if(!isDefined(args))
		args = {};
	defaults = { preset: {}, onChange: null, fareList: null, parentDiv: "FilterDiv" };
	for(var pr in defaults)
		this[pr] = isDefined(args[pr]) ?args[pr] :defaults[pr];
    var filter = this;
    
    // Method for updating checked status list
    this.updateCheckedList = function() {
	    var num;
	    for(var i=0; i<this.list.length; i++) {
		    num = this.list[i].get('stops');
		    num = this.abs(num);
		    if(!isDefined(this.checked[num]))
			    this.checked[num] = true; 
	    }
    };
	
	// Method to absolute a value to a maximum of 2
	this.abs = function(s) {
	    return (s > 2) ?2 :s;
	};
	
	// Get count of the required rows for airlines
	this.getRowsCnt = function() {
		var reqCnt = (this.list.length >= 3) ?3 :this.list.length;
		var actualCnt = 0;
		if(isArray(this.domMgr.elements["cols"])) 
			actualCnt = this.domMgr.elements["cols"].length;
		return { 'req': reqCnt, 'actual': actualCnt };
	};

    // Get check status for Airline-code
	this.getCheckStatus = function(c) {
		return this.checked[this.abs(c)];
	};

    // Set check status for Airline-code
	this.setCheckStatus = function(s, b) {
		this.checked[this.abs(s)] = b;
		if(this.onChange)
			this.onChange(this);
	};

    // Method for validating fare to be displayed
    this.isValidFare = function(fare) {
	    return this.checked[this.abs(fare.get('stops'))];
    };
	
	// Sort list of fares
	this.sortList = function() {
        this.list.sort(function(f1, f2) {
            return f1.get('stops') - f2.get('stops');
        });
	};
	
	// Reset filter
	this.reset = function(list)
	{
	    this.list = convertToArr(list);
	    this.checked = {};
        this.update();
    };            
    
  	// Update the filter
  	this.update = function() {
  	    this.sortList();

  	    var plus2 = false;
  	    var arr = new Array();
  	    for(var i=0; i<this.list.length; i++) {
  	        if(this.list[i].get('stops') >= 2) {
  	            if(!plus2) {
  	                plus2 = true;
                    arr.push(this.list[i]);
                }
            }
            else
                arr.push(this.list[i]);
  	    }  	        
  	    this.list = arr;
  	    
  	    this.updateCheckedList();
	    this.domMgr.update(false);
    };
        
    this.hide = function() {
        $(this.parentDiv).style.display = "none";        
    };

    this.show = function() {
        $(this.parentDiv).style.display = "";        
    };
        
	var c = {};
	var row = {
        tagName: "div",	
        name: "cols",    
        cssClass: "col",
        style: { width: "100px" },
        updateFunc: function(el, mgr) {
	        if(mgr.indices.row < c.req) {
	            var num = filter.list[mgr.indices.row].get('stops');
	            var chkBox = "<input type='checkBox'/>";
	            el.innerHTML = chkBox + "<div>" + filter.captions[filter.abs(num)] + "</div>";
	            status = el.getElementsByTagName("input")[0].checked = filter.getCheckStatus(num);
	            el.style.display = "";
	            el.setAttribute("stops", filter.abs(filter.list[mgr.indices.row].get('stops'))); 
            }
            else {
                el.style.display = "none";
	            el.setAttribute("stops", ""); 
            }                
        },
	    handlers: {
		    click: function(ev, mgr) {
			    var el = DOM.getTargetElement(ev);
			    while(el && !isDefined(el.getAttribute("stops")))
				    el = el.parentNode;
			    var code = el.getAttribute("stops");
			    var status = filter.getCheckStatus(code);
			    status = !status;

			    el.getElementsByTagName("input")[0].checked = status;
			    filter.setCheckStatus(code, status);
		    }
	    }
    };
	
	var body = {
        tagName: "div",
        cssClass: "row",
	    foreach: { startIndex: 0, stopIndex: function(mgr) {
		    return (c.req > c.actual) ?c.req-1 :c.actual-1;		    
	    }, indexKey: "row" },
	    layout: row,
	    updateFunc: function(el, mgr) {
            c = filter.getRowsCnt();
            var rows = Math.ceil(c.req/2);
            el.style.height = rows*20 + "px";
		    for(var i=c.actual; i<c.req; i++) {
			    mgr.indices.row = i;
			    mgr.createLayout(row, el);
		    }
	    }    
	};
	
    this.container = new LeftFilter({ 
        caption: "No. of Stops",
        parentDiv: filter.parentDiv
    });
    
	this.layout = {
	    parent: filter.container.body, 
	    layout: body
	};
	
    this.list = convertToArr(this.fareList.get('min(total)', 'stops'));
    this.captions = [ "No Stops", "1 Stop", "2+ Stops" ];
	this.checked = {};
	
	// StopsFilter Dom-manager (manage DOM manipulation)
	this.domMgr = new DomMgr(this.layout);
	this.domMgr.create();
	this.update();
};