// Generated by CoffeeScript 1.4.0
(function() {
  var Room, Rooms, Server, login,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  Server = (function(_super) {

    __extends(Server, _super);

    function Server() {
      return Server.__super__.constructor.apply(this, arguments);
    }

    Server.configure("Server", "name", "ip", "port", "index");

    Server.extend(Spine.Model.Ajax);

    Server.url = "/servers.json";

    return Server;

  })(Spine.Model);

  Room = (function(_super) {

    __extends(Room, _super);

    function Room() {
      return Room.__super__.constructor.apply(this, arguments);
    }

    Room.configure("Room", "name", "status", "private", "rule", "mode", "start_lp");

    Room.belongsTo('server', Server);

    return Room;

  })(Spine.Model);

  Rooms = (function(_super) {

    __extends(Rooms, _super);

    Rooms.prototype.events = {
      'click .room': 'clicked'
    };

    function Rooms() {
      this.render = __bind(this.render, this);
      Rooms.__super__.constructor.apply(this, arguments);
      Room.bind("refresh", this.render);
    }

    Rooms.prototype.render = function() {
      return this.html($('#room_template').tmpl(_.sortBy(Room.all(), this.sort)));
    };

    Rooms.prototype.sort = function(room) {
      return [room.status === "wait" ? 0 : 1, room["private"]];
    };

    Rooms.prototype.clicked = function(e) {
      var room;
      room = $(e.target).tmplItem().data;
      if (room["private"]) {
        $('#join_private_room')[0].reset();
        $('#join_private_room').data('room_id', room.id);
        return $('#join_private_room_dialog').dialog('open');
      } else {
        return mycard.join(room.server().ip, room.server().port, mycard.room_name(room.name, null, room.pvp, room.rule, room.mode, room.start_lp));
      }
    };

    return Rooms;

  })(Spine.Controller);

  login = function(username, password) {
    Candy.init('http://s70.hebexpo.com:5280/http-bind/', {
      core: {
        debug: false,
        autojoin: ['mycard@conference.my-card.in']
      },
      view: {
        resources: '/vendor/candy/res/',
        language: 'cn'
      }
    });
    Candy.Util.getPosTopAccordingToWindowBounds = function(elem, pos) {
      var backgroundPositionAlignment, elemHeight, marginDiff, relative, windowHeight;
      windowHeight = $(document).height();
      elemHeight = elem.outerHeight();
      marginDiff = elemHeight - elem.outerHeight(true);
      backgroundPositionAlignment = 'top';
      pos -= relative = $('#candy').offset().top;
      if (pos + elemHeight >= windowHeight - relative) {
        pos -= elemHeight - marginDiff;
        backgroundPositionAlignment = 'bottom';
      }
      return {
        px: pos,
        backgroundPositionAlignment: backgroundPositionAlignment
      };
    };
    CandyShop.InlineImages.init();
    Candy.View.Template.Login.form = $('#login_form_template').html();
    Candy.Util.setCookie('candy-nostatusmessages', '1', 365);
    Candy.Core.connect(username, password);
    window.onbeforeunload = null;
    return $('#candy').show();
  };

  $(document).ready(function() {
    var jid, new_room, rooms;
    if (jid = Candy.Util.getCookie('jid')) {
      login(jid, Candy.Util.getCookie('password'));
    }
    $('#new_room_dialog').dialog({
      autoOpen: false,
      resizable: false,
      title: "建立房间"
    });
    $('#join_private_room_dialog').dialog({
      autoOpen: false,
      resizable: false,
      title: "加入私密房间"
    });
    new_room = $('#new_room')[0];
    new_room.pvp.onchange = function() {
      if (this.checked) {
        if (new_room.mode.value === '2') {
          new_room.mode.value = 1;
        }
        new_room.rule.value = 0;
        return new_room.start_lp.value = 8000;
      }
    };
    new_room.mode.onchange = function() {
      if (this.value === '2') {
        return new_room.pvp.checked = false;
      }
    };
    new_room.rule.onchange = function() {
      if (this.value !== '0') {
        return new_room.pvp.checked = false;
      }
    };
    new_room.start_lp.onchange = function() {
      if (this.value !== '8000') {
        return new_room.pvp.checked = false;
      }
    };
    new_room.onsubmit = function(ev) {
      var server, servers;
      ev.preventDefault();
      $('#new_room_dialog').dialog('close');
      servers = Server.all();
      server = servers[Math.floor(Math.random() * servers.length)];
      return mycard.join(server.ip, server.port, mycard.room_name(this.name.value, this.password.value, this.pvp.checked, parseInt(this.rule.value), parseInt(this.mode.value), parseInt(this.start_lp.value)));
    };
    $('#join_private_room').submit(function(ev) {
      var room, room_id;
      ev.preventDefault();
      $('#join_private_room_dialog').dialog('close');
      if (this.password.value) {
        room_id = $(this).data('room_id');
        if (Room.exists(room_id)) {
          room = Room.find(room_id);
          return mycard.join(room.server().ip, room.server().port, mycard.room_name(room.name, this.password.value, room.pvp, room.rule, room.mode, room.start_lp));
        } else {
          return alert('房间已经关闭');
        }
      }
    });
    $('#new_room_button').click(function() {
      new_room.reset();
      new_room.name.value = Math.floor(Math.random() * 1000);
      return $('#new_room_dialog').dialog('open');
    });
    $('#login_dialog').dialog({
      autoOpen: false,
      resizable: false,
      title: "用户登录"
    });
    $('#login_button').click(function() {
      return login();
    });
    rooms = new Rooms({
      el: $('#rooms')
    });
    Server.one("refresh", function() {
      var websocket, wsServer;
      wsServer = 'ws://mycard-server.my-card.in:9998';
      websocket = new WebSocket(wsServer);
      websocket.onopen = function() {
        return console.log("Connected to WebSocket server.");
      };
      websocket.onclose = function() {
        return console.log("Disconnected");
      };
      websocket.onmessage = function(evt) {
        var room, _i, _len;
        console.log('Retrieved data from server: ' + evt.data);
        rooms = JSON.parse(evt.data);
        for (_i = 0, _len = rooms.length; _i < _len; _i++) {
          room = rooms[_i];
          if (room._deleted) {
            if (Room.exists(room.id)) {
              Room.find(room.id).destroy();
            }
          }
        }
        return Room.refresh((function() {
          var _j, _len1, _results;
          _results = [];
          for (_j = 0, _len1 = rooms.length; _j < _len1; _j++) {
            room = rooms[_j];
            if (!room._deleted) {
              _results.push(room);
            }
          }
          return _results;
        })());
      };
      return websocket.onerror = function(evt) {
        return console.log('Error occured: ' + evt.data);
      };
    });
    return Server.fetch();
  });

}).call(this);
