/*global jQuery */
(function($) {
    
    function propertyName(row) {
        var property = row.data("property");
        var result;
        if (property.label() != property.name()) {
            result = $("<span class='changed'>" + property.label()  + "</span>");
        } else {
            result = $("<span>" + property.name() + "</span>");        
        }
        return result;
    }
    
    
    $.freemix.prototypes.identify =$.extend({}, $.freemix.prototypes.identify, {
        initialize: function(database) {
            
            var props = $.freemix.property.propertyList;
            
            var table = this.getContent();
            var footer = $(".table-footer", table);
            footer.prevAll().remove();
            var identify = this;
            $.each(props, function(name, property) {
                var row = $("<tr class='property-row'></tr>").data("property", property);                           
                footer.before(row);
                
                $("<td class='enabled'></td>").appendTo(row).createChildCheck({
                    checked: property.enabled(), 
                    enabled: function() {return identify.editor;},
                    change: function() {
                        property.enabled($(this).is(":checked"));
                        identify.propertyChanged(property.config);
                    }
                });

                $("<td class='name'></td>").append(propertyName(row)).appendTo(row);   
                // Multi-Select requires that it's target is in the DOM
                var typeList = identify.createTypeList(row, $("<td class='types'></td>").appendTo(row) );       
                $("<td class='value'></td>").appendTo(row);     
                if (identify.editor) {
                    identify.makeEditable(row);
                }
                identify.updateTypeList(row);
            });
                
            $this = this;
            footer.find("#left-record-button").unbind().freemixButton(function() {
                $this.previousRecord();
                $this.populateRecordDisplay();                
            });
            footer.find("#right-record-button").unbind().freemixButton(function() {    
                $this.nextRecord();
                $this.populateRecordDisplay();
            });
            this.setCurrentRecord(0);
            this.populateRecordDisplay();

        },
        // Set the record number.
    	setCurrentRecord: function (record_num) {
    		var size = $.exhibit.database.getAllItemsCount();
    		var num = (record_num + size) % size;
    		this.getContent().data("record_num", num);
    		return num;
    	},
    	getCurrentRecord: function () {
    		var record_num = this.getContent().data("record_num");
    		if (!record_num) {
    			record_num = this.setCurrentRecord(0);
    		}
    		return record_num;
    	},
    	nextRecord: function () {
    		var next = this.getCurrentRecord()+1;
    		this.setCurrentRecord(next);
    	},
    	previousRecord: function () {
    		var previous = this.getCurrentRecord()-1;
    		this.setCurrentRecord(previous);
    	},
    	getContent: function() {
    	    if (!this._content) {
    	        this._content = $("#identify-table");
    	    }
    	    return this._content;
    	},
    	populateRecordDisplay: function () {

    		var content = this.getContent();
				
    		var record_num = this.getCurrentRecord();
            var database = $.exhibit.database;
     		var num_records = database.getAllItemsCount();			
            var recordIds = database.getAllItems();
    		var id = recordIds.toArray()[record_num];
    		var record = database.getItem(id);

    		content.find("#current-record").html(record_num+1);
    		content.find("#record-count").html(num_records);
            var identify = this;
            $("tr.property-row", content).each(function() {
                var row = $(this);
                identify.renderProperty(row);         
            });
            
    		// Read in the current record.
            // content.find("#record-header").text(record.label);
    	},
    	renderProperty: function(row) {    	    
    		var record_num = this.getCurrentRecord();      		  		
            var database = $.exhibit.database;    
            var recordIds = database.getAllItems();
    		var id = recordIds.toArray()[record_num];        
    		var record = database.getItem(id);    		
            var property = row.data("property");
            var value = record[property.name()];
            var result;
            
            if (!value) {
                result = "<em>No Value</em>";
            } else {
                var type = property.defaultType();
                if (!type) {
                    var types = property.listTypes();
                    if (types.length > 0) {
                        type = types[0];
                    } else {
                        type = "text";
                    }
                }      
                result = $.freemix.property.type[type].getValueHtml(property,value);
            } 
            row.find(".value").empty().append(result);
    	},
        updateTypeList: function(row) {
            var identify = this;
            var property = row.data("property");
            var list = row.find("ul.identify-type-list");    
            list.empty();
            var types = property.listTypes();
            $.each(types, function() {
                var label = $.freemix.property.type[this].label || this;
                if (this == property.defaultType()) {
                    label = "<em>" + label + "</em>";
                }
                if (identify.editor) {
                    
                    var li = $("<li><a href='#' class='identify-type-selector' id='" + this + "'>" + label + "</a></li>");
                    li.find("a").click(function() {
                        var type = $(this).attr("id");
                        property.defaultType(type);
                        identify.updateTypeList(row);
                        identify.renderProperty(row);
                        identify.propertyChanged(property.config);
                        return false; 
                    });
                } else {
                    li = $("<li><span id ='" + this + "'>"+ label + "</span></li");
                }
                list.append(li);
            });
        },    
        createTypeList: function(row, column) {
            var identify = this;
            var list = $("<div><ul class='identify-type-list'></ul></div>").appendTo(column);
            if (identify.editor) {
                identify.makeTypeListEditable(list, row);
            }
  
            return list;
        },    
        propertyChanged: function(property) {
            if ($.freemix.profile.localProperties) {
                $.freemix.profile.localProperties[property.property] = property;
            }
        }
    });
})(jQuery);
