//------------------------------------------------------------------
//  general and filters declarations...
//------------------------------------------------------------------

/*--------------------------------------------------*/
/*if no firebug, stop console calls from breaking JS*/
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}
/*--------------------------------------------------*/

var iPageSize = 16;

var sActiveTabCurrent;
var lItemIDCurrent;
var sParentTypeCurrent;
var lParentIDCurrent;
var sChildTypeCurrent;
var lChildIDCurrent;
var sRelationTypeCurrent;

var SearchWidth = 150;
var DropDownWidth = 150;
var DropDownWidthLong = 250;

var IDWidth = 50;
var TitleWidth = 300;
var DateWidth = 80;
var FieldWidth = 150;
var FieldWidthLong = 220;


function formatDate(value) {
    return value ? value.dateFormat('j M y') : '';
}


//--------------------------------------------------------------------
//more task specific functions
//--------------------------------------------------------------------


function RelationshipAdd(sParentType, lParentID, sChildType, aCaller, bShowCommentDialog) {
    sActiveTabCurrent = sChildType.replace(/tbl/, "");

    sParentTypeCurrent = sParentType;
    lParentIDCurrent = lParentID;
    sChildTypeCurrent = sChildType;

    var sFeedUrl;
    var aReaderFields;
    var aColumns;
    var sNoun;
    var sKeywordFilterFields;
    var sIDColumn;
    var sAutoExpandColumn;
    var sDefaultSortFld = "";
    var sDefaultSortDir = "";


	if (sChildType == "tblvoting") {	
        sFeedUrl = '/cms/feedpage.asp?url=/cms/modules/voting/json.html'
        aReaderFields = ['voteid', 'voteclosedx', 'subject', 'showmex' ,{ name: 'voteopendatex', type: 'date', dateFormat: 'YmdHis' }, 'votecount'];
        aColumns = [
                 {header: 'ID', dataIndex: 'voteid', hidden:true ,width: IDWidth}
                ,{header: 'Open Date', dataIndex: 'voteopendatex' /*,renderer: formatDate*/ ,width: DateWidth}
                ,{header: 'Subject', dataIndex: 'subject' ,width: TitleWidth}
                ,{header: 'Closed', dataIndex: 'voteclosedx' ,width: 50}
                ,{header: 'Visible', dataIndex: 'showmex', width: 50}
                ,{header: 'Votes', dataIndex: 'votecount', width: 50}
            ];
        sIDColumn = "voteid";
        sNoun = "Vote";
        sKeywordFilterFields = 'subject'; 
        sAutoExpandColumn = 2
    }

	if (sChildType == "tblnews") {	
        sFeedUrl = '/cms/feedpage.asp?url=/cms/modules/news/json.html'
        aReaderFields = ['newsid','shorttitle','fulltitle', 'newscategoryname',{name: 'dateposted', type: 'date', dateFormat: 'YmdHis' }];
        aColumns = [
            {header: 'ID', dataIndex: 'newsid', hidden: true ,width: IDWidth},
            {header: 'Date Posted', dataIndex: 'dateposted' ,renderer: formatDate ,width: DateWidth},
            {header: 'Title', dataIndex: 'shorttitle' ,width: TitleWidth},
            {header: 'Summary', dataIndex: 'fulltitle' ,width: FieldWidth},
            {header: 'category', dataIndex: 'newscategoryname', width: 80}
        ];
        sIDColumn = "newsid";
        sNoun = "News Item";
        sKeywordFilterFields = 'shorttitle,fulltitle,n.contents';
        sDefaultSortFld = "dateposted"
        sDefaultSortDir = "desc";
    }    
    
    if (sChildType == "tblregistrations") {
        sFeedUrl = '/cms/feedpage.asp?url=/bespoke/json/users.html';
        aReaderFields = ['registrationid','photo','firstname','lastname'];
        aColumns = [
            {header: 'ID', dataIndex: 'userid', hidden: true ,width: IDWidth},
            //{header: 'Photo', dataIndex: 'photo',width: 50},
            {header: 'First Name', dataIndex: 'firstname' ,width: FieldWidth},
            {header: 'Last Name', dataIndex: 'lastname' ,width: FieldWidth}
        ];
        sIDColumn = "registrationid";
        sNoun = "User";
        sKeywordFilterFields = 'title,firstname,lastname,username';
        sDefaultSortFld = "lastname";
    }

    
    var doPostAction = function(scope, onBeforePostActionCallback) {
        if (bShowCommentDialog) {
            Ext.MessageBox.prompt(
                "Select " + sNoun, "Comments (optional):",
                function (btn, text) {
                    if (btn == "ok") {
                        Ext.callback(onBeforePostActionCallback, scope || this, null);
                        PostAction("linkadd", text);
                    }
                },
                null,
                true
            );
        } else {
            Ext.callback(onBeforePostActionCallback, scope || this, null);
            PostAction("linkadd", "");
        }
    }    

	/* Text field for keyword search */
    var KeywordSearch = new Ext.form.TextField({
        emptyText: 'Keyword search...',
        width: SearchWidth
    });

    //launch the dialog with grid...

    var ds = new Ext.data.Store({
        //groupField: 'startdatex',
        proxy: new Ext.data.HttpProxy({
            url: sFeedUrl,
            method: 'GET'
        }),
        reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'count',
            id: sIDColumn
        }, aReaderFields),
        remoteSort: true
    });

    if (sDefaultSortFld != "") {
        ds.setDefaultSort(sDefaultSortFld, sDefaultSortDir);
    }

    var cm = new Ext.grid.ColumnModel({
        columns: aColumns,
        defaults: {
            sortable: true
        }
    });

    cm.defaultSortable = true;

    var paging = new Ext.PagingToolbar({
        pageSize: iPageSize,
        store: ds,
        displayInfo: true,
        displayMsg: 'Displaying {0} - {1} of {2}',
        emptyMsg: "No entries to display"
    });

	var win = new Ext.Window({
		layout: 'fit',
		resizable: false,
		width: 700,
		height: 500,
		plain: true,
		modal: true,
		closeAction: 'close',
		title: 'Select ' + sNoun,
		items: new Ext.grid.GridPanel({
			id: 'gridSelector',
			border: false,
			autoScroll: true,
			height: 430,
			ds: ds,
			cm: cm,
			selModel: new Ext.grid.RowSelectionModel({ singleSelect: false, keepSelections: true }),
			enableColLock: false,
			loadMask: true,
			width: "100%",
			autoExpandColumn: sAutoExpandColumn,
			tbar: [/*EventTypes, '-', */KeywordSearch],
			bbar: paging,
			/*
			view: new Ext.grid.GroupingView({
				forceFit:true,
				startCollapsed: false,
				hideGroupedColumn: true,
				showGroupName: false,
				groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Events" : "Event"]})'
			}),
			*/
			listeners: {
				rowdblclick: function(grid, rowIndex, e) {
					var row = this.getView().getRow(rowIndex);
					lChildIDCurrent = ds.getAt(rowIndex).id;

					doPostAction(this, function() {
					    this.getEl().mask("Saving...", "x-mask-loading");
					    
				        // we should be using grid.buttons property but it doesn't work
                        Ext.getCmp("relationshipAdd_ApplyBtn").disable();
					});
				}
			},
			plugins: new Ext.grid.GridFilters({id:'gfAuto', filters: [
					  { type: 'keyword', dataIndex: sKeywordFilterFields, field: KeywordSearch, value: '' }
					  //,{ type: 'select', dataIndex: 'entryid', field: EventTypes }
			]})
		}),
		buttons: [{
		    id: "relationshipAdd_ApplyBtn",
			text: 'Apply',
			handler: function() {
			    var grid = Ext.getCmp('gridSelector');
				lChildIDCurrent = grid.selModel.selections.keys;
				if (lChildIDCurrent.length > 0) {
				    doPostAction(this, function() {
				        grid.getEl().mask("Saving...", "x-mask-loading");
				        this.disable();
				    });
			    }
			}
		},{
			text: 'Close',
			handler: function() {
                win.hide();
			}
		}]
	});

	win.show();
	ds.load({params:{start: 0, limit: iPageSize}});
}

//--------------------------------------------------------------------
//internal functions
//--------------------------------------------------------------------

function PostAction(sAction, sComment, sSubject) {

    var sPostUrl = '/bespoke/actions/default.asp';

    if ((sAction == "linkadd") && (sChildTypeCurrent == "tblusers") && (sParentTypeCurrent == "tblevents")) {
        sAction = 'eventattendeeadd';
        sActiveTabCurrent = 'attendees';
    }

    Ext.Ajax.request({
        url: sPostUrl,
        params: {
            action: sAction,
            comment: sComment,
            subject: sSubject,
            itemid: lItemIDCurrent,
            parenttype: sParentTypeCurrent,
            parentid: lParentIDCurrent,
            childtype: sChildTypeCurrent,
            childid: lChildIDCurrent,
            relationtype: sRelationTypeCurrent
        },
        success: function (oResponse, oOptions) {
            // Check for "logic" errors. ie the transport part of the request worked but server script disallowed
            var oRespDecoded = Ext.decode(oResponse.responseText);
            if (!oRespDecoded.success) {
                Ext.MessageBox.show({
                    title: 'Error',
                    msg: oRespDecoded.error,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.ERROR
                });
            } else {
                if (oRespDecoded.redirectto) {
                    window.location = oRespDecoded.redirectto;
                } else {
                    RefreshTabbedPage();
                }
            }
        },
        failure: function (oResponse, oOptions) {
            //most often "transport" errors eg page not found, page crashed on server side, etc
            Ext.MessageBox.show({
                title: 'Error',
                msg: oResponse.status + ' ' + oResponse.statusText,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    });
}

function FavouriteAdd(sParentType, lParentID, oCaller) {
    sParentTypeCurrent = sParentType;
    lItemIDCurrent = lParentID;
    sActiveTabCurrent = "";
    
    PostAction('favouriteadd', '')
    
    /*
    Ext.MessageBox.prompt(
        'Add to favourites',
        'Comments (optional):',
        function (btn, text) {
            if (btn == "ok") {
                PostAction('favouriteadd', text);
            }
        },
        '',
        true
    );
    */
}

function FavouriteDelete(sParentType, lParentID, oCaller) {
    sParentTypeCurrent = sParentType;
    lItemIDCurrent = lParentID;
    sActiveTabCurrent = "";

    Ext.Msg.confirm(sAppTitle, 'Are you sure?', function(btn, text) {
        if (btn == 'yes') PostAction("favouritedelete", "");
    });
}



function FavouriteAddForUser(sParentType, lParentID, oCaller) {
    sParentTypeCurrent = sParentType;
    lItemIDCurrent = lParentID;
    sActiveTabCurrent = "";
    
    RelationshipAdd(sParentType, lItemIDCurrent, "tblregistrations", oCaller);

    
}




function RefreshTabbedPage(){
window.location = window.location;
}
