﻿SortFares = createSingleton(SortFares = {});

SortFares.prototype.init = function(args) {
    if(!isDefined(args))
		args = {};
	defaults = { parentDiv: "SortFareDiv", mode: "total", onSelect: null };
    for(var pr in defaults)
		this[pr] = isDefined(args[pr]) ?args[pr] :defaults[pr];
    
    var sortBy = this;
    var cols = [{ caption: "Price", mode: "total", width: "80px" },
		        { caption: "Departure", mode: "deptTime", width: "133px" },
		        { caption: "Arrival", mode: "arrvTime", width: "113px" },
		        { caption: "Duration", mode: "duration", width: "122px" },
                { caption: "Fare type", mode: "fareType", width: "122px" }];
    
    // Method for handling onSelect event
    this.onBtnSelect = function(mode) {
	    if(this.onSelect)
		    this.onSelect(mode);
    };
    
    this.hide = function() {
        this.domMgr.parent.style.display = "none";        
    };

    this.show = function() {
        this.domMgr.parent.style.display = "";
    };
    
    var header = {
        tagName: "div",
        cssClass: "header",
	    layout: "<img src='images/sort-by.jpg' height='16px' width='63px' alt='Sort By' />"
	};
	
	var col = {
	    tagName: "div",
	    name: "cols",
	    cssClass: "col",
	    style: { width: function(mgr) { return cols[mgr.indices.i].width; }, 
	             borderLeftWidth: function(mgr) { return (mgr.indices.i != 0) ?"1px": "0px" } 
        },
	    attributes: { mode: function(mgr) { return cols[mgr.indices.i].mode; } },
	    layout: function(el, mgr) { 
		    var i = mgr.indices.i;
		    var btn = "<input type='radio' value='" + cols[i].mode + "' name='sortBy' " + 
		            ((cols[i].mode == sortBy.mode) ?"checked" :"") + " />";
		    el.innerHTML = btn + "&nbsp;<span>" + cols[i].caption + "</span>"; 
	    },
        updateFunc: function(el, mgr) {
		    var i = mgr.indices.i;
		    var btn = el.firstChild;
		    var mode = cols[i].mode;
		    btn.checked = (sortBy.mode == m);
	    },
	    handlers: {
		    click: function(ev, mgr) {
			    var el = DOM.getTargetElement(ev);
			    while(!(/div/i.test(el.tagName)) && el)
				    el = el.parentNode;
				el.getElementsByTagName("input")[0].checked = true;
			    sortBy.onBtnSelect(el.getAttribute("mode"));
		    }
	    }
    };
    
    var body = {
		tagName: "div",
		cssClass: "body",
		foreach: { startIndex: 0, stopIndex: cols.length-1, indexKey: "i" },
        layout: col
    };
    
    this.layout = {
        parent: sortBy.parentDiv,
        layout: {
            tagName: "div",
            cssClass: "sortBy",
            layout: [ header, body ]
        }
    };
    
    this.domMgr = new DomMgr(this.layout);
    this.domMgr.create();
};