/* jqGrid for osConcert                              */
/* Copyright 2011-2012 by Martin T. Zeitler, Germany */
/* globals */
var lastsel = 0,
last_expanded = 0,
lastsel_sub = 0;
/* custom formatter for HTML fields */
$.extend($.fn.fmatter,{htmlContent:function(cellval,options,rowdata){return $.jgrid.htmlEncode(cellval);}});
$.extend($.fn.fmatter.htmlContent,{unformat:function(cellval,options){return $.jgrid.htmlDecode(cellval);}});
/* custom formatter for the status dots */
$.extend($.fn.fmatter,{state:function(cellval,options,rowdata){return (cellval=='yes' ? '<img title="yes" src="includes/languages/english/images/buttons/icon_inactive.gif">':'<img title="no" src="includes/languages/english/images/buttons/icon_active.gif">');}});
$.extend($.fn.fmatter.state,{unformat:function(cellval,options,rowdata){return $(rowdata).children('img').attr('title');}});
/* detecting IE bitch */
if($.browser.msie){$.ie='_ie';}else{$.ie='';}
/* on document ready */
$(function(){
	
	if($('select#language').length > 0){
		
		$.lang_id = $('select#language :selected').attr('id');
		
		/* bind trigger on demand */
		$('select#language').on('change',function(){
			$("#concert_grid").setGridParam({
				url:'concert_details_ajax.php?mode=grid&lang='+$('select#language :selected').attr('id'),
				editurl: 'concert_details_ajax.php?mode=postback&lang='+$('select#language :selected').attr('id')
			}).trigger('reloadGrid');
		});
	}
	else {
		$.lang_id = 1;
	}
	
	$("#concert_grid").jqGrid({
		caption: "Concert Details",
		url:'concert_details_ajax.php?mode=grid'+$.ie+'&lang='+$.lang_id,
		datatype: "json",
		height: 496,
		autowidth: true,
		colNames:['ID','sort','active','Name','Heading','Description','Venue','Date','Time','Date ID',''],
		colModel:[
			{name:'ID',index:'venue_id',sortable:false,editable:true,width:35,align:'center'},
			{name:'sort',index:'sort_order',sortable:false,editable:false,hidden:true},
			{name:'active',index:'categories_status',formatter:'state',sortable:false,editable:true,edittype:'checkbox',editoptions:{value:"no:yes"}, width:60, align:'center'},
			{name:'Name',index:'categories_name',sortable:false,editable:true, width:160},
			{name:'Heading', index:'categories_heading_title',sortable:false,editable:true, width:140},
			{name:'Description', index:'categories_description',formatter:'htmlContent',sortable:false,editable:true,edittype:"textarea", editoptions:{rows:"6",cols:"50"}, width:260},
			{name:'Venue',index:'concert_venue',sortable:false,editable:true, width:150},
			{name:'Date',index:'concert_date',sortable:false,editable:true, width:120, align:'center', editoptions:{size:20, 
                  dataInit:function(el){ 
                        $(el).datepicker({dateFormat:'dd-mm-yy'}); 
                  }, 
                  defaultValue: function(){ 
                    var currentTime = new Date(); 
                    var month = parseInt(currentTime.getMonth() + 1); 
                    month = month <= 9 ? "0"+month : month; 
                    var day = currentTime.getDate(); 
                    day = day <= 9 ? "0"+day : day; 
                    var year = currentTime.getFullYear(); 
                    return year+"-"+month + "-"+day; 
                  } 
                } },
			//{name:'Date',index:'concert_date',sortable:false,editable:true, width:80, align:'center'},
			{name:'Time',index:'concert_time',sortable:false,editable:true, width:80, align:'center'},
			{name:'DateID',index:'date_id',sortable:false,editable:true, width:170, align:'center'},
			{name:'actions',fixed:true,sortable:false,resize:false,formatter:'actions',formatoptions:{keys:true,afterSave:function(){enableSort();},afterRestore:function(){enableSort();}}, width:55}
		],
		rowNum:150,
		rowList:[10,25,50,100,150,200,300,400],
		pager: '#concert_pager',
		sortname: 'sort_order',
		viewrecords: true,
		sortorder: 'asc',
		multiselect: false,
		beforeSelectRow: function(rowid, e) {
			$("#concert_grid").collapseSubGridRow(last_expanded);
		},
		ondblClickRow: function(id){
			if(id && id!==lastsel){
				if(lastsel!=0){
					$.fn.fmatter.rowactions(lastsel,'concert_grid','cancel',11);
				}
				disableSort();
				$.fn.fmatter.rowactions(id,'concert_grid','edit',11);
				lastsel=id;
			}
		},
		gridComplete: function(){
			enableSort();
		},
		serializeRowData: function(postdata){
			postdata['Description'] = encodeURIComponent(postdata['Description']);
			return postdata;
		},
		editurl: 'concert_details_ajax.php?mode=postback&lang='+$.lang_id,
		
		/* sub-grid */
		subGrid: true,
		subGridOptions: {
			"plusicon" : "ui-icon-triangle-1-e",
			"minusicon" : "ui-icon-triangle-1-s",
			"openicon" : "ui-icon-arrowreturn-1-e"
		},
		subGridRowExpanded:
			function(subgrid_id, row_id) {
				
				/* bug-fix - at most one sub-grid row expanded at a time */
				$('#concert_grid').collapseSubGridRow(last_expanded);
				last_expanded = row_id;
				
				var subgrid_table_id, pager_id;
				subgrid_table_id = subgrid_id+"_t";
				pager_id = "p_"+subgrid_table_id;
				$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table>");
				
				$("#"+subgrid_table_id).jqGrid({
					url:'concert_details_ajax.php?mode=subgrid'+$.ie+'&id='+row_id,
					datatype: "json",
					colNames: ['Color','Price','Seats','Locks','Sold'],
					colModel: [
						{name:"Color",index:"color_code",width:80,align:'center'},
						{name:"Price",index:"products_price",width:80,formatter:'currency',editable:true,align:'center'},
						{name:"Seats",index:"seats",width:70,align:'center'},
						{name:"Locks",index:"locks",width:70,align:'center'},
						{name:"Sold",index:"sold",width:70,align:'center'}
					],
					ondblClickRow: function(id){
						if(id && id!=lastsel_sub){
							$("#"+subgrid_table_id).jqGrid('restoreRow',lastsel_sub);
							$("#"+subgrid_table_id).jqGrid('editRow',id,true,'','','','',function(){lastsel_sub=0;});
							lastsel_sub=id;
						}
						else {
							/* bug-fix for escape key - edit row without restoring anything */
							if(id==lastsel_sub){
								$("#"+subgrid_table_id).jqGrid('editRow',id,true);
							}
						}
					},
					editurl: 'concert_details_ajax.php?mode=price',
					rowNum:10,
					sortname: 'products_price',
					sortorder: "asc",
					height: '100%'
				});
			},
		subGridRowColapsed:
			function(subgrid_id) {
				if(parseInt(subgrid_id.replace('concert_grid_',''))==parseInt(lastsel_sub)){
					lastsel_sub=0;
				}
			}
		
	});
	
	$("#concert_pager").jqGrid('navGrid','#concert_grid',{add:false, edit:false, del:false});
	$(window).bind('resize',function(){$("#concert_grid").setGridWidth($(window).width()-160);}).trigger('resize');
});
/* sortable rows on/off */
function enableSort(){
	$("#concert_grid").jqGrid('sortableRows', {
		cancel: '.ui-subgrid',
		cursor: 'n-resize',
		axis: 'y',
		update:
			function(e, ui){
				$.ajax({
					url:'concert_details_ajax.php?mode=sort&order='+$('#concert_grid').jqGrid('getDataIDs').toString(),
					success:function(){
						$("#concert_grid").trigger('reloadGrid');
					}
				});
			},
		start:
			function(e, ui){
				$('tr.ui-subgrid').remove();
			}
	});
}
function disableSort(){
	$('#concert_grid tbody').sortable('destroy');
}