

function Favorites() {}

Favorites.isInit = false;

Favorites.type_combo = null;
Favorites.group_list = null;
Favorites.combo_class = null;

Favorites.marker_data = null;
Favorites.marker_list = null;

Favorites.group_dialog = null;

Favorites.group_action = 0;

Favorites.GLOBAL_FAV  = "global";
Favorites.USER_FAV    = "user";
Favorites.current_fav = Favorites.GLOBAL_FAV;

Favorites.current_class = "255"; // All.

var tmp = null;

Favorites.init = function(parent) {

    if(this.isInit == true) return;


    // Class combo.
    this.combo_class = new qx.ui.form.ComboBox();
    with(this.combo_class)
    {
             setTop(8);
	     setLeft(2);
             setWidth(200);
	     setBorder(qx.renderer.border.BorderPresets.getInstance().shadow);
    }

    var item = new qx.ui.form.ListItem(Combo_Group_ItemAll);
    item.setValue("255");
    this.combo_class.add(item);

    var item = new qx.ui.form.ListItem(Combo_Group_ItemSeparator);
    item.setValue("separator");
    item.setEnabled(false);
    this.combo_class.add(item);

    for(var i=0; i<MapData.classes.length; i++) {
             if(MapData.classes[i].elmtName.text == "") continue;
             var item = new qx.ui.form.ListItem(MapData.classes[i].elmtName.text);
             item.setValue(MapData.classes[i].elmtCuid);
             this.combo_class.add(item);
    }

    this.combo_class.setSelected(this.combo_class.getList().getFirstChild());

    this.combo_class.getList().addEventListener("appear", function() {
             //Favorites.group_list.setEnabled(false);
    });
    
    this.combo_class.getList().addEventListener("disappear", function() {
             var value = Favorites.combo_class.getSelected().getValue() + "";

             if(value == Favorites.current_class) return;

             Favorites.current_class = value;

             if(Favorites.current_fav == "global") {
                   ResetWidgets(RESET_GROUP);
                   for(var i=0; i<MapData.groups.__indices.length; i++) {
                         var group = MapData.groups[MapData.groups.__indices[i] + ""];
                         
                         if(MapData.checkGroupOnGlobal(group) == false) continue;

                         if(group.elmtName + "" != "" && (group.elmtClass == value || value == "255")) {
                                   Favorites.addGroup2List(group);
                         }
                   }
                   Favorites.setCheckColor();
             }
             
             //Favorites.group_list.setEnabled(true);
    });

    parent.add(this.combo_class);

    Switcher.addWidget2Sector(Switcher.USER_SECTOR, this.combo_class);
    Switcher.addWidget2Sector(Switcher.GUEST_SECTOR, this.combo_class);
    this.combo_class.connect();

    // Radio.
    var tbr1 = new qx.ui.toolbar.RadioButton(null, "icon/22/actions/system-run.png", true);
    tbr1.set({ top: 5, right: 2, width: 28, height: 28 });
    tbr1.setToolTip(new qx.ui.popup.ToolTip(Tooltip_Group_Global));
    tbr1.__group_type = "global";
    tbr1.setDisableUncheck(true);
    parent.add(tbr1);

    var tbr2 = new qx.ui.toolbar.RadioButton(null, "icon/22/places/favorite-folder.png");
    tbr2.set({ top: 5, right: 32, width: 28, height: 28 });
    tbr2.setToolTip(new qx.ui.popup.ToolTip(Tooltip_Group_User));
    tbr2.__group_type = "user";
    tbr2.setDisableUncheck(true);
    parent.add(tbr2);

//    Switcher.addWidget2Sector(Switcher.ADMIN_SECTOR, tbr2);
//    Switcher.addWidget2Sector(Switcher.USER_SECTOR, tbr2);

    var group_manager = new qx.manager.selection.RadioManager(null, [tbr1, tbr2]);

    group_manager.addEventListener("changeSelected", function(e) {
        Favorites.current_fav = e.getData().__group_type;
        switch(Favorites.current_fav) {
              case "global":
              SetGlobal();
              break;
              case "user":
              SetUser();
              break;
        }
    });

    function SetGlobal() {
        ResetWidgets(RESET_GROUP);

        for(var i=0; i<MapData.groups.__indices.length; i++) {
                var group = MapData.groups[MapData.groups.__indices[i]];

                if(MapData.checkGroupOnGlobal(group) == false) continue;
                
                if(group.elmtName + "" != "" && (group.elmtClass == Favorites.current_class || Favorites.current_class == "255")) {
                          Favorites.addGroup2List(group);
                }
        }
        
        Favorites.setCheckColor();

        if(Switcher.currentSector != Switcher.ADMIN_SECTOR) {
                  Favorites.combo_class.setVisibility(true);
                  removeBtn.disconnect();
        } else
                  Favorites.combo_class.setVisibility(false);
    }

    function SetUser() {
        ResetWidgets(RESET_GROUP);
        Favorites.combo_class.setVisibility(false);
        for(var i=0; i<MapData.groups.__indices.length; i++) {
              var group = MapData.groups[MapData.groups.__indices[i]];
              if(MapData.checkGroupOnGlobal(group) == true) continue;
              Favorites.addGroup2List(group);
        }

        Favorites.setCheckColor();

        removeBtn.connect();
    }

    // ADMIN MODE -->

    var setlabelBtn = new qx.ui.toolbar.Button(null, "icon/22/actions/edit-add.png"); //new qx.ui.basic.Atom(Atom_UserPanel_RemoveLabel);
    with(setlabelBtn) {
             //setLocation(2, 170);
             setRight(62);
             setTop(5);
             setPadding(4, 4);
             setWidth(28);
             setHeight(28);
             setBorder(new qx.renderer.border.Border(1, "solid", "#B0B0B0"));
             setToolTip(new qx.ui.popup.ToolTip(Tooltip_Group_New));
             addEventListener("execute", function() {
                       if(Favorites.group_dialog == null)
                                 Favorites.group_dialog = InitGroupDialog();
                                 
                       WidgetSeter(Favorites.group_dialog._data_widgets, { elmtName : "", elmtComments : "", elmtIcon: "" });

                       Favorites.group_action = 1;
                       Favorites.group_dialog.open();
             });
    }

    var editlabelBtn = new qx.ui.toolbar.Button(null, "icon/22/actions/edit.png"); //new qx.ui.basic.Atom(Atom_UserPanel_RemoveLabel);
    with(editlabelBtn) {
             //setLocation(2, 170);
             setRight(92);
             setTop(5);
             setPadding(4, 4);
             setWidth(28);
             setHeight(28);
             setBorder(new qx.renderer.border.Border(1, "solid", "#B0B0B0"));
             setToolTip(new qx.ui.popup.ToolTip(Tooltip_Group_Edit));
             addEventListener("execute", function() {
                       if(Favorites.group_dialog == null)
                                 Favorites.group_dialog = InitGroupDialog();

                       var group = Favorites.group_list.getSelectedItem().__group;
                       WidgetSeter(Favorites.group_dialog._data_widgets, group);

                       Favorites.group_action = 2;
                       Favorites.group_dialog.open();
             });
    }

    var removeBtn = new qx.ui.toolbar.Button(null, "icon/22/actions/edit-delete.png"); //new qx.ui.basic.Atom(Atom_UserPanel_RemoveLabel);
    with(removeBtn) {
             setLocation(2, 5);
             setPadding(4, 4);
             setWidth(28);
             setHeight(28);
             setBorder(new qx.renderer.border.Border(1, "solid", "#B0B0B0"));
             setToolTip(new qx.ui.popup.ToolTip(Tooltip_Group_Delete));
             addEventListener("execute", function() {

                      if(Favorites.group_list.getManager().getItems().length == 0) return;

                      var item = Favorites.group_list.getSelectedItem();
                      var group = item.__group;

                      if(Switcher.currentSector != Switcher.GUEST_SECTOR) {
                            var uid = group.elmtUid;
                            var gid = group.elmtGid;
                            switch(Favorites.current_fav) {
                                 case "global":
                                 DelMarkerGroup(GAuthInfo.elmtAccuid, gid);
                                 break;
                                 case "user":
                                 Profile.delFav(MapData.map_guid, uid, gid);
                                 GUserProfile.elmtFavorite = Profile.fav_str;
                                 GDebugPort.debug(GUserProfile.elmtFavorite);
                                 GUserProfile.elmtAccuid = GAuthInfo.elmtAccuid;
                                 SetUserProfile(GUserProfile);
                                 break;
                            }
                      }

                      if((Switcher.currentSector == Switcher.ADMIN_SECTOR && Favorites.current_fav == "global") || Favorites.current_fav == "user") {
                                MapData.removeGroup(group);
                                Favorites.group_list.remove(item);
                                Favorites.marker_data.length = 0;
                                Favorites.marker_list.update();
                      }
             });
    };

    parent.add(setlabelBtn, editlabelBtn, removeBtn);

    Switcher.addWidget2Sector(Switcher.ADMIN_SECTOR, setlabelBtn);
    Switcher.addWidget2Sector(Switcher.ADMIN_SECTOR, editlabelBtn);
    //Switcher.addWidget2Sector(Switcher.ADMIN_SECTOR, removeBtn);
    
    removeBtn.disconnect();

    // <--
    
    var frame = new qx.ui.layout.VerticalBoxLayout;
    frame.setLocation(0, 35);
    frame.setBottom(10);
    frame.setRight(0);
//    frame.setBackgroundColor("#134275");
    frame.setSpacing(10);

    parent.add(frame);

/*    // the splitpane itself
    var splitpane = new qx.ui.splitpane.VerticalSplitPane("1*", "1*");
    splitpane.setEdge(0);
    splitpane.setLiveResize(false);
    splitpane.setEnabled(false);
    frame.add(splitpane);
*/
    this.group_list = new qx.ui.form.List;

//    this.group_list.set({ top : 62, left: 2, height: 300, right: 2, overflow : "auto" });
    this.group_list.setOverflow("scrollY");
    this.group_list.setWidth("100%");
    this.group_list.setHeight("50%");
    this.group_list.setBorder(new qx.renderer.border.Border(1, "solid", "#B0B0B0"));
    this.group_list.setSpacing(1);
    //parent.add(this.group_list);
    //splitpane.addTop(this.group_list);
    frame.add(this.group_list);

    this.group_list.addEventListener("keyup", function() {
              if(tmp != null) {
                     if(tmp.__group.__isCheck == true) {
                             tmp.setBackgroundColor(new qx.renderer.color.Color("#B0B0E0"));
                     } else {
                             //tmp.setBackgroundColor(new qx.renderer.color.Color("#FFFFFF"));
                     }
              }
              tmp = this.getSelectedItem();
      });

      this.group_list.addEventListener("click", function() {
              if(tmp != null) {
                     if(tmp.__group.__isCheck == true) {
                             tmp.setBackgroundColor(new qx.renderer.color.Color("#B0B0FF"));
                     } else {
                             //tmp.setBackgroundColor(new qx.renderer.color.Color("#FFFFFF"));
                     }
              }
              tmp = this.getSelectedItem();
      });

      this.group_list.getManager().addEventListener("changeSelection", function(e) {
           var item = e.getData()[0];
           var group = item.__group;

           if(group.__isFill == false) {

              Favorites.marker_data.length = 0;
              Favorites.marker_list.update();

              var old_gid = group.elmtGid;

              if(MapData.checkGroupOnGlobal(group) == true) {
                     // Get markers for global group.
                     var soap_data = [];
                     soap_data["elmtUid"] = "*";
                     soap_data["elmtLogicFlag"] = "strong";
                     soap_data["elmtName"] = "*";
                     soap_data["elmtGroup"] = group.elmtGid;
                     soap_data["elmtComments"] = "*";
                     soap_data["elmtPicsComments"] = "*";

                     GetMarker(soap_data, true, function(arr) {
                       for(var i=0; i<arr.length; i++) {
                            arr[i] = SetIconGroup(arr[i]);
                            arr[i] = SetTextGroup(arr[i]);
                            MapData.markers[MapData.FAVORITE_MARKERS].push(arr[i]);
                       }
                            if(old_gid == group.elmtGid) {
                                       Favorites.setFilter();
                                       MapData.markers[MapData.FAVORITE_MARKERS].gid_list = "G" + group.elmtGid + "";
                                       MapData.markers[MapData.FAVORITE_MARKERS].filter += "G" + group.elmtGid + "|";
                                       Favorites.marker_list.__change_sel = true;
                                       GDebugPort.debug("Select group: " + MapData.markers[MapData.FAVORITE_MARKERS].filter);
                                       RedrawLabels();
                            }
                     });
                     group.__isFill = true;
              } else { // User group.
                     //if(Switcher.currentSector != Switcher.GUEST_SECTOR) {
                           // Get markers for user group.
                           var soap_data = [];
                           soap_data["elmtUid"] = group.elmtUid;
                           soap_data["elmtLogicFlag"] = "strong";
                           soap_data["elmtName"] = "*";
                           soap_data["elmtGroup"] = group.elmtGid;
                           soap_data["elmtComments"] = "*";
                           soap_data["elmtPicsComments"] = "*";

                           GetMarker(soap_data, true, function(arr) {
                                   for(var i=0; i<arr.length; i++) {
                                           arr[i] = SetIconGroup(arr[i]);
                                           arr[i] = SetTextGroup(arr[i]);
                                           MapData.markers[MapData.FAVORITE_MARKERS].push(arr[i]);
                                   }
                                           if(old_gid == group.elmtGid) {
                                                  Favorites.setFilter();
                                                  MapData.markers[MapData.FAVORITE_MARKERS].gid_list = group.__ugid; //group.elmtGid + "";
                                                  MapData.markers[MapData.FAVORITE_MARKERS].filter += group.__ugid + "|"; //group.elmtGid + "|";
                                                  Favorites.marker_list.__change_sel = true;
                                                  GDebugPort.debug("Select group: " + MapData.markers[MapData.FAVORITE_MARKERS].filter);
                                                  RedrawLabels();
                                           }
                           });
                           group.__isFill = true;
                     //}
              }
           } else {

                 Favorites.setFilter();

                 if(Favorites.current_fav == "global") {
                         MapData.markers[MapData.FAVORITE_MARKERS].gid_list = "G" + group.elmtGid;
                         MapData.markers[MapData.FAVORITE_MARKERS].filter += "G" + group.elmtGid + "|";
                 } else {
                         MapData.markers[MapData.FAVORITE_MARKERS].gid_list = group.__ugid; //group.elmtGid + "";
                         MapData.markers[MapData.FAVORITE_MARKERS].filter += group.__ugid + "|";  //elmtGid + "|";
                 }

                 Favorites.marker_list.__change_sel = true;

                 RedrawLabels();
                 
                 GDebugPort.debug("Select group: " + MapData.markers[MapData.FAVORITE_MARKERS].filter);
           }

           if(Favorites.group_dialog != null)  {
                  //GDebugPort.debug("SELECTED GID = " + item.__gid);
                  WidgetSeter(Favorites.group_dialog._data_widgets, group);
                  //GDebugPort.debug(MapData.groups[item.__gid + ""].elmtClass + "   " + MapData.groups[item.__gid + ""].elmtIcon);
           }
    });

    this.marker_data = [];

    var header =
    {
        icon            : { label : "", width: 24, iconHeight: 20, type : "iconHtml" },
        elmtName        : { label : ListView_MyLabels_Name, width : 100, type : "text", sortable : true, sortProp : "text" },
        elmtComments    : { label : ListView_MyLabels_Comment, width : 200, type : "text", sortable : true, sortProp : "text" }
//        elmtType        : { label : ListView_MyLabels_Group, width : 100, type : "text", sortable : true, sortProp : "text" }
    };

    this.marker_list = new qx.ui.listview.ListView(this.marker_data, header);
    //this.marker_list.set({ top : 368, left: 2, bottom: 10, right: 2 });
    this.marker_list.setWidth("100%");
    this.marker_list.setHeight("50%");

    this.marker_list.setBorder(new qx.renderer.border.Border(1, "solid", "#B0B0B0"));
    this.marker_list.__change_sel == false;
    //parent.add(this.marker_list);
    //splitpane.addBottom(this.marker_list);
    frame.add(this.marker_list);

    this.marker_list.getPane().getManager().addEventListener("changeSelection", function(e) {

          var item = e.getData()[0];
          
          if(Gallery.fill(item) == true) {
                     Gallery.tab.connect();
                } else {
                     Gallery.tab.disconnect();
          }

          var id = MapData.markers[MapData.FAVORITE_MARKERS].indexOf(item);

/*	  for(var i=0; i<GMapCells.length; i++) {
                 for(j=0; j<GMapCells[i]._freeLabels.length; j++) {
                          var label = GMapCells[i]._freeLabels[j];
                          label.setBorder(qx.renderer.border.BorderPresets.getInstance().none);
                          if(label.getVisibility() == true && label._id == id) {
                                label.setBorder(qx.renderer.border.BorderPresets.getInstance().black);
                          }
                 }
          }*/
    });

    this.marker_list.getPane().getManager().handleDblClick = function(item, e) {
               var mX = MapData.markers[MapData.FAVORITE_MARKERS][MapData.markers[MapData.FAVORITE_MARKERS].indexOf(item)].mX;
               var mY = MapData.markers[MapData.FAVORITE_MARKERS][MapData.markers[MapData.FAVORITE_MARKERS].indexOf(item)].mY;
               GAbsX = -mX+GPortWidth/2; GAbsY = -mY+GPortHeight/2;
               SetMapPosition(-GAbsX, -GAbsY, 1);
               ShowInformator(item);
    }

    return { "type_combo" : this.type_combo, "group_list" : this.group_list, "marker_list" : this.marker_list };
};

Favorites.addGroup2List = function(group) {

      var name          = group.elmtName;
      var comments      = group.elmtComments;

      var icon = "";
      if(group.elmtUid + "" == "0") icon = IconGroupPath(group.elmtIcon, 32, 0);
      else icon = group.elmtIcon;

      var item = new qx.ui.form.ListItem("<b>" + name + "</b><br>" + comments, icon);

      item.__group = group;
      
      item.addEventListener("dblclick", function() {
              this.__group.__isCheck = !this.__group.__isCheck;
      });
      this.group_list.add(item);

};

Favorites.setCheckColor = function() {
      var items = this.group_list.getManager().getItems();
      for(var i=0; i<items.length; i++) {
              if(items[i].__group.__isCheck == true)
                      items[i].setBackgroundColor(new qx.renderer.color.Color("#B0B0E0"));
      }
};

Favorites.setFilter = function() {
      MapData.markers[MapData.FAVORITE_MARKERS].filter = "|";
      var items = this.group_list.getManager().getItems();
      for(var i=0; i<items.length; i++) {
              if(items[i].__group.__isCheck == true) {
                    if(Favorites.current_fav == "global")
                           MapData.markers[MapData.FAVORITE_MARKERS].filter += "G" + items[i].__group.elmtGid + "|";
                    else
                           MapData.markers[MapData.FAVORITE_MARKERS].filter += items[i].__group.__ugid + "|";  //elmtGid + "|";
              }
      }
      GDebugPort.debug("Filter: " + MapData.markers[MapData.FAVORITE_MARKERS].filter);
};

Favorites.reset = function() {

      Favorites.combo_class.setSelected(Favorites.combo_class.getList().getFirstChild());
      
      ResetWidgets(RESET_GROUP);
      for(var i=0; i<MapData.groups.__indices.length; i++) {
              var group = MapData.groups[MapData.groups.__indices[i] + ""];
              if(MapData.checkGroupOnGlobal(group) == false) continue;
              if(group.elmtName + "" != "")
                     Favorites.addGroup2List(group);
      }

      Favorites.removeAllUserGroups(); // Clear widgets and data.

      if(Switcher.currentSector != Switcher.GUEST_SECTOR) {
              if(MapData.map_guid != null) {
                      var user_groups = Profile.getFav(MapData.map_guid);
                      for(var i=0; i<user_groups.length; i++) {
                              var name = "unknown";
                              var uidgid = (user_groups[i] + "").split(':');
                              var uid = uidgid[0];
                              var gid = uidgid[1];
                              GDebugPort.debug("Favorites add: " + uid + " : " + gid);

                              var user_info = GetUserInfo(uid);
                              if(user_info.elmtResult == 0) {
                                         name = user_info.elmtAname;
                                         GDebugPort.debug("User name: " + user_info.elmtAname);
                              }

                              Favorites.addUserGroup(name, uid, gid);
                      }
              }
      }
};

Favorites.clearGroup = function() {
      this.group_list.removeAll();
};

Favorites.addUserGroup = function(name, uid, gid) {
      var group = (gid + "" == "-1") ? Label_Group_Replacer["all"] : (gid + "");

      var data = { elmtAccuid : "",
             elmtMapUid : MapData.map_guid,
             elmtModerator : 0,
             elmtUid : uid,
             elmtGid : gid,
             elmtName : name + " | " + group,
             elmtComments : Label_Group_DefaultComment,
             elmtClass : "",
             elmtIcon : "icon/32/places/favorite-folder.png",
             elmtFlags : ""
      };

      MapData.addGroup(data);
      if(this.current_fav == "user")
             this.addGroup2List(data);
};

Favorites.removeAllUserGroups = function() {
      MapData.removeAllUserGroups();
      if(this.current_fav == "user")
             this.clearGroup();
};
