<commit_before>window.onload = function() {
	'use strict';
	var ws = io.connect('', {transports: ['websocket']}),
	terminal = document.getElementById('terminal'),
	node = document.getElementById('cmd'),
	rowCnt = 0,
	aliases = {
		n: 'north',
		e: 'east',
		w: 'west',
		s: 'south',
		u: 'up',
		d: 'down',
		north: 'north',
		east: 'east',
		west: 'west',
		south: 'south',
		up: 'up',
		down: 'down',
		f: 'flee',
		l: 'look',
		ls: 'look',
		dir: 'look',
		i: 'inventory',
		sc: 'score',
		o: 'open',
		stats: 'score',
		eq: 'equipment',
		equip: 'wear',
		we: 'wear',
		q: 'quaff',
		c: 'cast',
		k: 'kill',
		re: 'rest',
		sl: 'sleep',
		h: 'help',
		wh: 'where',
		aff: 'affects',
		ooc: 'chat',
		slist: 'skills',
		skill: 'skills',
		desc: 'description',
		re: 'rest',
		r: 'recall',
		wake: 'stand',
		g: 'get'
	},
	isScrolledToBottom = false,
	movement = ['north', 'east', 'south', 'west', 'down', 'up'],
	playerIsLogged = null,
	display = function(r) {
		var i = 0;

		if (!r.styleClass) {
			r.styleClass = '';
		}

		if (r.element === undefined) {
			terminal.innerHTML += '

' + r.msg + '

';
		} else {
			terminal.innerHTML += '
<' + r.element + ' class="col-md-12 ' + r.styleClass + '">' + r.msg + '</' + r.element + '>
';
		}

		rowCnt += 1;

		if (rowCnt > 150) {
			for (i; i < 100; i += 1) {
				terminal.removeChild(document.getElementById( (i + 1) ));
			}

			rowCnt = 0;
		}

		isScrolledToBottom = terminal.scrollHeight - terminal.clientHeight <= terminal.scrollTop + 1;

		if (!isScrolledToBottom) {
			terminal.scrollTop = terminal.scrollHeight - terminal.clientHeight;
		}

		return parseCmd(r);
	},
	parseCmd = function(r) {
		if (r.msg !== undefined) {
			r.msg = r.msg.replace(/ /g, ' ').trim();
			ws.emit(r.emit, r);
		}
	},
	changeMudState = function(state) {
		document.getElementById('cmd').dataset.mudState = state;
	},
	checkMovement = function(cmdStr, fn) {
		if (movement.toString().indexOf(cmdStr) !== -1) {
			return fn(true, 'move ' + cmdStr);
		} else {
			return fn(false, cmdStr);
		}
	},
	checkAlias = function(cmdStr, fn) {
		var keys = Object.keys(aliases),
		i = 0,
		cmd,
		msg,
		keyLength = keys.length,
		cmdArr = cmdStr.split(' ');

		cmd = cmdArr[0].toLowerCase();
		msg = cmdArr.slice(1).join(' ');

		for (i; i < keyLength; i += 1) {
			if (keys[i] === cmd) {
				if (msg === '') {
					return fn(aliases[keys[i]]);
				} else {
					return fn(aliases[keys[i]] + ' ' + msg);
				}
			}
		}

		return fn(cmd + ' ' + msg);
	};

	document.getElementById('console').onsubmit = function (e) {
		var messageNodes = [],
		msg = node.value.toLowerCase().trim();

		display({
			msg : checkAlias(msg, function(cmd) {
				 return checkMovement(cmd, function(wasMov, cmd) {
					return cmd;
				});
			}),
			emit : (function () {
				var res = node.dataset.mudState;

				if (res === 'login') {
					return 'login';
				} else if (msg === 'quit' || msg === 'disconnect') {
					return 'quit';
				} else if (res === 'selectRace') {
					return 'raceSelection';
				} else if (res === 'selectClass') {
					return 'classSelection';
				} else if (res === 'createPassword') {
					return 'setPassword';
				} else if (res === 'enterPassword') {
					return 'password';
				} else {
					return 'cmd';
				}
			}()),
			styleClass: 'cmd'
		});

		node.value = '';
		node.focus();

		return false;
	};

	document.getElementById('cmd').focus();

	ws.on('msg', function(r) {
		display(r);

		if (r.res && r.res.toLowerCase().indexOf('password') !== -1) {
			node.type = 'password';
		} else {
			node.type = 'text';
		}

		if (r.res === 'end') {
			window.location.reload();
		}

		if (r.res) {
			changeMudState(r.res);
		}
	});
};
<commit_msg>client side fix for IE<commit_after>window.onload = function() {
	'use strict';
	var ws = io.connect('', {transports: ['websocket']}),
	terminal = document.getElementById('terminal'),
	node = document.getElementById('cmd'),
	rowCnt = 0,
	aliases = {
		n: 'north',
		e: 'east',
		w: 'west',
		s: 'south',
		u: 'up',
		d: 'down',
		north: 'north',
		east: 'east',
		west: 'west',
		south: 'south',
		up: 'up',
		down: 'down',
		f: 'flee',
		l: 'look',
		ls: 'look',
		dir: 'look',
		i: 'inventory',
		sc: 'score',
		o: 'open',
		stats: 'score',
		eq: 'equipment',
		equip: 'wear',
		we: 'wear',
		q: 'quaff',
		c: 'cast',
		k: 'kill',
		re: 'rest',
		sl: 'sleep',
		h: 'help',
		wh: 'where',
		aff: 'affects',
		ooc: 'chat',
		slist: 'skills',
		skill: 'skills',
		desc: 'description',
		r: 'recall',
		wake: 'stand',
		g: 'get'
	},
	isScrolledToBottom = false,
	movement = ['north', 'east', 'south', 'west', 'down', 'up'],
	playerIsLogged = null,
	display = function(r) {
		var i = 0;

		if (!r.styleClass) {
			r.styleClass = '';
		}

		if (r.element === undefined) {
			terminal.innerHTML += '

' + r.msg + '

';
		} else {
			terminal.innerHTML += '
<' + r.element + ' class="col-md-12 ' + r.styleClass + '">' + r.msg + '</' + r.element + '>
';
		}

		rowCnt += 1;

		if (rowCnt > 150) {
			for (i; i < 100; i += 1) {
				terminal.removeChild(document.getElementById( (i + 1) ));
			}

			rowCnt = 0;
		}

		isScrolledToBottom = terminal.scrollHeight - terminal.clientHeight <= terminal.scrollTop + 1;

		if (!isScrolledToBottom) {
			terminal.scrollTop = terminal.scrollHeight - terminal.clientHeight;
		}

		return parseCmd(r);
	},
	parseCmd = function(r) {
		if (r.msg !== undefined) {
			r.msg = r.msg.replace(/ /g, ' ').trim();
			ws.emit(r.emit, r);
		}
	},
	changeMudState = function(state) {
		document.getElementById('cmd').dataset.mudState = state;
	},
	checkMovement = function(cmdStr, fn) {
		if (movement.toString().indexOf(cmdStr) !== -1) {
			return fn(true, 'move ' + cmdStr);
		} else {
			return fn(false, cmdStr);
		}
	},
	checkAlias = function(cmdStr, fn) {
		var keys = Object.keys(aliases),
		i = 0,
		cmd,
		msg,
		keyLength = keys.length,
		cmdArr = cmdStr.split(' ');

		cmd = cmdArr[0].toLowerCase();
		msg = cmdArr.slice(1).join(' ');

		for (i; i < keyLength; i += 1) {
			if (keys[i] === cmd) {
				if (msg === '') {
					return fn(aliases[keys[i]]);
				} else {
					return fn(aliases[keys[i]] + ' ' + msg);
				}
			}
		}

		return fn(cmd + ' ' + msg);
	};

	document.getElementById('console').onsubmit = function (e) {
		var messageNodes = [],
		msg = node.value.toLowerCase().trim();

		display({
			msg : checkAlias(msg, function(cmd) {
				 return checkMovement(cmd, function(wasMov, cmd) {
					return cmd;
				});
			}),
			emit : (function () {
				var res = node.dataset.mudState;

				if (res === 'login') {
					return 'login';
				} else if (msg === 'quit' || msg === 'disconnect') {
					return 'quit';
				} else if (res === 'selectRace') {
					return 'raceSelection';
				} else if (res === 'selectClass') {
					return 'classSelection';
				} else if (res === 'createPassword') {
					return 'setPassword';
				} else if (res === 'enterPassword') {
					return 'password';
				} else {
					return 'cmd';
				}
			}()),
			styleClass: 'cmd'
		});

		node.value = '';
		node.focus();

		return false;
	};

	document.getElementById('cmd').focus();

	ws.on('msg', function(r) {
		display(r);

		if (r.res && r.res.toLowerCase().indexOf('password') !== -1) {
			node.type = 'password';
		} else {
			node.type = 'text';
		}

		if (r.res === 'end') {
			window.location.reload();
		}

		if (r.res) {
			changeMudState(r.res);
		}
	});
};
<|endoftext|>


<commit_before>jQuery(function($) {
    /*
    $('.admin-nav-bar').delegate('li a', 'click', function(e) {
        var url = $(this).attr('href');
        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("selected");
        });

        if(!deselect_this) {
            $(this).addClass('selected');
        }

        $.pjax({
            url: url
          , container: '.the-feedbacks'
          , success: function() {
              $('.status-change > select, .priority-change > select, div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
          }
        });

        e.preventDefault();
    });
    */

    $("abbr.timeago").timeago();

    $(document).delegate("a.cat-picks", "click", function(e) {

        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("Matched");
        });

        if(!deselect_this) {
            $(this).addClass('Matched');
        }

        var catpick = new CatPickObject($(this));
        catpick.process();
        catpick.undo();

        e.preventDefault();
    });

    $(document).delegate("a.menubtn", "click", function(e) {

        var deselect = false;

        $(this).parent().children('a.menubtn').each(function() {
            $(this).removeClass("matched");
        });

        if(!deselect) {
            $(this).addClass('matched');
        }

        $.ajax({
            type: "GET"
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                console.log("mathew");
                myStatus.notify("Processing...", 10000);
            }
        })

        e.preventDefault();
    })

    //for modify feedback bit
    $(document).delegate("a.flagged", "click", function(e) {
        $(this).toggleClass("matched");

        var state = $(this).attr('state');
        var var_state;
        if(state == 0) {
            $(this).attr('state', 1);
            var_state = 1;
        } else {
            $(this).attr('state', 0);
            var_state = 0;
        }

        $.ajax({
            type: "GET"
          , data: {"state": var_state}
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                myStatus.notify("Processing...", 1000);
            }
        })

        e.preventDefault();
    });

    $(document).delegate("a.delete", "click", function(e) {
        if(confirm("Are you sure you want to delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    $('.reply').bind("click", function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
        /*TODO WORK ON THIS LATER This should be a modal popup
        $.ajax({
            url: href
        });*/
    })

    var seen = {};
    $('.add-bcc > li').bind("click", function(e) {
        var pointer = $(this).index();
        var input = "<input type='text' name='bcc[]' value='"+$(this).text()+"' />  [x]";

        if(typeof seen[pointer] == 'undefined') {
           $("#bcc-target").append(input);
           seen[pointer] = true;
        }

        $(".delete-bcc").unbind("click.delete-bcc").bind("click.delete-bcc", function(e) {
            var del_pointer = $(this).attr('id');
            $(this).prev('input').remove().end().remove();
            delete seen[del_pointer];
            e.preventDefault();
        })

        e.preventDefault();
    })

    //check theme 1 by default
    $("#themeId_1 input:radio").attr('checked', true);

    //FastForward Email Block...fuck this is a mess...
    $('div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
    var mouse_is_inside = false;
    $('.contact, .fileas, .forward').hover(function() {
        mouse_is_inside = true;
    }, function() {
        mouse_is_inside = false;
    });

    $(document).delegate(".fileas", "click", function(e) {
        var id = $(this).attr('id');
        $('#' + id + ' div.category-picker-holder').show().hover(function() {
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $('textarea[name="email_comment"]').bind("focus", function() {
        $(this).val("");
    })

    //fucking bug where in for some reason jquery cannot select the div.fast-forward-holder element when using the forward class name.
    $(document).delegate(".contact, .forward", "click", function(e) {
        var id = $(this).attr('id');
        var selector;

        var class_name = $(this).attr('class');

        if(class_name == 'contact') {
            selector = $('#' + id + ' div.fast-forward-holder');
        }

        if(class_name == 'forward') {
            selector = $('#' + id);
        }

        selector.show()
        .hover(function() {
            $('div.email-list > ul.email-picker li', this)
            .live('click', function() {
                var me = $(this);
                me.parent().hide()
                       .siblings('.ff-form')
                       .ajaxForm({
                            success: function() {
                                me.parents('div.fast-forward-holder').hide().end()
                                  .parents('.email-picker').show().end()
                                  .parent().siblings('.ff-form').hide().children('.ff-forward-to').html("").end();
                                $('textarea[name="email_comment"]').val("");
                                alert("Fast-forward sent to " + $('a', me).text());
                            }
                        })
                           .children('.ff-forward-to').html($(this).html()).end()
                           .children('input[name="email"]').val($('a', this).html()).end()
                       .show();
            });
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $("body").click(function() {
        if(!mouse_is_inside) {
            $('div.fast-forward-holder, div.category-picker-holder, .ff-form').hide();
            $('.email-picker').show();
            $('textarea[name="email_comment"]').val("");
        }
    })

    //End of FastForward
    new InboxStatusChange('.check, .feature, .remove, .popup-delete').initialize();
    $('div.undo-bar').hide();

    //TODO: Please update
    $('.flag').switcharoo('-100px 0px');

    $.each($('ul#nav-menu li'), function(index, value) {
        $(value).bind('click', function(e) {
            window.location = $(this).children('a').attr('href');
        });
    });

    var check = new Checky({
        feed_selection: '.feed-selection'
      , check_feed_id: '.check-feed-id'
      , category_feed_id: '.category-feed-id'
      , click_all: '.click-all'
    });

    check.init();
    check.clickAll();

    $('.status-change > select, .priority-change > select').hide();

    var statusChange = new DropDownChange({status_element: 'span.status-change', status_selector: 'change.status'});
    statusChange.enable();
    var priorityChange = new DropDownChange({status_element: 'span.priority-change', status_selector: 'change.priority'});
    priorityChange.enable();

    $('.check').fancytips();
    $('.fileas').fancytips();
    $('.reply').fancytips();
    $('.feature').fancytips();
    $('.contact').fancytips();
    $('.flag').fancytips();
    $('.remove').fancytips({'top': 45});

    $('a.perm-delete').click(function(e) {
        if(confirm("Are you sure you want to permanently delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    CategoryControl();

    $('a.add-new-ctgy').bind("click", function(e) {
        var ctgy_nm = $("input[name='category_nm']");
        var ctgy_list = $("#ctgy-list");

        if(ctgy_nm.val() == false)
            alert("Category Name cannot be blank.");
        else
            $.ajax({
                url: ctgy_list.attr('hrefaction')
              , type: "POST"
              , data: {ctgy_nm: ctgy_nm.val(), companyId: $("input[name='companyid']").val()}
              , success: function(msg) {
                  ctgy_list.append(msg);
                  ctgy_nm.val("");
                  CategoryControl();
              }
            });

        e.preventDefault();
    })

    function CategoryControl() {
       $('a.rename-ctgy, a.delete-ctgy').unbind('click.ctgy-controls').bind('click.ctgy-controls', function(e) {
           var class_name = $(this).attr('class');
           var that = $(this);

           if(class_name == 'rename-ctgy') {
               var input = $('<input type="text" name="ctgy_nm"/>').val(
                   that.parents('div').siblings('div').children('.ctgy-name').html()
               );

              if(that.text() == "Update") {
                  var ctgy_nm_val = $('input[name="ctgy_nm"]').val()
                  console.log("Rename");
                  that.text("Rename")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( ctgy_nm_val ).end().end().end()
                  $.ajax({ url: that.attr('href'), type: "POST", data: {ctgy_nm: ctgy_nm_val} });
              } else {
                  that.text("Update")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( input ).end().end().end()
              }

           }

           if(class_name == 'delete-ctgy') {
              var d = that.parents('div.grids');
              if(confirm("Are you sure you want to delete this category? There is no undo.")) {
                  $.ajax({ url: $(this).attr('href'), success: function(msg) { d.fadeOut(); } });
              }
           }

           e.preventDefault();
       })
    }

    var jcrop_api, set_image;
    function initJcrop() {
        $('#jcrop_target').Jcrop({
            setSelect: ['40','20','190','170']
          , boxWidth: 350
          , boxHeight: 230
          , aspectRatio: 1
          , onChange: showPreview
          , onSelect: showPreview
        }, function() {
            jcrop_api = this;
        });
    }

    function showPreview(coords) {

        var rx = 100 / coords.w;
        var ry = 100 / coords.h;
        var target = $('#jcrop_target');
        var hgt = target.height();
        var wdt = target.width();

        $('#x').val(coords.x);
        $('#y').val(coords.y);
        $('#w').val(coords.w);
        $('#h').val(coords.h);

        $('#preview').css({
            width: Math.round(rx * wdt) + 'px',
            height: Math.round(ry * hgt) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    };

    $('div.adjust-crop').hide();
    $(document).delegate("#your_photo", "change", function() {
		$.ajaxFileUpload ({
            url: $("#ajax-upload-url").attr('hrefaction'),
            secureuri:false,
            fileElementId:'your_photo',
            dataType: 'json',
            success: function (data, status) {

                var myStatus = new Status();
                myStatus.notify("Photo Upload Success!", 1000);

                var file = "/" + data.dir;
                var width = Math.round(data.wid);
                var jcrop_div = $("div.jcrop_div");
                var existing_avatar = $('input[name="existing_avatar"]');

                $('div.adjust-crop').show();

                $('#profile_picture').attr('src',file);
                $('#jcrop_target').attr('src',file);
                $('#preview').attr('src',file);

                if(jcrop_api) {
                    jcrop_api.setImage($('#profile_picture').attr('src'));
                    jcrop_api.setSelect(['40','20','190','170']);
                }

                if(existing_avatar.length > 0) {
                    $.post($("#ajax-delete-existing-avatar").attr('hrefaction'), {avatar: existing_avatar.val()});
                }

                jcrop_div.css({'width':width});
                $('input[name="orig_image_dir"]').val(file);
                initJcrop();

            }
		});
    });

    $('#cropbtn').click(function(){
        var x_coords = $('#x').val();
        var y_coords = $('#y').val();
        var wd = $('#w').val();
        var ht = $('#h').val();
        var cropped_photo = $('#preview').attr('src');
		var crop_status = $('#crop_status');
		var oldphoto = $('#cropped_photo').val();
        var data = {src: cropped_photo, x_coords: x_coords, y_coords: y_coords, wd: wd, ht: ht, oldphoto: oldphoto, login_type: 36};
        crop_status.html(' Cropping Photo...');

        $.ajax({
            url: $("#ajax-crop-url").attr('hrefaction')
          , type: "POST"
          , data: data
          , success: function(data){
                crop_status.fadeOut('fast',function(){
                    $('#cropped_photo').val(data);
                });
                var myStatus = new Status();
                myStatus.notify("Your photo is successfully cropped! If you feel this is the right photo for you please click on the Save Settings button.", 7000);

            }
        });
    });

    $(document).delegate('a.save', 'click', function(e) {
        var textarea = $('.feedback-textarea');
        var hrefaction = textarea.attr('hrefaction');

        var feed_id = $('#feed-id').val();
        $.post(hrefaction, { feed_id: feed_id, feedback_text: textarea.val() }, function(msg) {
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        });
        e.preventDefault();
    });

    $('a.admin-delete').bind('click', function(e) {
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            return true;
        }
        e.preventDefault();
    });

    $('.contact-edit').bind('click', function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
    });

    $('.contact-delete').bind('click', function(e) {
        var hrefaction= $(this).attr('hrefaction');
        var that = this;
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            $.get(hrefaction, function(msg) {
                $(that).parents('tr').fadeOut(350);
            });
        }
        e.preventDefault();
    });

    $('.copycheck').hide();
    $("#widget-preview").hide();
    new ZClip();
});
<commit_msg>debuggin<commit_after>jQuery(function($) {
    /*
    $('.admin-nav-bar').delegate('li a', 'click', function(e) {
        var url = $(this).attr('href');
        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("selected");
        });

        if(!deselect_this) {
            $(this).addClass('selected');
        }

        $.pjax({
            url: url
          , container: '.the-feedbacks'
          , success: function() {
              $('.status-change > select, .priority-change > select, div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
          }
        });

        e.preventDefault();
    });
    */

    $("abbr.timeago").timeago();

    $(document).delegate("a.cat-picks", "click", function(e) {

        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("Matched");
        });

        if(!deselect_this) {
            $(this).addClass('Matched');
        }

        var catpick = new CatPickObject($(this));
        catpick.process();
        catpick.undo();

        e.preventDefault();
    });

    $(document).delegate("a.menubtn", "click", function(e) {

        var deselect = false;

        $(this).parent().children('a.menubtn').each(function() {
            $(this).removeClass("matched");
        });

        if(!deselect) {
            $(this).addClass('matched');
        }

        $.ajax({
            type: "GET"
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                console.log("mathew");
                myStatus.notify("Processing...", 10000);
            }
        })

        e.preventDefault();
    })

    //for modify feedback bit
    $(document).delegate("a.flagged", "click", function(e) {
        $(this).toggleClass("matched");

        var state = $(this).attr('state');
        var var_state;
        if(state == 0) {
            $(this).attr('state', 1);
            var_state = 1;
        } else {
            $(this).attr('state', 0);
            var_state = 0;
        }

        $.ajax({
            type: "GET"
          , data: {"state": var_state}
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                myStatus.notify("Processing...", 1000);
            }
        })

        e.preventDefault();
    });

    $(document).delegate("a.delete", "click", function(e) {
        if(confirm("Are you sure you want to delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    $('.reply').bind("click", function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
        /*TODO WORK ON THIS LATER This should be a modal popup
        $.ajax({
            url: href
        });*/
    })

    var seen = {};
    $('.add-bcc > li').bind("click", function(e) {
        var pointer = $(this).index();
        var input = "<input type='text' name='bcc[]' value='"+$(this).text()+"' />  [x]";

        if(typeof seen[pointer] == 'undefined') {
           $("#bcc-target").append(input);
           seen[pointer] = true;
        }

        $(".delete-bcc").unbind("click.delete-bcc").bind("click.delete-bcc", function(e) {
            var del_pointer = $(this).attr('id');
            $(this).prev('input').remove().end().remove();
            delete seen[del_pointer];
            e.preventDefault();
        })

        e.preventDefault();
    })

    //check theme 1 by default
    $("#themeId_1 input:radio").attr('checked', true);

    //FastForward Email Block...fuck this is a mess...
    $('div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
    var mouse_is_inside = false;
    $('.contact, .fileas, .forward').hover(function() {
        mouse_is_inside = true;
    }, function() {
        mouse_is_inside = false;
    });

    $(document).delegate(".fileas", "click", function(e) {
        var id = $(this).attr('id');
        $('#' + id + ' div.category-picker-holder').show().hover(function() {
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $('textarea[name="email_comment"]').bind("focus", function() {
        $(this).val("");
    })

    //fucking bug where in for some reason jquery cannot select the div.fast-forward-holder element when using the forward class name.
    $(document).delegate(".contact, .forward", "click", function(e) {
        var id = $(this).attr('id');
        var selector;

        var class_name = $(this).attr('class');

        if(class_name == 'contact') {
            selector = $('#' + id + ' div.fast-forward-holder');
        }

        if(class_name == 'forward') {
            selector = $('#' + id);
        }

        selector.show()
        .hover(function() {
            $('div.email-list > ul.email-picker li', this)
            .live('click', function() {
                var me = $(this);
                me.parent().hide()
                       .siblings('.ff-form')
                       .ajaxForm({
                            success: function() {
                                me.parents('div.fast-forward-holder').hide().end()
                                  .parents('.email-picker').show().end()
                                  .parent().siblings('.ff-form').hide().children('.ff-forward-to').html("").end();
                                $('textarea[name="email_comment"]').val("");
                                alert("Fast-forward sent to " + $('a', me).text());
                            }
                        })
                           .children('.ff-forward-to').html($(this).html()).end()
                           .children('input[name="email"]').val($('a', this).html()).end()
                       .show();
            });
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $("body").click(function() {
        if(!mouse_is_inside) {
            $('div.fast-forward-holder, div.category-picker-holder, .ff-form').hide();
            $('.email-picker').show();
            $('textarea[name="email_comment"]').val("");
        }
    })

    //End of FastForward
    new InboxStatusChange('.check, .feature, .remove, .popup-delete').initialize();
    $('div.undo-bar').hide();

    //TODO: Please update
    $('.flag').switcharoo('-100px 0px');

    $.each($('ul#nav-menu li'), function(index, value) {
        $(value).bind('click', function(e) {
            window.location = $(this).children('a').attr('href');
        });
    });

    var check = new Checky({
        feed_selection: '.feed-selection'
      , check_feed_id: '.check-feed-id'
      , category_feed_id: '.category-feed-id'
      , click_all: '.click-all'
    });

    check.init();
    check.clickAll();

    $('.status-change > select, .priority-change > select').hide();

    var statusChange = new DropDownChange({status_element: 'span.status-change', status_selector: 'change.status'});
    statusChange.enable();
    var priorityChange = new DropDownChange({status_element: 'span.priority-change', status_selector: 'change.priority'});
    priorityChange.enable();

    $('.check').fancytips();
    $('.fileas').fancytips();
    $('.reply').fancytips();
    $('.feature').fancytips();
    $('.contact').fancytips();
    $('.flag').fancytips();
    $('.remove').fancytips({'top': 45});

    $('a.perm-delete').click(function(e) {
        if(confirm("Are you sure you want to permanently delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    CategoryControl();

    $('a.add-new-ctgy').bind("click", function(e) {
        var ctgy_nm = $("input[name='category_nm']");
        var ctgy_list = $("#ctgy-list");

        if(ctgy_nm.val() == false)
            alert("Category Name cannot be blank.");
        else
            $.ajax({
                url: ctgy_list.attr('hrefaction')
              , type: "POST"
              , data: {ctgy_nm: ctgy_nm.val(), companyId: $("input[name='companyid']").val()}
              , success: function(msg) {
                  ctgy_list.append(msg);
                  ctgy_nm.val("");
                  CategoryControl();
              }
            });

        e.preventDefault();
    })

    function CategoryControl() {
       $('a.rename-ctgy, a.delete-ctgy').unbind('click.ctgy-controls').bind('click.ctgy-controls', function(e) {
           var class_name = $(this).attr('class');
           var that = $(this);

           if(class_name == 'rename-ctgy') {
               var input = $('<input type="text" name="ctgy_nm"/>').val(
                   that.parents('div').siblings('div').children('.ctgy-name').html()
               );

              if(that.text() == "Update") {
                  var ctgy_nm_val = $('input[name="ctgy_nm"]').val()
                  console.log("Rename");
                  that.text("Rename")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( ctgy_nm_val ).end().end().end()
                  $.ajax({ url: that.attr('href'), type: "POST", data: {ctgy_nm: ctgy_nm_val} });
              } else {
                  that.text("Update")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( input ).end().end().end()
              }

           }

           if(class_name == 'delete-ctgy') {
              var d = that.parents('div.grids');
              if(confirm("Are you sure you want to delete this category? There is no undo.")) {
                  $.ajax({ url: $(this).attr('href'), success: function(msg) { d.fadeOut(); } });
              }
           }

           e.preventDefault();
       })
    }

    var jcrop_api, set_image;
    function initJcrop() {
        $('#jcrop_target').Jcrop({
            setSelect: ['40','20','190','170']
          , boxWidth: 350
          , boxHeight: 230
          , aspectRatio: 1
          , onChange: showPreview
          , onSelect: showPreview
        }, function() {
            jcrop_api = this;
        });
    }

    function showPreview(coords) {

        var rx = 100 / coords.w;
        var ry = 100 / coords.h;
        var target = $('#jcrop_target');
        var hgt = target.height();
        var wdt = target.width();

        $('#x').val(coords.x);
        $('#y').val(coords.y);
        $('#w').val(coords.w);
        $('#h').val(coords.h);

        $('#preview').css({
            width: Math.round(rx * wdt) + 'px',
            height: Math.round(ry * hgt) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    };

    $('div.adjust-crop').hide();
    $(document).delegate("#your_photo", "change", function() {
		$.ajaxFileUpload ({
            url: $("#ajax-upload-url").attr('hrefaction'),
            secureuri:false,
            fileElementId:'your_photo',
            dataType: 'json',
            success: function (data, status) {

                var myStatus = new Status();
                myStatus.notify("Photo Upload Success!", 1000);

                var file = "/" + data.dir;
                var width = Math.round(data.wid);
                var jcrop_div = $("div.jcrop_div");
                var existing_avatar = $('input[name="existing_avatar"]');

                $('div.adjust-crop').show();

                $('#profile_picture').attr('src',file);
                $('#jcrop_target').attr('src',file);
                $('#preview').attr('src',file);

                if(jcrop_api) {
                    jcrop_api.setImage($('#profile_picture').attr('src'));
                    jcrop_api.setSelect(['40','20','190','170']);
                }

                if(existing_avatar.length > 0) {
                    $.post($("#ajax-delete-existing-avatar").attr('hrefaction'), {avatar: existing_avatar.val()});
                }

                jcrop_div.css({'width':width});
                $('input[name="orig_image_dir"]').val(file);
                initJcrop();

            }
		});
    });

    $('#cropbtn').click(function(){
        var x_coords = $('#x').val();
        var y_coords = $('#y').val();
        var wd = $('#w').val();
        var ht = $('#h').val();
        var cropped_photo = $('#preview').attr('src');
		var crop_status = $('#crop_status');
		var oldphoto = $('#cropped_photo').val();
        var data = {src: cropped_photo, x_coords: x_coords, y_coords: y_coords, wd: wd, ht: ht, oldphoto: oldphoto, login_type: 36};
        crop_status.html(' Cropping Photo...');

        $.ajax({
            url: $("#ajax-crop-url").attr('hrefaction')
          , type: "POST"
          , data: data
          , success: function(data){
              /*
                crop_status.fadeOut('fast',function(){
                    $('#cropped_photo').val(data);
                });
                */
              console.log(data);
                var myStatus = new Status();
                myStatus.notify("Your photo is successfully cropped! If you feel this is the right photo for you please click on the Save Settings button.", 7000);

                $('div.adjust-crop').hide();
            }
        });
    });

    $(document).delegate('a.save', 'click', function(e) {
        var textarea = $('.feedback-textarea');
        var hrefaction = textarea.attr('hrefaction');

        var feed_id = $('#feed-id').val();
        $.post(hrefaction, { feed_id: feed_id, feedback_text: textarea.val() }, function(msg) {
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        });
        e.preventDefault();
    });

    $('a.admin-delete').bind('click', function(e) {
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            return true;
        }
        e.preventDefault();
    });

    $('.contact-edit').bind('click', function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
    });

    $('.contact-delete').bind('click', function(e) {
        var hrefaction= $(this).attr('hrefaction');
        var that = this;
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            $.get(hrefaction, function(msg) {
                $(that).parents('tr').fadeOut(350);
            });
        }
        e.preventDefault();
    });

    $('.copycheck').hide();
    $("#widget-preview").hide();
    new ZClip();
});
<|endoftext|>


<commit_before>/* @flow */

import { CompositeDisposable, File } from "atom";
import {
  observable,
  computed,
  action,
  isObservableMap,
  keys,
  values
} from "mobx";
import {
  isMultilanguageGrammar,
  getEmbeddedScope,
  isUnsavedFilePath
} from "./../utils";
import _ from "lodash";

import Config from "./../config";
import * as codeManager from "./../code-manager";
import MarkerStore from "./markers";
import kernelManager from "./../kernel-manager";
import Kernel from "./../kernel";

const commutable = require("@nteract/commutable");

export class Store {
  subscriptions = new CompositeDisposable();
  @observable
  markersMapping: Map<number, MarkerStore> = new Map();
  @observable
  runningKernels: Array<Kernel> = [];
  @observable
  kernelMapping: KernelMapping = new Map();
  @observable
  startingKernels: Map<string, boolean> = new Map();
  @observable
  editor = atom.workspace.getActiveTextEditor();
  @observable
  grammar: ?atom$Grammar;
  @observable
  configMapping: Map<string, ?mixed> = new Map();
  globalMode: boolean = Boolean(atom.config.get("Hydrogen.globalMode"));

  @computed
  get kernel(): ?Kernel {
    if (!this.grammar || !this.editor) return null;

    if (this.globalMode) {
      const currentScopeName = this.grammar.scopeName;
      return this.runningKernels.find(
        k => k.grammar.scopeName === currentScopeName
      );
    }
    const file = this.filePath;
    if (!file) return null;
    const kernelOrMap = this.kernelMapping.get(file);
    if (!kernelOrMap) return null;
    if (kernelOrMap instanceof Kernel) return kernelOrMap;
    return this.grammar && this.grammar.name
      ? kernelOrMap.get(this.grammar.name)
      : null;
  }

  @computed
  get filePath(): ?string {
    const editor = this.editor;
    if (!editor) return null;
    const savedFilePath = editor.getPath();
    return savedFilePath ? savedFilePath : `Unsaved Editor ${editor.id}`;
  }

  @computed
  get filePaths(): Array<string> {
    return keys(this.kernelMapping);
  }

  @computed
  get notebook() {
    const editor = this.editor;
    if (!editor) return null;
    let notebook = commutable.emptyNotebook;
    if (this.kernel) {
      notebook = notebook.setIn(
        ["metadata", "kernelspec"],
        this.kernel.transport.kernelSpec
      );
    }
    const cellRanges = codeManager.getCells(editor);
    _.forEach(cellRanges, cell => {
      const { start, end } = cell;
      let source = codeManager.getTextInRange(editor, start, end);
      source = source ? source : "";
      // When the cell marker following a given cell range is on its own line,
      // the newline immediately preceding that cell marker is included in
      // `source`. We remove that here. See #1512 for more details.
      if (source.slice(-1) === "\n") source = source.slice(0, -1);
      const cellType = codeManager.getMetadataForRow(editor, start);
      let newCell;
      if (cellType === "codecell") {
        newCell = commutable.emptyCodeCell.set("source", source);
      } else if (cellType === "markdown") {
        source = codeManager.removeCommentsMarkdownCell(editor, source);
        newCell = commutable.emptyMarkdownCell.set("source", source);
      }
      notebook = commutable.appendCellToNotebook(notebook, newCell);
    });
    return commutable.toJS(notebook);
  }

  @computed
  get markers(): ?MarkerStore {
    const editor = this.editor;
    if (!editor) return null;
    const markerStore = this.markersMapping.get(editor.id);
    return markerStore ? markerStore : this.newMarkerStore(editor.id);
  }

  @action
  newMarkerStore(editorId: number) {
    const markerStore = new MarkerStore();
    this.markersMapping.set(editorId, markerStore);
    return markerStore;
  }

  @action
  startKernel(kernelDisplayName: string) {
    this.startingKernels.set(kernelDisplayName, true);
  }

  addFileDisposer(editor: atom$TextEditor, filePath: string) {
    const fileDisposer = new CompositeDisposable();

    if (isUnsavedFilePath(filePath)) {
      fileDisposer.add(
        editor.onDidSave(event => {
          fileDisposer.dispose();
          this.addFileDisposer(editor, event.path); // Add another `fileDisposer` once it's saved
        })
      );
      fileDisposer.add(
        editor.onDidDestroy(() => {
          this.kernelMapping.delete(filePath);
          fileDisposer.dispose();
        })
      );
    } else {
      const file: atom$File = new File(filePath);
      fileDisposer.add(
        file.onDidDelete(() => {
          this.kernelMapping.delete(filePath);
          fileDisposer.dispose();
        })
      );
    }

    this.subscriptions.add(fileDisposer);
  }

  @action
  newKernel(
    kernel: Kernel,
    filePath: string,
    editor: atom$TextEditor,
    grammar: atom$Grammar
  ) {
    if (isMultilanguageGrammar(editor.getGrammar())) {
      if (!this.kernelMapping.has(filePath)) {
        this.kernelMapping.set(filePath, new Map());
      }
      const multiLanguageMap = this.kernelMapping.get(filePath);
      if (multiLanguageMap) multiLanguageMap.set(grammar.name, kernel);
    } else {
      this.kernelMapping.set(filePath, kernel);
    }
    this.addFileDisposer(editor, filePath);
    const index = this.runningKernels.findIndex(k => k === kernel);
    if (index === -1) {
      this.runningKernels.push(kernel);
    }
    // delete startingKernel since store.kernel now in place to prevent duplicate kernel
    this.startingKernels.delete(kernel.kernelSpec.display_name);
  }

  @action
  deleteKernel(kernel: Kernel) {
    const grammar = kernel.grammar.name;
    const files = this.getFilesForKernel(kernel);

    files.forEach(file => {
      const kernelOrMap = this.kernelMapping.get(file);
      if (!kernelOrMap) return;
      if (kernelOrMap instanceof Kernel) {
        this.kernelMapping.delete(file);
      } else {
        kernelOrMap.delete(grammar);
      }
    });

    this.runningKernels = this.runningKernels.filter(k => k !== kernel);
  }

  getFilesForKernel(kernel: Kernel): Array<string> {
    const grammar = kernel.grammar.name;
    return this.filePaths.filter(file => {
      const kernelOrMap = this.kernelMapping.get(file);
      if (!kernelOrMap) return [];
      return kernelOrMap instanceof Kernel
        ? kernelOrMap === kernel
        : kernelOrMap.get(grammar) === kernel;
    });
  }

  @action
  dispose() {
    this.subscriptions.dispose();
    this.markersMapping.forEach(markerStore => markerStore.clear());
    this.markersMapping.clear();
    this.runningKernels.forEach(kernel => kernel.destroy());
    this.runningKernels = [];
    this.kernelMapping.clear();
  }

  @action
  updateEditor(editor: ?atom$TextEditor) {
    this.editor = editor;
    this.setGrammar(editor);

    if (this.globalMode && this.kernel && editor) {
      const fileName = editor.getPath();
      if (!fileName) return;
      this.kernelMapping.set(fileName, this.kernel);
    }
  }

  // Returns the embedded grammar for multilanguage, normal grammar otherwise
  getEmbeddedGrammar(editor: atom$TextEditor): ?atom$Grammar {
    const grammar = editor.getGrammar();
    if (!isMultilanguageGrammar(grammar)) {
      return grammar;
    }

    const embeddedScope = getEmbeddedScope(
      editor,
      editor.getCursorBufferPosition()
    );

    if (!embeddedScope) return grammar;
    const scope = embeddedScope.replace(".embedded", "");
    return atom.grammars.grammarForScopeName(scope);
  }

  @action
  setGrammar(editor: ?atom$TextEditor) {
    if (!editor) {
      this.grammar = null;
      return;
    }

    this.grammar = this.getEmbeddedGrammar(editor);
  }

  @action
  setConfigValue(keyPath: string, newValue: ?mixed) {
    if (!newValue) {
      newValue = atom.config.get(keyPath);
    }
    this.configMapping.set(keyPath, newValue);
  }

  /**
   * Force mobx to recalculate filePath (which depends on editor observable)
   */
  forceEditorUpdate() {
    const currentEditor = this.editor;
    if (!currentEditor) return;

    const oldKey = this.filePath;
    if (!oldKey) return;
    // Return back if the kernel for this editor is already disposed.
    if (!this.kernelMapping.has(oldKey)) return;

    this.updateEditor(null);
    this.updateEditor(currentEditor);
    const newKey = this.filePath;
    if (!newKey) return;

    // Change key of kernelMapping from editor ID to file path
    this.kernelMapping.set(newKey, this.kernelMapping.get(oldKey));
    this.kernelMapping.delete(oldKey);
  }
}

const store = new Store();
export default store;

// For debugging
window.hydrogen_store = store;
<commit_msg>fix return value<commit_after>/* @flow */

import { CompositeDisposable, File } from "atom";
import {
  observable,
  computed,
  action,
  isObservableMap,
  keys,
  values
} from "mobx";
import {
  isMultilanguageGrammar,
  getEmbeddedScope,
  isUnsavedFilePath
} from "./../utils";
import _ from "lodash";

import Config from "./../config";
import * as codeManager from "./../code-manager";
import MarkerStore from "./markers";
import kernelManager from "./../kernel-manager";
import Kernel from "./../kernel";

const commutable = require("@nteract/commutable");

export class Store {
  subscriptions = new CompositeDisposable();
  @observable
  markersMapping: Map<number, MarkerStore> = new Map();
  @observable
  runningKernels: Array<Kernel> = [];
  @observable
  kernelMapping: KernelMapping = new Map();
  @observable
  startingKernels: Map<string, boolean> = new Map();
  @observable
  editor = atom.workspace.getActiveTextEditor();
  @observable
  grammar: ?atom$Grammar;
  @observable
  configMapping: Map<string, ?mixed> = new Map();
  globalMode: boolean = Boolean(atom.config.get("Hydrogen.globalMode"));

  @computed
  get kernel(): ?Kernel {
    if (!this.grammar || !this.editor) return null;

    if (this.globalMode) {
      const currentScopeName = this.grammar.scopeName;
      return this.runningKernels.find(
        k => k.grammar.scopeName === currentScopeName
      );
    }
    const file = this.filePath;
    if (!file) return null;
    const kernelOrMap = this.kernelMapping.get(file);
    if (!kernelOrMap) return null;
    if (kernelOrMap instanceof Kernel) return kernelOrMap;
    return this.grammar && this.grammar.name
      ? kernelOrMap.get(this.grammar.name)
      : null;
  }

  @computed
  get filePath(): ?string {
    const editor = this.editor;
    if (!editor) return null;
    const savedFilePath = editor.getPath();
    return savedFilePath ? savedFilePath : `Unsaved Editor ${editor.id}`;
  }

  @computed
  get filePaths(): Array<string> {
    return keys(this.kernelMapping);
  }

  @computed
  get notebook() {
    const editor = this.editor;
    if (!editor) return null;
    let notebook = commutable.emptyNotebook;
    if (this.kernel) {
      notebook = notebook.setIn(
        ["metadata", "kernelspec"],
        this.kernel.transport.kernelSpec
      );
    }
    const cellRanges = codeManager.getCells(editor);
    _.forEach(cellRanges, cell => {
      const { start, end } = cell;
      let source = codeManager.getTextInRange(editor, start, end);
      source = source ? source : "";
      // When the cell marker following a given cell range is on its own line,
      // the newline immediately preceding that cell marker is included in
      // `source`. We remove that here. See #1512 for more details.
      if (source.slice(-1) === "\n") source = source.slice(0, -1);
      const cellType = codeManager.getMetadataForRow(editor, start);
      let newCell;
      if (cellType === "codecell") {
        newCell = commutable.emptyCodeCell.set("source", source);
      } else if (cellType === "markdown") {
        source = codeManager.removeCommentsMarkdownCell(editor, source);
        newCell = commutable.emptyMarkdownCell.set("source", source);
      }
      notebook = commutable.appendCellToNotebook(notebook, newCell);
    });
    return commutable.toJS(notebook);
  }

  @computed
  get markers(): ?MarkerStore {
    const editor = this.editor;
    if (!editor) return null;
    const markerStore = this.markersMapping.get(editor.id);
    return markerStore ? markerStore : this.newMarkerStore(editor.id);
  }

  @action
  newMarkerStore(editorId: number) {
    const markerStore = new MarkerStore();
    this.markersMapping.set(editorId, markerStore);
    return markerStore;
  }

  @action
  startKernel(kernelDisplayName: string) {
    this.startingKernels.set(kernelDisplayName, true);
  }

  addFileDisposer(editor: atom$TextEditor, filePath: string) {
    const fileDisposer = new CompositeDisposable();

    if (isUnsavedFilePath(filePath)) {
      fileDisposer.add(
        editor.onDidSave(event => {
          fileDisposer.dispose();
          this.addFileDisposer(editor, event.path); // Add another `fileDisposer` once it's saved
        })
      );
      fileDisposer.add(
        editor.onDidDestroy(() => {
          this.kernelMapping.delete(filePath);
          fileDisposer.dispose();
        })
      );
    } else {
      const file: atom$File = new File(filePath);
      fileDisposer.add(
        file.onDidDelete(() => {
          this.kernelMapping.delete(filePath);
          fileDisposer.dispose();
        })
      );
    }

    this.subscriptions.add(fileDisposer);
  }

  @action
  newKernel(
    kernel: Kernel,
    filePath: string,
    editor: atom$TextEditor,
    grammar: atom$Grammar
  ) {
    if (isMultilanguageGrammar(editor.getGrammar())) {
      if (!this.kernelMapping.has(filePath)) {
        this.kernelMapping.set(filePath, new Map());
      }
      const multiLanguageMap = this.kernelMapping.get(filePath);
      if (multiLanguageMap) multiLanguageMap.set(grammar.name, kernel);
    } else {
      this.kernelMapping.set(filePath, kernel);
    }
    this.addFileDisposer(editor, filePath);
    const index = this.runningKernels.findIndex(k => k === kernel);
    if (index === -1) {
      this.runningKernels.push(kernel);
    }
    // delete startingKernel since store.kernel now in place to prevent duplicate kernel
    this.startingKernels.delete(kernel.kernelSpec.display_name);
  }

  @action
  deleteKernel(kernel: Kernel) {
    const grammar = kernel.grammar.name;
    const files = this.getFilesForKernel(kernel);

    files.forEach(file => {
      const kernelOrMap = this.kernelMapping.get(file);
      if (!kernelOrMap) return;
      if (kernelOrMap instanceof Kernel) {
        this.kernelMapping.delete(file);
      } else {
        kernelOrMap.delete(grammar);
      }
    });

    this.runningKernels = this.runningKernels.filter(k => k !== kernel);
  }

  getFilesForKernel(kernel: Kernel): Array<string> {
    const grammar = kernel.grammar.name;
    return this.filePaths.filter(file => {
      const kernelOrMap = this.kernelMapping.get(file);
      if (!kernelOrMap) return false;
      return kernelOrMap instanceof Kernel
        ? kernelOrMap === kernel
        : kernelOrMap.get(grammar) === kernel;
    });
  }

  @action
  dispose() {
    this.subscriptions.dispose();
    this.markersMapping.forEach(markerStore => markerStore.clear());
    this.markersMapping.clear();
    this.runningKernels.forEach(kernel => kernel.destroy());
    this.runningKernels = [];
    this.kernelMapping.clear();
  }

  @action
  updateEditor(editor: ?atom$TextEditor) {
    this.editor = editor;
    this.setGrammar(editor);

    if (this.globalMode && this.kernel && editor) {
      const fileName = editor.getPath();
      if (!fileName) return;
      this.kernelMapping.set(fileName, this.kernel);
    }
  }

  // Returns the embedded grammar for multilanguage, normal grammar otherwise
  getEmbeddedGrammar(editor: atom$TextEditor): ?atom$Grammar {
    const grammar = editor.getGrammar();
    if (!isMultilanguageGrammar(grammar)) {
      return grammar;
    }

    const embeddedScope = getEmbeddedScope(
      editor,
      editor.getCursorBufferPosition()
    );

    if (!embeddedScope) return grammar;
    const scope = embeddedScope.replace(".embedded", "");
    return atom.grammars.grammarForScopeName(scope);
  }

  @action
  setGrammar(editor: ?atom$TextEditor) {
    if (!editor) {
      this.grammar = null;
      return;
    }

    this.grammar = this.getEmbeddedGrammar(editor);
  }

  @action
  setConfigValue(keyPath: string, newValue: ?mixed) {
    if (!newValue) {
      newValue = atom.config.get(keyPath);
    }
    this.configMapping.set(keyPath, newValue);
  }

  /**
   * Force mobx to recalculate filePath (which depends on editor observable)
   */
  forceEditorUpdate() {
    const currentEditor = this.editor;
    if (!currentEditor) return;

    const oldKey = this.filePath;
    if (!oldKey) return;
    // Return back if the kernel for this editor is already disposed.
    if (!this.kernelMapping.has(oldKey)) return;

    this.updateEditor(null);
    this.updateEditor(currentEditor);
    const newKey = this.filePath;
    if (!newKey) return;

    // Change key of kernelMapping from editor ID to file path
    this.kernelMapping.set(newKey, this.kernelMapping.get(oldKey));
    this.kernelMapping.delete(oldKey);
  }
}

const store = new Store();
export default store;

// For debugging
window.hydrogen_store = store;
<|endoftext|>


<commit_before>(function (module){

  var adminFlag = false;

  var postView = {
    renderPostTemplate (post) {
      var template = Handlebars.compile($('#post-template').text());
      var htmlObject = template(post);
      return htmlObject;
    },
    populateEventSelector (events) {
      var optionTag = '';
      postView.dom.$pse.empty();
      var template = Handlebars.compile($('#post-selector-template').text());
      postView.dom.$pse.append(template({title: ''}));
      events.forEach(function (e) {
        optionTag = template(e);
        postView.dom.$pse.append(optionTag);
      });
    },

    // takes three parameters, posts per page, page number and isAdmin
    renderPage(perPage, page, isAdmin){
      adminFlag = isAdmin;

      // $('#new-post').hide();
      // $('#events').hide();
      // $('#my-profile').hide();

      API.getAll('api/post/list/'+perPage+'/'+page, Post, function(arrayOfPosts){
        $('#all-posts').empty();
        arrayOfPosts.reverse();
        arrayOfPosts.forEach(function(post){
          post.createdAt = moment(post.createdAt).format('HH:mm on MM-DD-YY');
          $('#currentPage').text(postView.currentPage+1);
          $('#all-posts').append(postView.renderPostTemplate(post));
          $(`#${post._id}`).on('click', function(e){
            e.preventDefault();
            function callback() {postView.renderPage(postView.perPage, postView.currentPage, isAdmin); }
            API.delete ('/api/post/' + e.target.id, Post, callback);
          });
        });
        window.userView.renderUser();
      });
    },
    dom: {
      form: document.getElementById('new-post-form').elements,
      $pse: $('#postEventSelector')
    },
    getPostCount() {
      $.ajax({
        url: '/api/post/postcount',
        type: 'GET',
        headers: {token: localStorage.token}})
      .done(function(data){
        postView.postCount = data;
        postView.numPages = Math.ceil(postView.postCount/postView.perPage);
        $('#numPages').text(postView.numPages);
      });

    },
    nextPage(e) {
      e.preventDefault();
      if (postView.currentPage < postView.numPages-1) {
        postView.currentPage++;
        $('#currentPage').text(postView.currentPage+1);
        postView.renderPage(postView.perPage, postView.currentPage, adminFlag);
        // Reset the topic filter drop down
        $('#filter-topic-dropdown :nth-child(1)').prop('selected', true);
      }
    },
    prevPage(e) {
      e.preventDefault();
      if (postView.currentPage > 0) {
        postView.currentPage--;
        $('#currentPage').text(postView.currentPage+1);
        postView.renderPage(postView.perPage, postView.currentPage, adminFlag);
        // Reset the topic filter drop down
        $('#filter-topic-dropdown :nth-child(1)').prop('selected', true);
      }
    },
    currentPage: 0,
    perPage: 8

  };

  $('#next-page').click(postView.nextPage);
  $('#prev-page').click(postView.prevPage);

  $('#new-post-submit').click(function () {
    var user = JSON.parse(localStorage.user);

    const arrayOfTopics = getSelectValues(postView.dom.form.newposttopics) || [];

    var eventValue = postView.dom.form.postEventSelector.value;
    if (eventValue === '') eventValue = null;

    var data = {
      body: postView.dom.form.postmsg.value,
      author: user.id,
      topics: arrayOfTopics,
      event: eventValue
    };
    $('#new-post-form').find('textarea').val('');

    postView.postCount++;
    $('#topics-drop-down').children().prop('selected', false);
    function callback() {
      postView.renderPage(postView.perPage, postView.currentPage, adminFlag);
      $('.main-nav').hide();
      $('#posts-wrapper').show();
    }

    API.post('api/post/', data, Post, callback);
  });

  //TODO add user contact info

  function getSelectValues(select) {
    var result = [];
    var options = select && select.options;
    var opt;

    for (var i=0, iLen=options.length; i<iLen; i++) {
      opt = options[i];

      if (opt.selected) {
        result.push(opt.value || opt.text);
      }
    }
    return result;
  }

  module.postView = postView;
})(window);
<commit_msg>Bug fix for broken posts AJAX call<commit_after>(function (module){

  var adminFlag = false;

  var postView = {
    renderPostTemplate (post) {
      var template = Handlebars.compile($('#post-template').text());
      var htmlObject = template(post);
      return htmlObject;
    },
    populateEventSelector (events) {
      var optionTag = '';
      postView.dom.$pse.empty();
      var template = Handlebars.compile($('#post-selector-template').text());
      postView.dom.$pse.append(template({title: ''}));
      events.forEach(function (e) {
        optionTag = template(e);
        postView.dom.$pse.append(optionTag);
      });
    },

    // takes three parameters, posts per page, page number and isAdmin
    renderPage(perPage, page, isAdmin){
      adminFlag = isAdmin;

      // $('#new-post').hide();
      // $('#events').hide();
      // $('#my-profile').hide();

      // TODO: The perPage endpoint is not returning anything.
      // Defaulting to the /list endpoint is a temoporary fix
      // API.getAll('api/post/list/'+perPage+'/'+page, Post, function(arrayOfPosts){
      API.getAll('api/post/list/', Post, function(arrayOfPosts){
        $('#all-posts').empty();
        arrayOfPosts.reverse();
        arrayOfPosts.forEach(function(post){
          post.createdAt = moment(post.createdAt).format('HH:mm on MM-DD-YY');
          $('#currentPage').text(postView.currentPage+1);
          $('#all-posts').append(postView.renderPostTemplate(post));
          $(`#${post._id}`).on('click', function(e){
            e.preventDefault();
            function callback() {postView.renderPage(postView.perPage, postView.currentPage, isAdmin); }
            API.delete ('/api/post/' + e.target.id, Post, callback);
          });
        });
        window.userView.renderUser();
      });
    },
    dom: {
      form: document.getElementById('new-post-form').elements,
      $pse: $('#postEventSelector')
    },
    getPostCount() {
      $.ajax({
        url: '/api/post/postcount',
        type: 'GET',
        headers: {token: localStorage.token}})
      .done(function(data){
        postView.postCount = data;
        postView.numPages = Math.ceil(postView.postCount/postView.perPage);
        $('#numPages').text(postView.numPages);
      });

    },
    nextPage(e) {
      e.preventDefault();
      if (postView.currentPage < postView.numPages-1) {
        postView.currentPage++;
        $('#currentPage').text(postView.currentPage+1);
        postView.renderPage(postView.perPage, postView.currentPage, adminFlag);
        // Reset the topic filter drop down
        $('#filter-topic-dropdown :nth-child(1)').prop('selected', true);
      }
    },
    prevPage(e) {
      e.preventDefault();
      if (postView.currentPage > 0) {
        postView.currentPage--;
        $('#currentPage').text(postView.currentPage+1);
        postView.renderPage(postView.perPage, postView.currentPage, adminFlag);
        // Reset the topic filter drop down
        $('#filter-topic-dropdown :nth-child(1)').prop('selected', true);
      }
    },
    currentPage: 0,
    perPage: 8

  };

  $('#next-page').click(postView.nextPage);
  $('#prev-page').click(postView.prevPage);

  $('#new-post-submit').click(function () {
    var user = JSON.parse(localStorage.user);

    const arrayOfTopics = getSelectValues(postView.dom.form.newposttopics) || [];

    var eventValue = postView.dom.form.postEventSelector.value;
    if (eventValue === '') eventValue = null;

    var data = {
      body: postView.dom.form.postmsg.value,
      author: user.id,
      topics: arrayOfTopics,
      event: eventValue
    };
    $('#new-post-form').find('textarea').val('');

    postView.postCount++;
    $('#topics-drop-down').children().prop('selected', false);
    function callback() {
      postView.renderPage(postView.perPage, postView.currentPage, adminFlag);
      $('.main-nav').hide();
      $('#posts-wrapper').show();
    }

    API.post('api/post/', data, Post, callback);
  });

  //TODO add user contact info

  function getSelectValues(select) {
    var result = [];
    var options = select && select.options;
    var opt;

    for (var i=0, iLen=options.length; i<iLen; i++) {
      opt = options[i];

      if (opt.selected) {
        result.push(opt.value || opt.text);
      }
    }
    return result;
  }

  module.postView = postView;
})(window);
<|endoftext|>


<commit_before>var FastRender = null;
if(Package['meteorhacks:fast-render']) {
  FastRender = Package['meteorhacks:fast-render'].FastRender;
}

SubsManager = function (options) {
  var self = this;
  self.options = options || {};
  // maxiumum number of subscriptions are cached
  self.options.cacheLimit = self.options.cacheLimit || 10;
  // maximum time, subscription stay in the cache
  self.options.expireIn = self.options.expireIn || 5;

  self._cacheMap = {};
  self._cacheList = [];
  self._ready = false;
  self.dep = new Deps.Dependency();

  self.computation = self._registerComputation();
};

SubsManager.prototype.subscribe = function() {
  var self = this;
  if(Meteor.isClient) {
    var args = _.toArray(arguments);
    this._addSub(args);

    return {
      ready: function() {
        self.dep.depend();
        return self._ready;
      }
    };
  } else {
    // to support fast-render
    if(Meteor.subscribe) {
      return Meteor.subscribe.apply(Meteor, arguments);
    }
  }
};

SubsManager.prototype._addSub = function(args) {
  var self = this;
  var hash = EJSON.stringify(args);
  var subName = args[0];
  var paramsKey = EJSON.stringify(args.slice(1));

  if(!self._cacheMap[hash]) {
    var sub = {
      args: args,
      hash: hash
    };

    this._handleError(sub);

    self._cacheMap[hash] = sub;
    self._cacheList.push(sub);

    // if fast-render comes with this subscription
    // we need to fake the ready message at first
    // This is because we are delaying the actual subscription evaluation
    // May be FastRender needs to send full list of subscription args to the client
    // But, for now this is something working
    if(FastRender && FastRender._subscriptions && FastRender._subscriptions[subName]) {
      self._ready = self._ready && FastRender._subscriptions[subName][paramsKey];
    } else {
      self._ready = false;
    }

    // to notify the global ready()
    self._notifyChanged();

    // no need to interfere with the current computation
    self._reRunSubs();
  }

  // add the current sub to the top of the list
  var sub = self._cacheMap[hash];
  sub.updated = (new Date).getTime();

  var index = _.indexOf(self._cacheList, sub);
  self._cacheList.splice(index, 1);
  self._cacheList.push(sub);
};

SubsManager.prototype._reRunSubs = function() {
  var self = this;

  if(Deps.currentComputation) {
    Deps.afterFlush(function() {
      self.computation.invalidate();
    });
  } else {
    self.computation.invalidate();
  }
};

SubsManager.prototype._notifyChanged = function() {
  var self = this;
  if(Deps.currentComputation) {
    setTimeout(function() {
      self.dep.changed();
    }, 0);
  } else {
    self.dep.changed();
  }
};

SubsManager.prototype._applyCacheLimit = function () {
  var self = this;
  var overflow = self._cacheList.length - self.options.cacheLimit;
  if(overflow > 0) {
    var removedSubs = self._cacheList.splice(0, overflow);
    _.each(removedSubs, function(sub) {
      delete self._cacheMap[sub.hash];
    });
  }
};

SubsManager.prototype._applyExpirations = function() {
  var self = this;
  var newCacheList = [];

  var expirationTime = (new Date).getTime() - self.options.expireIn * 60 * 1000;
  _.each(self._cacheList, function(sub) {
    if(sub.updated >= expirationTime) {
      newCacheList.push(sub);
    } else {
      delete self._cacheMap[sub.hash];
    }
  });

  self._cacheList = newCacheList;
};

SubsManager.prototype._registerComputation = function() {
  var self = this;
  var computation = Deps.autorun(function() {
    self._applyExpirations();
    self._applyCacheLimit();

    // if their are no subs, we need to set the ready state as false
    if(self._cacheList.length === 0) {
      self._ready = false;
      return;
    }

    var ready = true;
    _.each(self._cacheList, function(sub) {
      sub.ready = Meteor.subscribe.apply(Meteor, sub.args).ready();
      ready = ready && sub.ready;
    });

    if(ready) {
      self._ready = true;
      self._notifyChanged();
    }
  });

  return computation;
};

SubsManager.prototype._createIdentifier = function(args) {
  var tmpArgs = _.map(args, function(value) {
    if(typeof value == "string") {
      return '"' + value + '"';
    } else {
      return value;
    }
  });

  return tmpArgs.join(', ');
};

SubsManager.prototype._handleError = function(sub) {
  var args = sub.args;
  var lastElement = _.last(args);
  sub.identifier = this._createIdentifier(args);

  if(!lastElement) {
    args.push({onError: errorHandlingLogic});
  } else if(typeof lastElement == "function") {
    args.pop();
    args.push({onReady: lastElement, onError: errorHandlingLogic});
  } else if(typeof lastElement.onError == "function") {
    var originalOnError = lastElement.onError;
    lastElement.onError = function(err) {
      errorHandlingLogic(err);
      originalOnError(err);
    };
  } else if(typeof lastElement.onReady == "function") {
    lastElement.onError = errorHandlingLogic;
  } else {
    args.push({onError: errorHandlingLogic});
  }

  function errorHandlingLogic (err) {
    console.log("Error invoking SubsManager.subscribe(%s): ", sub.identifier , err.reason);
    // expire this sub right away.
    // Then expiration machanism will take care of the sub removal
    sub.updated = new Date(1);
  }
};

SubsManager.prototype.reset = function() {
  var self = this;
  var oldComputation = self.computation;
  self.computation = self._registerComputation();

  // invalidate the new compuation and it will fire new subscriptions
  self.computation.invalidate();

  // after above invalidation completed, fire stop the old computation
  // which then send unsub messages
  // mergeBox will correct send changed data and there'll be no flicker
  Deps.afterFlush(function() {
    oldComputation.stop();
  });
};

SubsManager.prototype.clear = function() {
  this._cacheList = [];
  this._cacheMap = [];
  this._reRunSubs();
};

SubsManager.prototype.ready = function() {
  this.dep.depend();
  return this._ready;
};<commit_msg>Make subs.ready() === false at initially still supporting SSR<commit_after>var FastRender = null;
if(Package['meteorhacks:fast-render']) {
  FastRender = Package['meteorhacks:fast-render'].FastRender;
}

SubsManager = function (options) {
  var self = this;
  self.options = options || {};
  // maxiumum number of subscriptions are cached
  self.options.cacheLimit = self.options.cacheLimit || 10;
  // maximum time, subscription stay in the cache
  self.options.expireIn = self.options.expireIn || 5;

  self._cacheMap = {};
  self._cacheList = [];
  self._ready = false;
  self.dep = new Deps.Dependency();

  self.computation = self._registerComputation();
};

SubsManager.prototype.subscribe = function() {
  var self = this;
  if(Meteor.isClient) {
    var args = _.toArray(arguments);
    this._addSub(args);

    return {
      ready: function() {
        self.dep.depend();
        return self._ready;
      }
    };
  } else {
    // to support fast-render
    if(Meteor.subscribe) {
      return Meteor.subscribe.apply(Meteor, arguments);
    }
  }
};

SubsManager.prototype._addSub = function(args) {
  var self = this;
  var hash = EJSON.stringify(args);
  var subName = args[0];
  var paramsKey = EJSON.stringify(args.slice(1));

  if(!self._cacheMap[hash]) {
    var sub = {
      args: args,
      hash: hash
    };

    this._handleError(sub);

    self._cacheMap[hash] = sub;
    self._cacheList.push(sub);

    // if fast-render comes with this subscription
    // we need to fake the ready message at first
    // This is because we are delaying the actual subscription evaluation
    // May be FastRender needs to send full list of subscription args to the client
    // But, for now this is something working
    if(FastRender && FastRender._subscriptions && FastRender._subscriptions[subName]) {
      self._ready = self._ready && FastRender._subscriptions[subName][paramsKey];
    } else {
      self._ready = false;
    }

    // to notify the global ready()
    self._notifyChanged();

    // no need to interfere with the current computation
    self._reRunSubs();
  }

  // add the current sub to the top of the list
  var sub = self._cacheMap[hash];
  sub.updated = (new Date).getTime();

  var index = _.indexOf(self._cacheList, sub);
  self._cacheList.splice(index, 1);
  self._cacheList.push(sub);
};

SubsManager.prototype._reRunSubs = function() {
  var self = this;

  if(Deps.currentComputation) {
    Deps.afterFlush(function() {
      self.computation.invalidate();
    });
  } else {
    self.computation.invalidate();
  }
};

SubsManager.prototype._notifyChanged = function() {
  var self = this;
  if(Deps.currentComputation) {
    setTimeout(function() {
      self.dep.changed();
    }, 0);
  } else {
    self.dep.changed();
  }
};

SubsManager.prototype._applyCacheLimit = function () {
  var self = this;
  var overflow = self._cacheList.length - self.options.cacheLimit;
  if(overflow > 0) {
    var removedSubs = self._cacheList.splice(0, overflow);
    _.each(removedSubs, function(sub) {
      delete self._cacheMap[sub.hash];
    });
  }
};

SubsManager.prototype._applyExpirations = function() {
  var self = this;
  var newCacheList = [];

  var expirationTime = (new Date).getTime() - self.options.expireIn * 60 * 1000;
  _.each(self._cacheList, function(sub) {
    if(sub.updated >= expirationTime) {
      newCacheList.push(sub);
    } else {
      delete self._cacheMap[sub.hash];
    }
  });

  self._cacheList = newCacheList;
};

SubsManager.prototype._registerComputation = function() {
  var self = this;
  var computation = Deps.autorun(function() {
    self._applyExpirations();
    self._applyCacheLimit();

    var ready = true;
    _.each(self._cacheList, function(sub) {
      sub.ready = Meteor.subscribe.apply(Meteor, sub.args).ready();
      ready = ready && sub.ready;
    });

    if(ready) {
      self._ready = true;
      self._notifyChanged();
    }
  });

  return computation;
};

SubsManager.prototype._createIdentifier = function(args) {
  var tmpArgs = _.map(args, function(value) {
    if(typeof value == "string") {
      return '"' + value + '"';
    } else {
      return value;
    }
  });

  return tmpArgs.join(', ');
};

SubsManager.prototype._handleError = function(sub) {
  var args = sub.args;
  var lastElement = _.last(args);
  sub.identifier = this._createIdentifier(args);

  if(!lastElement) {
    args.push({onError: errorHandlingLogic});
  } else if(typeof lastElement == "function") {
    args.pop();
    args.push({onReady: lastElement, onError: errorHandlingLogic});
  } else if(typeof lastElement.onError == "function") {
    var originalOnError = lastElement.onError;
    lastElement.onError = function(err) {
      errorHandlingLogic(err);
      originalOnError(err);
    };
  } else if(typeof lastElement.onReady == "function") {
    lastElement.onError = errorHandlingLogic;
  } else {
    args.push({onError: errorHandlingLogic});
  }

  function errorHandlingLogic (err) {
    console.log("Error invoking SubsManager.subscribe(%s): ", sub.identifier , err.reason);
    // expire this sub right away.
    // Then expiration machanism will take care of the sub removal
    sub.updated = new Date(1);
  }
};

SubsManager.prototype.reset = function() {
  var self = this;
  var oldComputation = self.computation;
  self.computation = self._registerComputation();

  // invalidate the new compuation and it will fire new subscriptions
  self.computation.invalidate();

  // after above invalidation completed, fire stop the old computation
  // which then send unsub messages
  // mergeBox will correct send changed data and there'll be no flicker
  Deps.afterFlush(function() {
    oldComputation.stop();
  });
};

SubsManager.prototype.clear = function() {
  this._cacheList = [];
  this._cacheMap = [];
  this._reRunSubs();
};

SubsManager.prototype.ready = function() {
  this.dep.depend();

  // if there are no items in the cacheList we are not ready yet.
  if(this._cacheList.length === 0) {
    return false;
  }
  return this._ready;
};<|endoftext|>


<commit_before>wn.provide("wn.messages")

wn.messages.waiting = function(parent, msg, bar_percent) {
	if(!bar_percent) bar_percent = '100';
	return $(repl('
\

%(msg)s
\

\

', {
				bar_percent: bar_percent,
				msg: msg
			}))
		.appendTo(parent);
}

wn.confirm = function(message, ifyes, ifno) {
	var d = msgprint("
" + message + "
\

\
			<button class='btn btn-small btn-info btn-yes'>Yes</button>\
			<button class='btn btn-small btn-no'>No</button>\

");
	$(d.wrapper).find(".btn-yes").click(function() {
		ifyes && ifyes();
		d.hide();
	});
	$(d.wrapper).find(".btn-no").click(function() {
		ifno && ifno();
		d.hide();
	});
}

var msg_dialog=null;
function msgprint(msg, title) {
	if(!msg) return;

	if(msg instanceof Array) {
		$.each(msg, function(i,v) {
			if(v) {
				msgprint(v);
			}
		})
		return;
	}

	if(typeof(msg)!='string')
		msg = JSON.stringify(msg);

	// small message
	if(msg.substr(0,8)=='__small:') {
		show_alert(msg.substr(8)); return;
	}

	if(!msg_dialog) {
		msg_dialog = new wn.ui.Dialog({
			title:"Message",
			onhide: function() {
				msg_dialog.msg_area.empty();
			}
		});
		msg_dialog.msg_area = $('
')
			.appendTo(msg_dialog.body);
	}

	if(msg.search(/
|
|
/)==-1)
		msg = replace_newlines(msg);

	msg_dialog.set_title(title || 'Message')

	// append a
 if another msg already exists
	if(msg_dialog.msg_area.html()) msg_dialog.msg_area.append("
");

	msg_dialog.msg_area.append(msg);
	msg_dialog.show();

	return msg_dialog;
}

// Floating Message
function show_alert(txt, add_class) {
	if(!$('#dialog-container').length) {
		$('
').appendTo('body');
	}
	if(!$('#alert-container').length) {
		$('

').appendTo('#dialog-container');
	}

	var div = $('
\
		×'+ txt +'
')
			.appendTo('#alert-container')
			.addClass(add_class);
	div.find('.close').click(function() {
		$(this).parent().remove();
		return false;
	});
	return div;
}<commit_msg>hide confirm dialog before excuting relevant function<commit_after>wn.provide("wn.messages")

wn.messages.waiting = function(parent, msg, bar_percent) {
	if(!bar_percent) bar_percent = '100';
	return $(repl('
\

%(msg)s
\

\

', {
				bar_percent: bar_percent,
				msg: msg
			}))
		.appendTo(parent);
}

wn.confirm = function(message, ifyes, ifno) {
	var d = msgprint("
" + message + "
\

\
			<button class='btn btn-small btn-info btn-yes'>Yes</button>\
			<button class='btn btn-small btn-no'>No</button>\

");
	$(d.wrapper).find(".btn-yes").click(function() {
		d.hide();
		ifyes && ifyes();
	});
	$(d.wrapper).find(".btn-no").click(function() {
		d.hide();
		ifno && ifno();
	});
}

var msg_dialog=null;
function msgprint(msg, title) {
	if(!msg) return;

	if(msg instanceof Array) {
		$.each(msg, function(i,v) {
			if(v) {
				msgprint(v);
			}
		})
		return;
	}

	if(typeof(msg)!='string')
		msg = JSON.stringify(msg);

	// small message
	if(msg.substr(0,8)=='__small:') {
		show_alert(msg.substr(8)); return;
	}

	if(!msg_dialog) {
		msg_dialog = new wn.ui.Dialog({
			title:"Message",
			onhide: function() {
				msg_dialog.msg_area.empty();
			}
		});
		msg_dialog.msg_area = $('
')
			.appendTo(msg_dialog.body);
	}

	if(msg.search(/
|
|
/)==-1)
		msg = replace_newlines(msg);

	msg_dialog.set_title(title || 'Message')

	// append a
 if another msg already exists
	if(msg_dialog.msg_area.html()) msg_dialog.msg_area.append("
");

	msg_dialog.msg_area.append(msg);
	msg_dialog.show();

	return msg_dialog;
}

// Floating Message
function show_alert(txt, add_class) {
	if(!$('#dialog-container').length) {
		$('
').appendTo('body');
	}
	if(!$('#alert-container').length) {
		$('

').appendTo('#dialog-container');
	}

	var div = $('
\
		×'+ txt +'
')
			.appendTo('#alert-container')
			.addClass(add_class);
	div.find('.close').click(function() {
		$(this).parent().remove();
		return false;
	});
	return div;
}<|endoftext|>