//------------------------------------------------------------------
//  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') : '';
}

function formatDescription(value) {
    if (value && value.length > 150)
        return value.substr(0, 150) + '...';
    else
        return value ? value : 'None';
}

/* Search keyword for keyword search */
function extractParam(paramName) {
    var paramValue = '';
    if (window.location.search) {
        var queryString = escape(window.location.search);
        var paramArray = queryString.substr(1).split('%26');
        var length = paramArray.length;
        for (var index = 0; index < length; index++) {
            var param = paramArray[index].split('%3D');
            if (paramName == param[0]) {
                var paramValue = typeof param[1] == "string" ? decodeURIComponent(param[1].replace(/\+/g, ' ')) : null;
                break;
            }
        }
    }
    return paramValue;
}

var SearchKeyword = extractParam('keyword');

//var tb = new Ext.Toolbar('toolbar');

//------------------------------------------------------------------
//functions called from pages and tools
//------------------------------------------------------------------

function AddNew(sObjectType, oCaller) {
    sParentTypeCurrent = sObjectType;

    Ext.MessageBox.prompt(
        'Add New',
        'Enter title of new ' + sObjectType + ':',
        function(btn, text) {
            if ((btn == "ok") && (text != "")) {
                PostAction('addnew', text)
            }
        },
        '',
        true
    );
}

function CommentAdd(sParentType, lParentID, oCaller, defaultComemnt, tab) {
    sParentTypeCurrent = sParentType;
    lParentIDCurrent = lParentID;
    sActiveTabCurrent = tab || "comments";

    Ext.MessageBox.prompt(
        'Comment',
        'Please enter your comment:',
        function(btn, text) {
            if ((btn == "ok") && (sParentType == "tbleventattendees" || text != "")) {
                PostAction('commentadd', text);
            }
        },
        '',
        true,
        defaultComemnt
    );
}

function CommentDelete(lParentID) {
    lItemIDCurrent = lParentID;
    sActiveTabCurrent = "comments";

    Ext.Msg.confirm(sAppTitle, 'Are you sure you want to delete this comment?', function(btn, text) {
        if (btn == 'yes') PostAction("commentdelete", "");
    });
}

//--------------------------------------------------------------------

function RelationshipDelete(sParentType, lParentID, sChildType, sChildID, aCaller) {
    //console.log(sParentType, lParentID, sChildType, sChildID)

    sParentTypeCurrent = sParentType;
    lParentIDCurrent = lParentID;
    sChildTypeCurrent = sChildType;
    lChildIDCurrent = sChildID;

    Ext.Msg.confirm(sAppTitle, 'Are you sure you want to remove this link?', function(btn, text) {
        if (btn == 'yes') PostAction("linkdelete", "");
    });
}

function RelationshipDeleteById(lItemID, aCaller) {
    lItemIDCurrent = lItemID;

    Ext.Msg.confirm(sAppTitle, 'Are you sure you want to remove this link?', function(btn, text) {
        if (btn == 'yes') PostAction("linkdeletebyid", "");
    });
}

//--------------------------------------------------------------------
//more task specific functions
//--------------------------------------------------------------------

function UploadFileBasic(sParentType, lParentID, oCaller) {
    Ext.FileUploadWindow.show({
        title: "Upload File",
        animEl: oCaller,
        ShowTitle: false,
        ShowType: false,
        ShowDescription: false,
        params: {"target":"/userfiles/attachments/" + sParentType + "/" + lParentID, "parentType": sParentType, "parentID": lParentID},
        url: '/bespoke/actions/upload.asp',
        waitMsg: 'Uploading your file...',
        success: function(fp, o) {
            //o.result.message,
            window.location.search = window.location.search;
        },
        failure: function(fp, o) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: o.result.message + ' ' + o.result.error,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    });
}

function UploadFile(sParentType, lParentID, oCaller) {
    sActiveTabCurrent = "documents";

    Ext.FileUploadWindow.show({
        title: "Upload File",
        animEl: oCaller,
        ShowTitle: true,
        ShowType: true,
		AllowBlankType: true,
        ShowDescription: true,
        params: {"target": "/userfiles/attachments/" + sParentType + "/" + lParentID},
        url: '/bespoke/actions/upload.asp',
        waitMsg: 'Uploading your file...',
        success: function(fp, o) {
            //o.result.message,
            RefreshTabbedPage();
        },
        failure: function(fp, o) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: o.result.message + ' ' + o.result.error,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    });
}

function UploadDocument(sParentType, lParentID, oCaller) {
    sActiveTabCurrent = "documents";

    Ext.FileUploadWindow.show({
        title: "Upload and attach document",
        animEl: oCaller,
        ShowTitle: true,
        ShowType: true,
		AllowBlankType: true,
        ShowDescription: true,
        DocumentTypesUrl: '/cms/utilities/listwriter.asp?listname=reportdocumenttypes&style=JSON',
        params: {
            "target": "/userfiles/attachments/" + sParentType + "/" + lParentID,
            "parentId": lParentID,
            "parentType": sParentType
        },
        url: '/bespoke/actions/upload.asp',
        waitMsg: 'Uploading your document...',
        success: function(fp, o) {
            //o.result.message,
            RefreshTabbedPage();
        },
        failure: function(fp, o) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: o.result.message + ' ' + o.result.error,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    });
}

function DeleteImage(sParentType, lParentID, oCaller) {
    sParentTypeCurrent = sParentType;
    lParentIDCurrent = lParentID;
    sActiveTabCurrent = "";

    Ext.Msg.confirm(sAppTitle, 'Are you sure you want to delete this image?', function(btn, text) {
        if (btn == 'yes') PostAction("deleteimage", "");
    });
}

function DeleteFile(lItemID, oCaller) {
    lItemIDCurrent = lItemID;
    sActiveTabCurrent = "documents";
    Ext.Msg.confirm(sAppTitle, 'Are you sure you want to delete this file?', function(btn, text) {
            if (btn == 'yes') PostAction("deletefile", "");
    });
}

function UploadYourPhoto(oCaller) {
    Ext.FileUploadWindow.show({
        title: "Upload Image",
        animEl: oCaller,
        ShowTitle: false,
        ShowType: false,
        ShowDescription: false,
        params: {"FileNameOverride1": "image.png"},
        url: '/bespoke/actions/upload.asp',
        waitMsg: 'Uploading your image...',
        success: function(fp, o) {
            //o.result.message,
            window.location.search = window.location.search;
        },
        failure: function(fp, o) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: o.result.message + ' ' + o.result.error,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    });
}

function UploadImage(sParentType, lParentID, oCaller) {
    Ext.FileUploadWindow.show({
        title: "Upload Image",
        animEl: oCaller,
        ShowTitle: false,
        ShowType: false,
        ShowDescription: false,
        params: {"target": "/userfiles/attachments/" + sParentType + "/" + lParentID, "FileNameOverride1": "image.png"},
        url: '/bespoke/actions/upload.asp',
        waitMsg: 'Uploading your image...',
        success: function(fp, o) {
            //o.result.message,
            window.location.search = window.location.search;
        },
        failure: function(fp, o) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: o.result.message + ' ' + o.result.error,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    });
}

function SurveyLink(sParentType, lParentID, lPageID, oCaller) {
//if object=pages use pageid as itemid will be from previous page request

    if (sParentType == "tblpages") {
        RelationshipAdd("tblpages", lPageID, "tblvoting", oCaller);
    } else {
        RelationshipAdd(sParentType, lParentID, "tblvoting", oCaller);
    }

    //var sQueryString = window.location.search.toString();
    //var urlObj = Ext.urlDecode(sQueryString)
    //alert(urlObj.itemid)
}

function EventCancelOwnPlace(lEventID, oCaller) {
    lParentIDCurrent = lEventID;

    Ext.MessageBox.prompt(
        'Are you sure you want to cancel your place?',
        'Comments (optional):',
        function (btn, text) {
            if (btn == "ok") {
                PostAction('eventcancelownplace', text);
            }
        },
        '',
        true
    );
}

function EventCancelOthersPlace(lEventAttendeeID, oCaller) {
    lItemIDCurrent = lEventAttendeeID;

    Ext.MessageBox.prompt(
        'Are you sure you want to cancel this booking?',
        'Comments (optional):',
        function (btn, text) {
            if (btn == "ok") {
                PostAction('eventcancelothersplace', text);
            }
        },
        '',
        true
    );
}

function GroupJoin(lParentID, oCaller) {
    lParentIDCurrent = lParentID;
    sRelationTypeCurrent = "chapter";
    sActiveTabCurrent = "users";

    Ext.MessageBox.prompt(
        'Join Group',
        'Please provide a simple explanation for joining this group:',
        function (btn, text) {
            if ((btn == "ok") && (text != "")) {
                PostAction('groupjoin', text);
            }
        },
        '',
        true
    );
}

function ChapterSetHome(lParentID, oCaller) {
    lChildIDCurrent = lParentID;
    PostAction('chaptersethome');
}


function RelationshipDelete_User(sParentType, lParentID, sRelationType) {
    if (confirm("Are you sure?")) {

        sParentTypeCurrent = sParentType;
        lParentIDCurrent = lParentID;
        sRelationTypeCurrent = sRelationType;
        sActiveTabCurrent = "users";

        PostAction("linkdeleteuser", "");
    }
}

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?page=DataSet:Voting';
        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 == "tblevents") {
        sFeedUrl = '/cms/feedpage.asp?page=DataSet:EventsFuture';
        aReaderFields = ['eventid', 'title', 'venue', 'entry', 'summary',{ name: 'startdatex', type: 'date', dateFormat: 'YmdHis' },{ name: 'enddatex', type: 'date', dateFormat: 'YmdHis' }];
        aColumns = [
            {header: 'ID', dataIndex: 'eventid', hidden: true ,width: IDWidth},
            {header: 'Start Date', dataIndex: 'startdatex' ,renderer: formatDate ,width: DateWidth},
            {header: 'Title', dataIndex: 'title' ,width: TitleWidth},
            {header: 'Venue', dataIndex: 'venue' ,width: FieldWidth},
            {header: 'Event Type', dataIndex: 'entry', width: 80}
        ];
        sIDColumn = "eventid";
        sNoun = "Event";
        sKeywordFilterFields = 'title,venue,summary,contents';
        sDefaultSortFld = "startdatex";
    }

    if (sChildType == "tblnews") {
        sFeedUrl = '/cms/feedpage.asp?page=DataSet:News';
        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';
    }

    if (sChildType == "tblarticles") {
        sFeedUrl = '/cms/feedpage.asp?page=DataSet:Articles';
        aReaderFields = ['articleid','title','synopsis'];
        aColumns = [
            {header: 'ID', dataIndex: 'articleid', hidden: true ,width: IDWidth},
            {header: 'Title', dataIndex: 'title' ,width: TitleWidth},
            {header: 'Summary', dataIndex: 'synopsis' ,width: FieldWidth}
        ];
        sIDColumn = "articleid";
        sNoun = "Article";
        sKeywordFilterFields = 'title,synopsis,contents';
    }

    if (sChildType == "tblusers") {
        sFeedUrl = '/cms/feedpage.asp?url=/bespoke/panels/json/users2.html';
        aReaderFields = ['userid','photox','fullnamex','jobtitle','companyname'];
        aColumns = [
            {header: 'ID', dataIndex: 'userid', hidden: true ,width: IDWidth},
            {header: 'Photo', dataIndex: 'photox',width: IDWidth},
            {header: 'Name', dataIndex: 'fullnamex' ,width: FieldWidth},
            {header: 'Title', dataIndex: 'jobtitle',width: FieldWidth},
            {header: 'Company', dataIndex: 'companyname' ,width: FieldWidth}
        ];
        sIDColumn = "userid";
        sNoun = "User";
        sKeywordFilterFields = 'u.title,u.firstname,u.lastname,c.name,u.jobtitle';
        sDefaultSortFld = "u.lastname";
    }


    if (sChildType == "tblregistrations") {
        sFeedUrl = '/cms/feedpage.asp?url=/bespoke/json/users2.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";
    }
        
    if (sChildType == "tbldocuments") {
        sFeedUrl = '/cms/feedpage.asp?url=/bespoke/panels/json/documents.html';
        aReaderFields = ['documentid','documenttypetext','title'];
        aColumns = [
            {header: 'ID', dataIndex: 'documentid', hidden: true ,width: IDWidth},
            {header: 'Type', dataIndex: 'documenttypetext',width: IDWidth},
            {header: 'Title', dataIndex: 'title' ,width: FieldWidth, id:'coltitle'}
        ];
        sIDColumn = "documentid";
        sNoun = "Document";
        sKeywordFilterFields = 'd.title';
        sDefaultSortFld = "d.title";
        sAutoExpandColumn = 'coltitle'; //expected a number to work here but it doesn't, so have had to specify col's id above
    }

    if (sChildType == "comments") {
        sFeedUrl = '/cms/feedpage.asp?url=/bespoke/panels/json/discussions.html';
        aReaderFields = ['commentid','subject','u_fullname','jobtitle','companyname'];
        aColumns = [
            {header: 'ID', dataIndex: 'commentid', hidden: true ,width: IDWidth},
            {header: 'Subject', dataIndex: 'subject',width: FieldWidth},
            {header: 'Name', dataIndex: 'u_fullname' ,width: FieldWidth},
            {header: 'Title', dataIndex: 'jobtitle',width: FieldWidth},
            {header: 'Company', dataIndex: 'companyname' ,width: FieldWidth}
        ];
        sIDColumn = "commentid";
        sNoun = "Discussion";
        sKeywordFilterFields = 'tD.subject,tU.firstname,tU.lastname,co.name,jobtitle';
    }
    
    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 RefreshTabbedPage() {
    var sQueryString = window.location.search.toString();

    if (sActiveTabCurrent) {
        //if no querystring, start one off so urlDecode works
        if (!sQueryString) sQueryString = "tab=";
        
        // Ext.urlDecode doesn't handle "?" is query string
        sQueryString = sQueryString.replace("?", "");

        //tab specified so update value (might be unchanged)
        var urlObj = Ext.urlDecode(sQueryString);
        urlObj.tab = sActiveTabCurrent;
        sQueryString = Ext.urlEncode(urlObj);
        sQueryString = sQueryString.replace(/%3F/, "");
    }

    //update the querystring causing refresh...
    //console.log(sQueryString, window.location.search)
    if (sQueryString.length == 0) {
        window.location = window.location.href;
    } else {
        if (window.location.href.match(/(\..\w+|\/)\??(\w+=\w+&?)*$/)) {
            window.location.search = sQueryString;
        } else {
            window.location = window.location.href + "/?" + sQueryString;
        }
    }
}

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
            });
        }
    });
}

//------------------------------------------------------------
//start discussion dialog
//------------------------------------------------------------
var dlgStartDiscussion;
function StartDiscussion(sParentType, lParentID, oCaller) {

    sParentTypeCurrent = sParentType;
    lItemIDCurrent = lParentID;
    sActiveTabCurrent = "discussions";

    if (!dlgStartDiscussion) {
        dlgStartDiscussion = new Ext.Window({
            autoCreate: true,
            resizable: false,
            minimizable: false,
            maximizable: false,
            modal: true,
            buttonAlign: "center",
            plain: true,
            closable: true,
            width: 600,
            height: 300,
            closeAction: "close",
            title: "Start discussion",
            items: [{
                xtype: "form",
                monitorValid: true,
                id: "discussionwindow-form",
                bodyStyle: "padding: 10px 10px 0 10px;",
                labelWidth: 70,
                baseCls: "",
                defaults: {
                    anchor: "95%",
                    msgTarget: "side"
                },
                items: [{
                    xtype: "textfield",
                    id: "discussionwindow-title",
                    fieldLabel: "Subject",
                    name: "Subject",
                    allowBlank: false
                },{
                    xtype: "textarea",
                    id: "discussionwindow-description",
                    fieldLabel: "Details",
                    name: "Comment",
                    allowBlank: false,
                    height: 180
                }],
                buttonAlign: 'center',
                buttons: [{
                    text: "OK",
                    formBind: true,
                    handler: function() {
                        PostAction("commentadd", Ext.getCmp("discussionwindow-description").getValue(), Ext.getCmp("discussionwindow-title").getValue());
                    }
                },{
                    text: "Cancel",
                    handler: function() {
                        dlgStartDiscussion.close();
                    }
                }]
            }],
            close: function() {
                dlgStartDiscussion.hide();
            }
        });
    }

    dlgStartDiscussion.show();

    //params: {"target":"/userfiles/attachments/" + sParentType + "/" + lParentID, "FileNameOverride1":"image.png"},
    //url: '/bespoke/actions/upload.asp',
}

function EventReserveOwnPlace(lParentID) {
    lParentIDCurrent = lParentID;
    var sComment = "";
    sActiveTabCurrent = "attendees";
    Ext.MessageBox.prompt(
        "Reserve your place at this event", "Comments (optional):",
        function (btn, text) {
            if (btn == "ok") {
                PostAction("eventreserveownplace", text);
            }
        },
        "",
        true
    );
}

function EventAttendeeAdd(lParentID) {
    lParentIDCurrent = lParentID;
    var sComment = '';
    sActiveTabCurrent = 'attendees';
    PostAction('eventattendeeadd', sComment);
}

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);

    
}