/**
 * Spindeln Result view
 *
 * @author    Mikael Karlsson
 * @date      13. April 2008
 * @version   $Id$
 *
 * @license spindelnResult.js is licensed under the terms of the Open Source
 * LGPL 3.0 license. 
 * 
 * License details: http://www.gnu.org/licenses/lgpl.html
 */
 
/*global Ext, Spindeln*/
var spindelnBasePath = 'http://spindeln.iml.umu.se/spindeln/';


 function spindelnSubmitenter(myfield,e)
 {
 var keycode;
 if (window.event) { 
 	keycode = window.event.keyCode;
 } else if (e) {
  keycode = e.which;
 } else {
  return true;
 }
 if (keycode == 13) {
   myfield.submit();
   return false;
 } else {
   return true;
 }
}




Ext.BLANK_IMAGE_URL = spindelnBasePath + 'ext/resources/images/default/s.gif';
Ext.ns('Spindeln');

Ext.onReady(function(){
	var refresherTask; 
	var spindelnRunner = new Ext.util.TaskRunner();

    // proxy
	var spindelnProxy = new Ext.data.ScriptTagProxy({
            url: spindelnBasePath + 'fire/result.action'
        });
  
    // create the Data Store
    var store = new Ext.data.Store({
        // load using script tags for cross domain
        proxy: spindelnProxy,

        // create reader that reads the Topic records
        reader: new Ext.data.JsonReader({
            root: 'posts',
            totalProperty: 'totalCount',
            successProperty:'success',
            fields: [
                {name:'catalog'}, 
				{name:'location'}, 
				{name:'title'}, 
				{name:'description'}, 
				{name:'ageRange'}, 
				{name:'lretypes'}, 
				{name:'langs'}
            ]
        }),
        remoteSort: true
        //autoLoad: true,
    });
    // store.setDefaultSort('lastpost', 'desc');

	// Add the HTTP parameter searchTerm to the request
	spindelnProxy.on('beforeload', function(p, params) {
    	if (typeof spindelnQueryId != 'undefined') {
    		params.id = spindelnQueryId;
    	}
    	params.totalCount = store.getTotalCount();
	});

	function getLang(string)
	{
		var langMap =[];        
		langMap["sv"] = "Svenska";
        langMap["de"] = "Tyska";
        langMap["da"] = "Danska";
        langMap["fr"] = "Franska";
        langMap["no"] = "Norska";
        langMap["es"] = "Spanska";
        langMap["en"] = "Engelska";
        langMap["it"] = "Italienska";
        langMap["is"] = "Isländska";
        langMap["ru"] = "Ryska";
        langMap["fi"] = "Finska";
        langMap["x-none"] = "-";
        langMap["none"] = "-";
        if (langMap[string] === undefined) {
        	return "-";
        } else  {
			return langMap[string];
		}
	}
    // pluggable renders
    function renderColumn1(value, p, record){
     	var langs = record.data.langs;//.split(',');
		var flags ='';
		
		for (var i = 0, len = langs.length; i < len; i++) {
			if (getLang(langs[i]) != "-") {
				flags = flags + "&nbsp;<img src=\"" + spindelnBasePath + "images/spindeln/flags/" + langs[i] + ".gif\" alt=\"" +getLang(langs[i])+ "\" />"; 
			}
		}
        var title = Ext.util.Format.ellipsis(value, 100);
     
      	var description = record.data.description; //Ext.util.Format.ellipsis(record.data.description, 500);
     	// quick bugfix, script removed from deSCRIPTion
	description = description.replace('deion ','description ');
     	var row1 = String.format('<b class="record-title"><a href="{1}" target="_blank">{0}</a>{2}</b>', title, record.data.location, flags);
//		var row2 = String.format('<span class="record-catalog">{0}</span>', record.data.catalog);
        var row3 = String.format('<p class="record-description">{0}</p>', description);
        var row4 = String.format('<span class="metakey">K&auml;lla:</span><span class="metavalue"> {0}&nbsp;&nbsp;</span><span class="metakey">Typ:</span><span class="metavalue"> {1}&nbsp;&nbsp;</span><span class="metakey">&Aring;lder:</span><span class="metavalue"> {2}</span>',record.data.catalog, record.data.lretypes, record.data.ageRange);
		var result = row1 + row3 +row4;
        return result
         
    	//var result = new Object();
		//result.title = value;
		//result.description = record.data.description;
		//result.location = record.data.location;
    	//result.catalog = record.data.catalog;
 		//   console.log(Ext.util.JSON.encode(result));
    	//t = new Ext.Template('<b><a href="{"location"}" target="_blank">{"title"}</a></b>{"catalog"}{"description":ellipsis(50)}');
    	
    	//return t.applyTemplate(Ext.util.JSON.encode(result));
        //return String.format('<b><a href="{1}" target="_blank">{0}</a></b><span>{2}</span><p>{3}</p>', value, record.data.location,record.data.catalog,Ext.util.Format.ellipsis(record.data.description, 200));
    }
    
    function renderColumn2(value, p, record){
	    var result ='';
		
		for(var i = 0, len = value.length; i < len; i++) {
			result = result + value[i] + "<br/>";  
		}	

        return result;
    }
    
	/*var expander = new Ext.grid.RowExpander({
        tpl : new Ext.Template('{description:substr(200,1000)}')
    });
	*/
	
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([
    //	expander,
    	{
           id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "S&ouml;kresultat...",
           dataIndex: 'title',
           width: 200,
           renderer: renderColumn1
        },
        {
           id: 'column2',
           header: "Typ",
           dataIndex: 'lretypes',
           width: 50,
           renderer: renderColumn2,
           hidden:true
        }]);

    // by default columns are sortable
    cm.defaultSortable = false;

	var paging = new Ext.PagingToolbar({
            pageSize: 8,
            store: store,
            displayInfo: true,
            displayMsg: 'Visar post {0} - {1} av {2}',
            emptyMsg: "V&auml;ntar p&aring; s&ouml;kresultat!",
            afterPageText:'av {0}',
			beforePageText:'Sida', 
			firstText:'F&ouml;rsta sidan',
			lastText:'Sista sidan',
			nextText:'N&auml;sta sida',
			prevText:'F&ouml;reg&aring;ende sida',
			refreshText:'Uppdatera',
            items:[
                '-'
                //, {
                //pressed: true,
                //enableToggle:true,
                //text: 'Show Preview',
                //cls: 'x-btn-text-icon details',
				//toggleHandler: toggleDetails
            	//}
            ]
        });
        
    
    //GRIDPANEL 
    var grid = new Ext.grid.GridPanel({
      	//el:'spindelnResult',
        width: 445,
        height:'100%',
      	//autoWidth:true,
        autoHeight:true,
        autoExpandColumn:'colum1',
        autoExpandMax: 230,
        autoExpandMin: 100,
        header:false,
        frame:false,  //round borders
        border:true, //display the borders of the panel's body element
        enableHdMenu:false, // enable the drop down for menu in the headers.
        stripeRows:true, 
        //baseCls : String The base CSS class to apply to this panel's element (defaults to 'x-panel'). 
        //cls: String, //own css
        //region: 'south',
        //margins:'3 3 3 3',
        //minHeight: 150,
        //autoScroll: false,
        //plugins: expander,
        title:'Spindeln s&ouml;kresultat',
        store: store,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: false,
        viewConfig: {
            forceFit:true, 
            scrollOffset: 2, //hides scrollbar, 10 default
            emptyText: 'V&auml;ntar p&aring; resultat!' /* ,
            enableRowBody:true,
            showPreview:true,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p>'+record.data.description+'</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }*/
        },
        bbar: paging
    });


	// Start a clock task that updates gride once every 2 seconds
	refresherTask = {
		run: function(){
			if (typeof spindelnQueryId != 'undefined' && spindelnQueryId != '') {
				store.reload();
			}
		},
		scope: store,
		interval: 1000,
		duration: 120000 //2 minutes
	};

	// Stop timer after 2 minutes, waited enough time for archives to answer 
	/*var stopTimerTask = {
  		run: function(){
    		stopTimer = false;
    		if (skipFirstTime) {
	        	spindelnRunner.stopAll();
        	}
    		stopTimer = true;
	     },
   		duration: 120000 //2 minutes
	}*/
	
	if(document.getElementById("spindelnResult")) {
       if (typeof spindelnQueryId != 'undefined' && spindelnQueryId !='') {
           // render grid
           grid.render('spindelnResult');

           // trigger the data store load
           store.load({params:{start:0, limit:8}});
           spindelnRunner.start(refresherTask);
           //spindelnRunner.start(stopTimerTask);
       }
    }
});

