/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
// Add back browser detection to jQuery
(function($) {
    var userAgent = navigator.userAgent.toLowerCase();

    $.browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
    };

})(jQuery);

var ActionSelect;

function Grid(opts){
    var settings = $.extend({
        headers : null,         // Headers of the grid table
        contents : null,        // json key name for content being displayed in grid
        attributes : null,      // json key name for attributes being injected
        update : null,
        onCreate : null
    }, opts);

    this.headers = settings.headers;
    this.contents = settings.contents;
    this.attributes = settings.attributes;

    this.update = settings.update;
    this.onCreate = settings.onCreate;

    //    this.fetchSequence = function(){
    //        var self = this;
    //        $.ajax({
    //            type : 'get',
    //            dataType : 'json',
    //            url : 'index.php?r=emoticon/getMySequence',
    //            beforeSend : function(){
    //                $(".grid-entry.grid-entry-selected").removeClass("grid-entry-selected");
    //            },
    //            success : function(data){
    //                self.fillEntry(data);
    //            }
    //        });
    //    }

    this.fetchSequence = function(data){
        this.fillEntry(data);
    }

    this._div = null;
    this._heading = null;
    this._content = null;
    this._entry = null;
    this._fieldWidth = null;

    // Events

    this.Create = function(mother){

        this._entry = new Array;
        this._fieldWidth = new Array;

        //log.info("Creating Grid Pane");
        // Create the div for content holding
        this._div = $("<div />")
        .addClass("grid")
        .height(mother.height())
        .width(mother.width())
        .appendTo(mother);

        mother.css("overflow", "hidden").css("textAlign", "center");

        this._title = $("<div />")
        .addClass("grid-title")
        .appendTo(this._div);

        this._content = $("<div />")
        .addClass("grid-content")
        .height(mother.height() - this._title.height())
        .insertAfter(this._title);

        var self = this;

        $.each(this.headers, function(idx, obj){
            self._fieldWidth[idx] = obj;
            $("<div />").addClass("grid-header").text(idx).width(obj).appendTo(self._title);
            $("<div />").addClass("grid-header-seperator").appendTo(self._title);
        });
        $(".grid-header-seperator:last", this._title).remove();

        if (typeof this.onCreate == "function") this.onCreate();

        return this;
    }

    this.fillEntry = function(data){

        var self = this;

        self._content.empty();

        $.each(data, function(idx, obj){
            // create a row
            row = $("<div />").addClass("grid-entry").appendTo(self._content);
            $.each(obj, function(key, value){
                if($.inArray(key, self.attributes) != -1) row.attr(key, value);
            });
            row.click(function(){
                // make the row marked as select, and enable buttons
                // clear every row
                $(".grid-entry.grid-entry-selected").removeClass("grid-entry-selected");
                $(this).addClass("grid-entry-selected");
                $("[_toggleDisable]").removeAttr("disabled").removeClass("ui-state-disabled");
            });

            for (i=0; i<self.contents.length; i++){
                header = $("div.grid-header", row.closest("div.grid"))[i];
                headerWidth = $(header).width();
                //var desired width = $("grid-header", $(this).closest("div.grid"))[i].width()
                $("<div />").addClass("grid-entry-text").text(eval("obj." + self.contents[i])).appendTo(row).width(headerWidth);
                $("<div />").addClass("grid-entry-seperator").appendTo(row);
            }
        });
    }

}

var FriendList = {
    InitStatus : function(){
//        $("[_tag=profile_link]").css("cursor", "pointer").click(function(){
//            window.location.href = "index.php?r=user/show&id=" + $(this).closest("[_userid]").attr("_userid");
//        });
        $("[_tag=profile_link]").hover(function(evt){
            // e = $(evt.relatedTarget);
            // if (e.closest(".context-menu").size() > 0) return;
            Popmenu.Attach($(this));
        }, function(evt){
            // e = $(evt.relatedTarget);
            // if (e.closest(".context-menu").size() > 0) return;
            Popmenu._Clear();
        });
    }
}

var Emoticon = {
    ManageDisplay : function(){
        numOfIcons = $("img.emoticon", $("#widget-emoticon")).size();
        if (numOfIcons == 0){
            $("div.tips", $("#widget-emoticon")).show();
        } else $("div.tips", $("#widget-emoticon")).hide();
    },
    /*Block : function(toggle){
        if ($("#composer-block").size() == 0){
            $("<div id=\"composer-block\" />").text("Control suspended while editing motions.").dialog({
                title : 'Notice',
                modal : true,
                resizable : false,
                draggable : false,
                buttons : {
                    'Close' : function(){
                        $(this).dialog('close')
                    }
                }
            });
        } else {
            $("#composer-block").dialog('open');
        }
    },*/
    UpdateListing : function(){
		$("form.effectForm select").html("");
        $.ajax({
            type : 'get',
            url : 'index.php?r=emoticon/getMySequence&user_id='+$("div#pageInfo").attr("_userid"),
            dataType : 'json',
            success : function(data){
                $.each(data, function(idx, obj){$("<option _hashid=\""+obj["hash_id"]+"\">"+obj["name_key"]+"</option>").appendTo("select.effectList","div#widget-effect")});
            }
        });
        if ($("#action-select").dialog('isOpen')){
            $.ajax({
                type : 'get',
                url : 'index.php?r=emoticon/getMySequence',
                dataType : 'json',
                beforeSend : function(){
                    //log.profile("Fetch action listing");
                    $(".grid-entry.grid-entry-selected").removeClass("grid-entry-selected");

                    $("button:last", $("div.ui-dialog-buttonpane", $("#action-select").parent()));
                    lastBtn = $("button:last", $("div.ui-dialog-buttonpane", $("#action-select").parent()));

                    cBtn = lastBtn;
                    for (i = 0; i < 6; i++){
                        if (i < 4) cBtn.css("float", "left");

                        if (i != 3 && i!= 5){
                            cBtn.attr("disabled", "disabled").addClass("ui-state-disabled");
                            cBtn.attr("_toggleDisable", 1); // These buttons should be enabled upon a select
                        }

                        if (i == 3) cBtn.css("margin-left", 10);
                        cBtn = cBtn.prev();
                    }
                },
                success : function(data){
                    //log.profile("Fetch action listing");

                    if (typeof ActionSelect != "object"){
                        ActionSelect = new Grid({
                            headers : {
                                "Motion name" : '400px',
                                "Last update" : '120px'
                            },
                            contents : ['name_key', 'lastupdate'],
                            attributes : ['sequence_id', 'hash_id'],
                            onCreate : function(){
                                ActionSelect.fetchSequence(data);
                            }
                        });
                        ActionSelect.Create($("#action-select"));
                    } else {
                        ActionSelect.fetchSequence(data);
                    }
                }
            })
        }
    },
    _progress : null,
    _currentEmoticon : null, // the selected emoticon
    ComposerWindow : null, // the composer window, always use this instance if already opened
    InitPreview : function(){
        $("[_tag=emoticon_preview][_init!=1]").hover(function(){
            $(this).attr("_src", $(this).attr("src")).attr("src", $(this).next("img:hidden").attr("src"));
        }, function(){
            $(this).attr("src", $(this).attr("_src"));
        }).click(function(evt){
            Popmenu.Attach($(this));
        }).attr("_init", 1).noContext();
    },
    Create : function(id){
        // guard from IE6
        if (($.browser.msie && $.browser.version >= 7) || ($.browser.mozilla)){
            // okay to create
            var keyId;
            // get private key
            $.get("index.php?r=user/createPrivateKey", null, function(key){
                keyId = key;
                $.get("index.php?r=user/retrievePrivateKey", {
                    key : keyId
                }, function(o){
                    url = "index.php?r=emoticon/create" + ((typeof id == "undefined")? "":("&sid=" + id));
                    this.ComposerWindow = window.open(url , 'composer', 'location=no,titlebar=no,resizable=yes,height=480,width=900', false);
                    if (this.ComposerWindow) this.ComposerWindow.focus();
                });
            });

        } else {
            // unsupported browser
            $("<div>This feature requires Microsoft Internet Explorer 7.0 or above, or Mozilla Firefox 2.0 or above.</div>").dialog({
                title : "Incompatible Browser Detected",
                modal: true,
                resizable: false,
                buttons: {
                    'close' : function(){
                        $(this).dialog("destroy");
                        $(this).remove();
                    }
                }
            });
        }
    },
    Run : function(hash, flag){
        prefix = "";
        if (flag == "play") prefix = "ucibp://sp";
        else if (flag == "download") prefix = "ucibp://sd";
		else if (flag == "test") prefix = "ucibp://st";

        if ($("#emoticon_preview").size() == 0){
            $("<iframe id=\"emoticon_preview\" width=\"0\" height=\"0\" style=\"display:none\" />").appendTo($("body:first"));
        }
        url = prefix + hash;
        $("#emoticon_preview").attr("src", url);
    }
}

var Popmenu = {
    _left : 0,
    _top : 0,
    _el : null,
    _currentTarget : null,
    _init : false,
    _CreateButton : function(label, action){
        pane = $("div.main", Popmenu._el);
        $("<a href=\"#\" class=\"button\" />").text(label).appendTo(pane).click(function(evt){
            if (typeof action == "function") action();
            Popmenu._Clear();
            return false;
        }).mouseenter(function(evt){
            evt.stopPropagation();
        });
    },
    _CreateTips : function(title, tips, style){
        pane = $("div.main", Popmenu._el);
        var s = (typeof style == "undefined")? "":style;
        if (title){
            $("<p class=\"title\">").addClass(s).text(title).appendTo(pane);
        }
        if (tips){
            $("<p>").text(tips).appendTo(pane);
        }
    },
    _Clear : function(){
        $("div.main", Popmenu._el).empty();
        Popmenu._el.hide();
        Popmenu._init = false;
    },
    Initialize : function(obj){
        this._el = $(obj);
        Popmenu._el.mouseleave(function(evt){
            evt.stopPropagation();
            x = $(evt.relatedTarget);
            // if ( (x != this._currentTarget) && (!x.hasClass("context-menu")) && (!x.parent().hasClass("context-menu")) && (!x.parent().parent().hasClass("context-menu")) )
            if ( (x != Popmenu._currentTarget) && (x.closest("div.context-menu").size() == 0))
                // if (!$.browser.msie && $.browser.version == 6)
                Popmenu._Clear(); // disable for ie6
        });
    },
    Attach : function(element){

        // console.info(element);

        Popmenu._currentTarget = $(element);
        if (Popmenu._init) return;

        if (element.attr("_tag") == "profile_link"){
            // e = $(element).closest("[_class=entry]")
            e = $(element);
            g = (e.attr("_gender") == "M")? "male" : ((e.attr("_gender") == "F")? "female" : "unknown" );
            this._CreateTips(e.attr("_username"), e.attr("_userstatusmessage"), g);
        }
        else if(element.attr("_tag") == "ibuddy_preview"){
            this._CreateButton("set as profile photo", function(){
                aContainer = $(element).parent();
                aContainer.hide();
                aContainer.prependTo(aContainer.parent()).show();
                $.ajax({
                    url : 'index.php?r=user/productProfilePicture',
                    type : 'get',
                    dataType : 'text',
                    data : {
                        product_photo_id : element.attr("_productPhotoId"),
                        product_id : element.closest("a").attr("_productid")
                    },
                    success : function(){
                        aContainer.attr("_isprofile","1");
                        EventLog.Info("Profile photo has been set.");
                    }
                });
            });
            this._CreateButton("Delete", function(){
                deleteDialog = $("<div />").text("Are you sure to delete?").dialog({
                    title : "Delete",
                    resizable : false,
                    modal : true,
                    buttons : {
                        'Cancel' : function(){
                            $(this).dialog('destroy');
                        },
                        'Ok' : function(){
                            $.ajax({
                                type : 'get',
                                dataType : 'text',
                                url : 'index.php?r=user/deleteProductPicture',
                                data : {
                                    product_photo_id : element.attr("_productPhotoId"),
                                    product_id : element.closest("a").attr("_productid")
                                },
                                beforeSend : function(){

                                },
                                success : function(data){
                                    deleteDialog.dialog('destroy');
                                    Popmenu._currentTarget.remove();

                                    if (data == 1){
                                        EventLog.Info("Photo has been deleted");
                                        location.reload(true);
//                                        _container = $(".container", $("#widget-picture")).scrollLeft(0);
//                                        numOfPics = $("img", _container).size();
//                                        $(".inner", _container).width(60*numOfPics);
//                                        while($(".inner", _container).height()>100) $(".inner", _container).width($(".inner", _container).width()+10);
//
//                                        // if delete image is profile pic, make the zoomed back to default img
//                                        if ($("[_isprofilephoto=1]").size() == 0){
//                                            $("a[_class=currentPhoto]").children("img:first").attr("src", "images/resources/default_profile_image.jpg");
//                                        }
//
//                                        // if all pictures are deleted
//                                        if (numOfPics == 0){
//                                            $("a[_class=currentPhoto]").children("img:first").attr("src", "images/resources/default_profile_image.jpg");
//                                            $(".tips", $("#widget-picture")).next().hide().prev().show();
//                                        } else {
//                                            // change display pic to second picture
//                                            cur = $("img:first", _container).addClass("selected");
//                                            $("a[_class=currentPhoto]").children("img:first").attr("src", cur.parent().attr("_zoom"));
//                                        }

                                    } else {
                                        Event//log.error("An error occured while deleting. please try again.");
                                    }
                                },
                                error : function(){
                                    Event//log.error("An error occured while deleting. please try again.");
                                }
                            });
                        }
                    }
                });
            });
        }
        else if (element.attr("_tag") == "photo_preview"){

            this._CreateButton("set as profile photo", function(){
                // move pic to left
                aContainer = $(element).parent();
                aContainer.hide();
                aContainer.prependTo(aContainer.parent()).show();
                $.ajax({
                    url : 'index.php?r=user/profilePicture',
                    type : 'get',
                    dataType : 'text',
                    data : {
                        photo_id : $(element).attr("_photoid")
                    },
                    success : function(){
                        EventLog.Info("Profile photo has been set.");
                        _container = $(".container", $("#widget-picture"));
                        $("div.photoContainer", _container).removeClass("selected");
                        Popmenu._currentTarget.parent().parent().addClass("selected");
                        _container.animate({
                            scrollLeft : 0
                        }, 200, "linear");
                    }
                });
            });
            this._CreateButton("Delete", function(){
                deleteDialog = $("<div />").text("Are you sure to delete?").dialog({
                    title : "Delete",
                    resizable : false,
                    modal : true,
                    buttons : {
                        'Cancel' : function(){
                            $(this).dialog('destroy');
                        },
                        'Ok' : function(){
                            $.ajax({
                                type : 'get',
                                dataType : 'text',
                                url : 'index.php?r=user/deleteImage',
                                data : {
                                    object_id : Popmenu._currentTarget.attr("_photoid"),
                                    object_type : 1
                                },
                                beforeSend : function(){

                                },
                                success : function(data){
                                    deleteDialog.dialog('destroy');
                                    Popmenu._currentTarget.parent().parent().remove();

                                    if (data == 1){
                                        EventLog.Info("Photo has been deleted");

                                        _container = $(".container", $("#widget-picture")).scrollLeft(0);
                                        numOfPics = $("img", _container).size();
                                        $(".inner", _container).width(60*numOfPics);
                                        while($(".inner", _container).height()>100) $(".inner", _container).width($(".inner", _container).width()+10);

                                        // if delete image is profile pic, make the zoomed back to default img
                                        if ($("[_isprofilephoto=1]").size() == 0){
                                            $("div[_class=currentPhoto]").children('a').children("img:first").attr("src", "images/resources/default_profile_image.jpg");
                                        }

                                        // if all pictures are deleted
                                        if (numOfPics == 0){
                                            $("div.user-photo a img").attr("src", "images/resources/default_profile_image.jpg");
                                            $(".tips", $("#widget-picture")).next().hide().prev().show();
                                        } else {
                                            // change display pic to second picture
                                            cur = $("div.photoContainer:first", _container).addClass("selected");
                                            $("a[_class=currentPhoto]").children("img:first").attr("src", cur.children('a').attr("_zoom"));
                                        }

                                    } else {
                                        Event//log.error("An error occured while deleting. please try again.");
                                    }
                                },
                                error : function(){
                                    Event//log.error("An error occured while deleting. please try again.");
                                }
                            });
                        }
                    }
                });
            });
        } else if (element.attr("_tag") == "addFavourite"){
            $(element).blur();
            this._CreateTips("Confirm to add?");
            this._CreateButton("yes", function(){
                $.ajax({
                    url : "index.php?r=user/addFavourite",
                    type : "post",
                    data : {
                        // user_id : $("#pageInfo").attr("_userid")
						user_id : ($(element).attr("_userid") == null)? $("#pageInfo").attr("_userid") : $(element).attr("_userid")
                    },
                    success : function(data){
                        if (data == "1"){
                            EventLog.Info("User successfully added.");

//                            $("<div />").text("User successfully added.").dialog({
//                                title : "User Added",
//                                modal : true,
//                                resizable : false,
//                                buttons : {
//                                    'Close' : function(){
//                                        $(this).dialog('destroy');
//                                        $(this).remove();
//                                    }
//                                }
//                            });
                        } else if(data == "0") {
//                            $("<div />").text("Unknown Error.").dialog({
//                                title : "Error",
//                                modal : true,
//                                resizable : false,
//                                buttons : {
//                                    'Close' : function(){
//                                        $(this).dialog('destroy');
//                                        $(this).remove();
//                                    }
//                                }
//                            });
                        }
                    },
                    error : function(){
                        Event//log.error("User already exisits.");
//                        $("<div />").text("User already exists in your friend list.").dialog({
//                            title : "Error",
//                            modal : true,
//                            resizable : false,
//                            buttons : {
//                                'Close' : function(){
//                                    $(this).dialog('destroy');
//                                    $(this).remove();
//                                }
//                            }
//                        });
                    }
                });
            });
        } else if (element.hasClass("videoPreview")){
            this._CreateTips(element.attr("_description"));
        } else if (element.hasClass("emoticon")){
            Emoticon._currentEmoticon = $(element);
            // console.info('emoticon!');

            this._CreateButton("Play motion", function(){
                Emoticon.Run(element.attr("_hash"), "play");
            });

            this._CreateButton("download", function(){
                // Emoticon.Run(element.attr("_hash"), "download");
                if($("#widget-emoticonList").size()>0)
                    Downloader.Download(element.attr("_src"), "emoticon");
                else
					Downloader.Download(element.next("img").attr("src"), "emoticon");
            });
            if ($("#pageInfo").attr("_host") == '1') this._CreateButton("assign a motion…", function(){
                //log.info("Creating dialog for action select");
                if ($("#action-select").size() == 0){
                    $("<div id=\"action-select\" />").dialog({
                        title : "Select a motion or create a new one",
                        width : 600,
                        height : 400,
                        modal : true,
                        resizable : false,
                        buttons : {
                            'Cancel' : function(){
                                $(this).dialog('close')
                            },

                            'Ok' : function(){
                                el = $(".grid-entry-selected");
                                emoticon = Emoticon._currentEmoticon;
                                // console.info("Assigning sequence " + el.attr("sequence_id") + " on emoticon " + emoticon.next("img:hidden").attr("src"));
                                $.ajax({
                                    url : 'index.php?r=emoticon/assignMotion',
                                    type : 'post',
                                    dataType : 'json',
                                    data : {
                                        sequence_id : el.attr("sequence_id"),
                                        emoticon : emoticon.next("img:hidden").attr("src")
                                    },
                                    beforeSend : function(){
                                        $("#action-select").dialog('close');
                                        if ($("#assign-dialog").size() == 0){
                                            $("<div id=\"assign-dialog\" />").dialog({
                                                resizable : false,
                                                modal : true,
                                                title : 'Assigning…',
                                                height: 50,
                                                open : function(){
                                                    $("#assign-dialog").empty();
                                                    $("<p>Processing emoticon,  please wait...</p>").appendTo($("#assign-dialog"));
                                                    $("<div id=\"assign-progress-bar\" />").appendTo($("#assign-dialog")).progressbar({
                                                        value : 0
                                                    });
                                                    Emoticon._progress = setInterval(function(){
                                                        if (typeof Emoticon._progressValue == "undefined") Emoticon._progressValue = 0;
                                                        else Emoticon._progressValue += Math.random()*5;
                                                        $("#assign-progress-bar").progressbar('value', Emoticon._progressValue);
                                                        if (Emoticon._progressValue >= 99) clearInterval(Emoticon._progress);
                                                    }, 100);
                                                },
                                                close : function(){
                                                    $("#assign-progress-bar").progressbar('value', 0);
                                                    Emoticon._progressValue = 0;
                                                }
                                            });
                                        } else $("#assign-dialog").dialog('open');
                                    },
                                    success : function(data){
                                        setTimeout(function(){
                                            clearInterval(Emoticon._progress);
                                            $("#assign-progress-bar").progressbar('value', 100);
                                            setTimeout(function(){
                                                $("#assign-dialog").dialog('close');
                                                $("<div />").text("The motion has been assigned to the emoticon.").dialog({
                                                    modal : true,
                                                    resizable : false,
                                                    title : "Notice",
                                                    buttons : {
                                                        'Close' : function(){
                                                            $(this).dialog('close');
                                                        }
                                                    },
                                                    close : function(){
                                                        $(this).remove()
                                                    }
                                                });
                                            }, 500)
                                        // real works here
                                        }, 2000);
                                    },
                                    error : function(xhr){
                                        //log.error(xhr.status)
                                    }
                                });
                            },

                            'Create New' : function(){
                                Emoticon.Create();
                            // @todo disable this windows
                            },

                            'Play motion' : function(){
                                el = $(".grid-entry-selected");
                                // Emoticon.Run(el.attr("hash_id"), "play");
								$.ajax({
                                    url : 'index.php?r=emoticon/playMotion',
                                    type : 'get',
                                    data : {
                                        hash_id : el.attr("hash_id")
                                    },
                                    success : function(hash){
                                        Emoticon.Run(hash, "test");
                                    }
                                });
                            },

                            'Edit' : function(evt){
                                el = $(".grid-entry-selected");
                                Emoticon.Create(el.attr("sequence_id"));
                            },

                            'Delete' : function(){
                                deleteDialog = $("<div />").text("Are you sure to delete?").dialog({
                                    title : "Delete",
                                    resizable : false,
                                    modal : true,
                                    buttons : {
                                        'Cancel' : function(){
                                            $(this).dialog('destroy');
                                        },
                                        'Ok' : function(){
                                            $.ajax({
                                                type : 'get',
                                                dataType : 'text',
                                                url : 'index.php?r=user/deleteMotion',
                                                data : {
                                                    object_id : $(".grid-entry-selected").attr("sequence_id")
                                                },
                                                beforeSend : function(){

                                                },
                                                success : function(data){
                                                    deleteDialog.dialog('destroy');
                                                    if (data == 1){
                                                        Emoticon.UpdateListing();
                                                        EventLog.Info("The motion has been deleted");
                                                    } else {
                                                        Event//log.error("Delete failed");
                                                    }
                                                },
                                                error : function(){
                                                    deleteDialog.dialog('destroy');
                                                    Event//log.error("An error occured while deleting. please try again.");
                                                }
                                            });
                                        }
                                    }
                                });
                            }

                        },
                        open : function(){
                            //log.info("Disable buttons, wait for Ajax");
                            $("button:last", $("div.ui-dialog-buttonpane", $(this).parent()));
                            lastBtn = $("button:last", $("div.ui-dialog-buttonpane", $(this).parent()));

                            cBtn = lastBtn;
                            for (i = 0; i < 6; i++){
                                if (i < 4) cBtn.css("float", "left");

                                if (i != 3 && i!= 5){
                                    cBtn.attr("disabled", "disabled").addClass("ui-state-disabled");
                                    cBtn.attr("_toggleDisable", 1); // These buttons should be enabled upon a select
                                }

                                if (i == 3) cBtn.css("margin-left", 10);
                                cBtn = cBtn.prev();
                            }

                            $.ajax({
                                type : 'get',
                                url : 'index.php?r=emoticon/getMySequence',
                                dataType : 'json',
                                beforeSend : function(){
                                    //log.profile("Fetch action listing");
                                    $(".grid-entry.grid-entry-selected").removeClass("grid-entry-selected");
                                },
                                success : function(data){
                                    //log.profile("Fetch action listing");
                                    if (typeof ActionSelect != "object"){
                                        ActionSelect = new Grid({
                                            headers : {
                                                "Motion name" : '400px',
                                                "Last update" : '120px'
                                            },
                                            contents : ['name_key', 'lastupdate'],
                                            attributes : ['sequence_id', 'hash_id'],
                                            onCreate : function(){
                                                ActionSelect.fetchSequence(data);
                                            }
                                        });
                                        ActionSelect.Create($("#action-select"));
                                    } else {
                                        ActionSelect.fetchSequence(data);
                                    }
                                },
                                error : function(xhr){
                                    //log.profile("Fetch action listing");
                                    //log.error("Ajax request failed: " + xhr.status);
                                }
                            });
                        }
                    });
                } else {
                    $("#action-select").dialog('open');
                }
            });
            if ($("#pageInfo").attr("_host") == '1') this._CreateButton("Delete", function(){
                deleteDialog = $("<div />").text("Are you sure to delete?").dialog({
                    title : "Delete",
                    resizable : false,
                    modal : true,
                    buttons : {
                        'Cancel' : function(){
                            $(this).dialog('destroy');
                        },
                        'Ok' : function(){
                            $.ajax({
                                type : 'get',
                                dataType : 'text',
                                url : 'index.php?r=user/deleteImage',
                                data : {
                                    object_id : Popmenu._currentTarget.attr("_emoticonid"),
                                    object_type : 2
                                },
                                beforeSend : function(){

                                },
                                success : function(data){
                                    deleteDialog.dialog('destroy');
                                    if (data == 1){
                                        Popmenu._currentTarget.remove();
                                        EventLog.Info("Emoticon has been deleted.");
                                    } else {
                                        Event//log.error("An error occured while deleting. please try again.");
                                    }
                                    Emoticon.ManageDisplay();
                                }
                            });
                        }
                    }
                });
            });
        }
        // attach the popup to the object
        // get the center of the element
        offsetX = $(element).width()/2 + parseFloat($(element).css("paddingLeft"))*0.5 + parseFloat($(element).css("paddingRight"))*0.5;
        offsetY = $(element).height()/2 + parseFloat($(element).css("paddingTop"))*0.5 + parseFloat($(element).css("paddingBottom"))*0.5;
        pageOffset = $(element).offset();
        this._left = pageOffset.left + offsetX - Popmenu._el.width()/2;
        // this._top = pageOffset.top + offsetY - Popmenu._el.height() - 15;
        this._top = pageOffset.top - Popmenu._el.height();
        Popmenu._el.css("left", this._left).css("top", this._top).show();
        if ($(element).attr("_popmenu_init") != 1){
            $(element).mouseleave(function(evt){
                x = $(evt.relatedTarget);
                // if (x.hasClass("context-menu") || x.parent().hasClass("context-menu")) return;
                if (x.hasClass("context-menu") || (x.closest("div.context-menu").size() > 0) ) return;
                else if (x == Popmenu._currentTarget) return;
                else Popmenu._Clear();
            });
            $(element).attr("_popmenu_init", 1);
        }

        Popmenu._init = true;
    }
}

$(document).ready(function(){

    _popmenu = $("<div class=\"context-menu\" />").appendTo($("body:first")).hide();
    _ie6fix = $("<div class=\"ie6fix\" />").appendTo(_popmenu);
    // _popupper = $("<div class=\"upper\" />").appendTo(_popmenu);
    // _popmain = $("<div class=\"main\" />").appendTo(_popmenu);
    _popupper = $("<div class=\"upper\" />").appendTo(_ie6fix);
    _popmain = $("<div class=\"main\" />").appendTo(_ie6fix);

    Popmenu.Initialize(_popmenu);

});