// Copyright 2008 Google Inc.
// All Rights Reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/** 
 * Javascript to manage the My Favorites page.
 */

function Favorites(win, doc, isAuthenticated) {

  this.doc_ = doc;
  this.win_ = win;
  this.isAuthenticated_ = isAuthenticated;
  
  this.favList_ = $("favorite_list");
  this.userSelect_ = $("user_select");
  this.userShareMsg_ = $("user_share_msg");
  this.sharedUsers_ = $("shared_users");
  this.shareMsg_ = $("user_share_msg");
  
  this.initFavorites();
}

Favorites.REMOVE_IMG = "/media/img/icons/group2/cross14.png";

Favorites.prototype.initFavorites = function () {
  if (this.favList_) {
    Sortable.create(this.favList_, {scroll: this.win_, scrollSpeed: 25,
        onUpdate: bind(this.updateFavorites, this)});
  }
};

Favorites.prototype.adjustFavorites_ = function () {
  var poststring = Sortable.serialize(this.favList_);
  var items = parseQueryString(poststring, true);
  var favs = items["favorite_list[]"];
  if (favs) {
    for (var i = 0; i < favs.length; i++) {
    	var item = $("position_" + favs[i]);
    	item.innerHTML = i + 1;
    	Effect.Grow(item);
    }
  }
  
  return poststring;
};

Favorites.prototype.updateFavorites = function (e) {
	var poststring = this.adjustFavorites_();
  var uri = "/moviequotes/update_favorites/";
  var res = doXHR(uri, {method: "POST", sendContent: poststring,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
};

Favorites.prototype.removeFavorite = function (favId, lineId) {
	var uri = "/moviequotes/set_favorite/";
	var d = doSimpleXMLHttpRequest(uri, {'line_id': lineId, 'is_fav': 1});
	removeElement("fav_" + favId);
	this.initFavorites();
	this.adjustFavorites_();
};
