
dojo.require("dojo.parser");	// scan page for widgets and instantiate them

var dojo_loaded = false;
var dojo_widgets = new Array();		
function registerWidget(id) {
        var widget = dojo.byId(id);
        dojo_widgets[dojo_widgets.length] = widget;
//        alert('register ' + id + ' ' + dojo_loaded);
        if (dojo_loaded) {
                alert('test: ' + dojo_loaded);
                dojo.parser.instantiate(widget);
        }
}

var dojo_code = new Array();		
function registerCode(code) {
        dojo_code[dojo_code.length] = code;
}

var dojo_buttons = new Array();
function registerButton(form_id,button) {
//        alert(form_id + ' ' + button);
        if (dojo_buttons[form_id] == null) {
                dojo_buttons[form_id] = new Array();
        }
        dojo_buttons[form_id][dojo_buttons.length] = button;
}

window.fck_editors = new Array();
function FCKeditor_OnComplete( editorInstance ){
        var name = editorInstance.Name;
        window.fck_editors[name] = editorInstance;
}

function parseWidgets() {
        dojo.parser.instantiate(dojo_widgets);
        dojo_loaded = true;
}

function loadEmbeddedJS(pane_id) {
        var pane = document.getElementById(pane_id);
        var embed = pane.lastChild;
        if (embed.toString() == '[object Text]') {
                embed = embed.previousSibling;
        }
//        alert('embed: ' + pane + '/' + pane_id);
//        alert('embed2: ' + pane.lastChild + '/' + pane_id);
//        alert('embed3: ' + embed.innerHTML);
}

/*			function postForm(button,target_form,target_pane) {
        target_pane = dijit.byId(target_pane);  //this isn't accessible in the scope of the form, but is here
//				alert(button + ' ' + target_form + ' ' + target_pane);
//				dojo.connect(button, "onClick", function(event){
                //Stop the submit event since we want to control form submission.
//					event.preventDefault();
//					event.stopPropagation();
//					alert('here');

                var args = {
                        form: target_form,
                        handleAs: "text",
                        load: function(data){
                          dojo.byId(target_pane).setContent = data;
                        },
                        error: function(error){
                          dojo.byId(target_pane).setContent = error;
                        }
                }
                var response = dojo.xhrPost(args);
//				});
}

function setupButton(button,target_form,target_pane) {
        target_pane = dijit.byId(target_pane);  //this isn't accessible in the scope of the form, but is here
//				alert(button + ' ' + target_form + ' ' + target_pane);
        dojo.connect(button, "onClick", function(event){
                //Stop the submit event since we want to control form submission.
                event.preventDefault();
                event.stopPropagation();
                alert('here');

                var args = {
                        form: target_form,
                        handleAs: "text",
                        load: function(data){
                          dojo.byId(target_pane).setContent = data;
                        },
                        error: function(error){
                          dojo.byId(target_pane).setContent = error;
                        }
                }
                var response = dojo.xhrPost(args);
        });
}

*/

function fixAnchorLink() {
        //set anchor link to reload
        var anchor = document.location.hash;
        if (anchor != '') {
                var link_id = anchor.substr(1);
                var current_link = document.getElementById(link_id);
                if (current_link != null) {
                        var rand = parseInt(Math.random() * 10000);
                        current_link.href = current_link.href.replace(document.location.hash,'&' + rand + document.location.hash);
                }
        }        
}

dojo.addOnLoad(parseWidgets);
dojo.addOnLoad(fixAnchorLink);

/* context menu code */

function contextMenu_ajaxGet(url) {
    dojo.xhrGet({
        url: url,
        handleAs: "text",
        load: function(data) { },
        error: function(error) {  }
    });
    return false;
}

function contextMenu_createPopup(contextMenu,data,row_id,depth) {
        for (i in data) {
                if (data[i][1] == 'menu') {
                        var popupmenu = new dijit.Menu({});
                        var popup = new dijit.PopupMenuItem({
                            label: data[i][0],
                            popup: popupmenu
                        });
        
                        var subpopup = contextMenu_createPopup(popupmenu,data[i][2],row_id,depth+1);
                        contextMenu.addChild(popup);                        
                } else {
                        var types = [];
                        if (typeof(data[i][1]) == 'string') {
                            types[0] = data[i][1];
                        } else {
                            types = data[i][1];
                        }
                    
                        if (types.length > 1) {
                                var popupmenu = new dijit.Menu({});
                                var popup = new dijit.PopupMenuItem({
                                    label: data[i][0],
                                    popup: popupmenu
                                });
                                contextMenu.addChild(popup);                        
                        }
                        for (j in types) {
                                var action = null;
                                if (data[i][2][row_id] != null) {  //form
                                        action = data[i][2][row_id];
                                } else if (data[i][2][-1]) {  //list
                                        action = data[i][2][-1];
                                }
                                if (action != null) {
                                        if (types[j] == 'link') {
                                                var menuitem = new dijit.MenuItem({
                                                    label: (types.length == 1?data[i][0]:'Open'),
                                                    action_href: action,
                                                    onClick: function(evt) {
                                                        if (this.action_href.substr(0,1) == '/') {
                                                                var base = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'');
                                                        } else {
                                                                var base = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'') + window.location.pathname;
                                                        }
                                                                    //alert(base + this.action_href);
                                                        window.location.href = base + this.action_href;
                                                        }
                                                });
                                        } else if (types[j] == 'new') {
                                                var menuitem = new dijit.MenuItem({
                                                    label: (types.length == 1?data[i][0]:'New Window'),
                                                    action_href: action,
                                                    onClick: function(evt) {
                                                        if (this.action_href.substr(0,1) == '/') {
                                                                var base = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'');
                                                        } else {
                                                                var base = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'') + window.location.pathname;
                                                        }
                                                        window.open(base + this.action_href)
                                                       }
                                                });
                                        } else if (types[j] == 'popup') {
                                                var menuitem = new dijit.MenuItem({
                                                    label: (types.length == 1?data[i][0]:'Popup Window'),                                
                                                    action_data: data,
                                                    action_href: action,                                        
                                                    onClick: function(evt) {
                                                        if (this.action_href.substr(0,1) == '/') {
                                                                var base = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'');
                                                        } else {
                                                                var base = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'') + window.location.pathname;
                                                        }
                                                        
                                                        var width  = 700;
                                                        var height = 500;
                                                        var left   = (screen.width  - width)/2;
                                                        var top    = (screen.height - height)/2;
                                                        var params = 'width='+width+', height='+height;
                                                        params += ', top='+top+', left='+left;
                                                        params += ', resizable=yes';
                                                        params += ', scrollbars=yes';
                                                        var href = '';
                                                        if (this.action_href.indexOf('#') > 0) {
                                                            href = this.action_href.replace('#','&__popup=true#')
                                                        } else {
                                                            href += this.action_href + '&__popup=true';
                                                        }
                                                        window.open(base + href,'popup_' + this.action_data.object_id, params);
                                                    }
                                                });
                                        } else if (types[j] == 'ajax') {
        //                                        var url = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'') + window.location.pathname + data.links[type][i]['custom_ajax'][j];
                                                var menuitem = new dijit.MenuItem({
                                                    label: (types.length == 1?data[i][0]:'Open'),                                
                                                    action_href: action,
                                                    onClick: function(evt) { contextMenu_ajaxGet(this.action_href); }
                                                });
                                        }
                                        if (types.length == 1) {
                                                contextMenu.addChild(menuitem);
                                        } else {
                                                popupmenu.addChild(menuitem);                                        
                                        }
                                } else {
//                                        alert('no match: ' + i + ' ' + j + ' row_id: ' + row_id);
                                }
                        }
                }
        }
}

function contextMenu_init(menu_id,row_ids,data_id) {
        var contextMenu = new dijit.Menu({
            id: menu_id + '_contextMenu',
            targetNodeIds: row_ids
        });
        dojo.connect(contextMenu, "_openMyself", this, function(evt) {
                var data = window[data_id];
                contextMenu.targetNode = evt.target.parentNode;
                if (contextMenu.hasChildren) {
                    var children = contextMenu.getChildren();
                    for (var child in children) {
                        contextMenu.removeChild(children[child]);
                    }
                }
                var parts = contextMenu.targetNode.id.split('__');
                if (parts.length > 1) {
                    var row_id = parts[parts.length-1];
                }
//                alert(row_id + ' ' + contextMenu.targetNode.id);
//                alert(var_dump(data));
            
                if (data['contextmenu'] != null) {
                        if (data['contextmenu']['form'] != null) {
                                contextMenu.addChild(new dijit.MenuItem({
                                        label: '<b>Form</b>'
                                }));
                                contextMenu_createPopup(contextMenu,data['contextmenu']['form'],row_id,0);
                        }
                        if (data['contextmenu']['list'] != null) {
                                var sep=new dijit.MenuSeparator();
                                contextMenu.addChild(sep);
                                contextMenu.addChild(new dijit.MenuItem({
                                        label: '<b>List</b>'
                                }));
                                contextMenu_createPopup(contextMenu,data['contextmenu']['list'],0,0);
                        }
        
                        var sep=new dijit.MenuSeparator();
                        contextMenu.addChild(sep);
                        contextMenu.addChild(new dijit.MenuItem({
                            label: '<b>Config</b>',
                            onClick: function(evt) {
//                                window.location.href = window.location.protocol + '//' + window.location.hostname + (window.location.port != ''?':' + window.location.port:'') + 'config.php';
                                window.location.href = 'config.php';
                            }
                        }));
                }
//                            alert(contextMenu.targetNode);
        });

/*        contextMenu.addChild(new dijit.MenuItem({
        label: 'list',
        onClick: function(evt) {
//                               alert(\'on click \' + evt.target + \' \' + evt.target.id + \' \' + evt.target.innerHTML);
//                               alert(dijit.getEnclosingWidget(evt.target))
//                var contextMenu = dojo.byId( '_contextMenu');
//                                alert(contextMenu.targetNode);

       
    }
}));
*/
contextMenu.startup();
}
