/**
* HyperCities session Objects
*
* @author    Jih-Chung Fan
* @copyright (c) 2008, by HyperCities Tech Team
* @date      2008-12-22
* @version   0.7
*
*/

HyperCities.user = function() {
	// do NOT access javascript generated DOM from here; elements don't exist yet
	
	//store object id which can be updated and deleted by everyone
	var _unlockObjList = [12249, 12248, 12250, 12251, 12252, 12335, 12337, 12338, 12339, 12340, 12341];

	// Private variable goes here
	var _id     = "[HyperCities.user] ";
	var _userId = null;
	var _nickname = null;
	var _login  = false;
	var _user   = null;
	var _group  = null;
	var _email  = null;
	var _photoUrl = null;
	var _defaultCollection = null;
	var _sync = false;
	var _neLat = 0;
	var _neLon = 0;
	var _swLat = 0;
	var _swLon = 0;

	// Private method goes here
	var _parseSync = function ($data) {
		_sync = true;

		$($data).find("User").each( function () {

			_userId = parseInt($("userId", this).text());

			//user has not login
			if (_userId === undefined || _userId === null || isNaN(_userId)) 
				_userId = null;
			else
			{
				_email = $("email", this).text();
				_nickname = $("nickname", this).text();
				_photoUrl = $("photoUrl", this).text();
				_defaultCollection = $("defaultCollection", this).text();
				_neLat = $("neLat", this).text();
				_neLon = $("neLon", this).text();
				_swLat = $("swLat", this).text();
				_swLon = $("swLon", this).text();
				//set _login to true
				_login = true;

				//show up add media control
				HyperCities.mainMap.setAddMediaControl();
				HyperCities.syncSession();
			}
		});
	};

	var _loadLoginForm = function () {

		$.ajax( {
			url: "loginForm.php",
			cache: false,
			success: function(message) {
				$("#topPanel").fadeOut("normal", function() {
					$("#topPanel").empty().append(message).fadeIn("normal", function() {
						HyperCities.user.init();
						$("#loadingMessage").fadeOut("slow");
					});
				});
			}
		});
	};

	var _showFailMessage = function () {

		var errorBox = $(document.createElement("div"));
		errorBox.attr("id", "loginErrorBox");
		errorBox.html("It appears that you've entered an incorrect email or password. <br/>" +
		'Please try again. Or <a href="./registration.php">register</a> a new account.');

		var closeBox = $(document.createElement("div"));
		closeBox.attr("id", "closeErrorBox");
		closeBox.click( function () {
			$("#loginErrorBox").remove();
		});

		var tipImage = $(document.createElement("div"));
		tipImage.attr("id", "errorBoxTip");

		errorBox.prepend(closeBox).append(tipImage);
		$("#loginForm").prepend(errorBox);

		$("#password").val("").focus();
	};

	var _parseLogin = function ($loginResult) {
		//var success = $($loginResult).find("Success").text();
		var error   = $($loginResult).find("Error > Message").text();

 		if ( error.length > 0 ) {
			_login = false;
			_showFailMessage();
		}
		else
		{
			//success
			_login = true;
			_parseSync($loginResult);
			_loadLoginForm();
		}
	};
	
	//todo: need reset server user?
	var _resetUser = function() {

		_userId = null;
		_login  = false;
		_user   = null;
		_group  = null;
		_email  = null;
		_photoUrl = null;
		_defaultCollection = null;
		_sync = false;
		_neLat = 0;
		_neLon = 0;
		_swLat = 0;
		_swLon = 0;
	};

	var _parseLogout = function () {
		
		_resetUser();
		_loadLoginForm();
		HyperCities.mainMap.removeAddMediaControl();
		HyperCities.syncSession();
	};

	var _openCollectionInfoWin = function() {
		HyperCities.debug("open collection info window");
		var div = $(document.createElement("div"));
		var subDiv = $(document.createElement("div"));
		subDiv.html("collection title:");
		div.append(subDiv);
		
		div.dialog({'zIndex': 3999});
	};

	var _createColItem = function($data)
	{
		var id            = $("id", $data).text(),
			title         = $("title", $data).text(),
			creator       = $("creator", $data).text(),
			password      = $("password", $data).text(),
			state         = parseInt($("state", $data).text()),
			ownerId       = parseInt($("ownerId", $data).text()),
			colItemId     = "colItem" + id;

		var colItem = $(document.createElement("div"));
		colItem.attr("id", colItemId);
		
		var input = $(document.createElement("input"));
		input.attr("type", "checkbox");
		input.attr("name", "collections");
		input.data("id", id);

		var text = $(document.createTextNode(title));
	
		/*
		if (ownerId === HyperCities.user.getUserId())
		{
				
		}
		else */
		if (state === HyperCities.config.HC_OBJECT_PRIVATE || state === HyperCities.config.HC_OBJECT_HIDDEN)
		{
			colItem.mousedown(function(event){
				HyperCities.debug("password="+password);
				var pwd = prompt("This is a private collection.\n Please input password:");
				if (pwd === null || HyperCities.util.MD5(pwd) !== password)
				{
					alert("Password is not correct!");
				}
				else
				{
					$(this).unbind("mousedown");
					$(this).draggable({
						revert: true,
						cursor: "move",
					});
				}
			});
		}
		else
		{
			colItem.draggable({
				revert: true,
				cursor: "move",
			});
		}

		var printState = function($state)
		{
			var stateName = null;

			switch ($state)
			{
				case 1: stateName = "Public";
					break;
				case 2: stateName = "Private visible";
					break;
				case 3: stateName = "Private hidden";
					break;
			}
			return stateName;
		}

		//colItem.click(_openCollectionInfoWin)
		var tooltipLink = $("<div class='tooltip'></div>");
		var tooltip = $("<div>title: "+title+"<br/><br/>"
					  + "Author: "+creator+"<br/><br/>"
					  + "state: "+printState(state)+"</div>");

		colItem.append(input).append(text).append(tooltipLink.append(tooltip));

		return colItem;
	};

	var _manageMyCollection = function($data) {

		//manage my collections panel
		var mainPane = $('<div><div>'
			//my collection panel
			+ '<div id="leftPane">  <div class="infoWinTitle">My Collections:</div>'
			+ '<div id="searchOwn"></div>'
			+ '<div id="ownCollection" class="collectionPanel"></div>  </div>'
			//middle panel
			+ '<div id="middlePane">'
			+ '<input type="button" id="addToMy" value="<<"><br/>'
			+ '<input type="button" id="addToOther" value=">>"> </div>'
			//right panel
			+ '<div id="rightPane">  <div class="infoWinTitle">All Collections:</div>'
			+ '<div id="searchOther"></div>'
			+ '<div id="otherCollection" class="collectionPanel"></div>  </div>'
			+ '</div>'
			//bottom bar
			+ '<div id="bottomBar"><input type="button" id="save" value="save"></div>'
			+ '</div>' );

		var ownCollection = $("#ownCollection", mainPane);
		var otherCollection = $("#otherCollection", mainPane);

		ownCollection.droppable({
			drop: function(ev, ui) {
				$(this).append($(ui.draggable));
			}
		});

		otherCollection.droppable({
			drop: function(ev, ui) {
				$(this).append($(ui.draggable));
			}
		});
		
		$("#addToMy", mainPane).click(function() {_addTo("otherCollection", "ownCollection")});
		$("#addToOther", mainPane).click(function() {_addTo("ownCollection", "otherCollection")});
	
		$($data).find("Folders > Folder").each( function () {
			if( $("name", this).text() == HyperCities.config.HC_COLLECTIONS.USER.name ){
				$("Folder", this).each( function () {

					var colItem = _createColItem(this);
					ownCollection.append(colItem);
				});
			}
			else if( $("name", this).text() == HyperCities.config.HC_COLLECTIONS.PUBLIC.name ){
				$("Folder", this).each( function () {

					var colItem = _createColItem(this);
					otherCollection.append(colItem);
				});
			}
		});
		
		$("#searchOwn", mainPane).append(HyperCities.util.createSearchBar(ownCollection));
		$("#searchOther", mainPane).append(HyperCities.util.createSearchBar(otherCollection));

		$("#save", mainPane).click(function(){
			
			HyperCities.debug(_id + "Save my collections.");
			var userId = _userId;
			var cidList = new Array();
			$("#ownCollection input[type=checkbox]").each(function() {
				cidList.push($(this).data("id"));	
			});


			HyperCities.mainMap.closeInfoWindow();

			var params = {userId: userId, collections: cidList.toString()};

			$.post("./updateMyCollections.php", params, function($response){
				var success = $($response).find("Success > Message").text();
				var error   = $($response).find("Error > Message").text();

				if ( error.length > 0 ) {
					alert(error);
				}
				else
				{
					alert(success);
				}	

			}, "xml");

		});

		//open manage my collections info window
		var map = HyperCities.mainMap.getMapInstance();
		var infoWinOpenHandle = GEvent.addListener(map, "infowindowopen", function(){
			HyperCities.mainMap.enableSync(false);
		});
		var infoWinCloseHandle = GEvent.addListener(map, "infowindowclose", function(){
			HyperCities.mainMap.restoreSync();
			GEvent.removeListener(infoWinOpenHandle);
		});
		HyperCities.mainMap.openInfoWindow("html", HyperCities.mainMap.getCenter(), mainPane.get(0), {noCloseOnClick:true});
	};

	//event handler of add to my/other collection button
	var _addTo = function($from, $to) {

		var checkedCollection = $("#"+$from+" :checked");
		$.each(checkedCollection, function(){
			$("#"+$to+"").append($(this).parent());
		});
	};

        /**
         * Callback for Manage My Snapshots link.
         *
         */
        var _manageMySnapshots = function ($data) {

            var __deleteSnapshot = function ($id) {
                if (!confirm("Are you sure you want to delete snapshot " + $id + "?")) return;
                var id = $id; //$(this).attr("id").split('_')[1];
                /**
                 * On Error:
                 * <Message>
                 *  <Code>USER_NOT_ALLOWED,
                 *  <Description>
                 *
                 * On Success:
                 * <Message>
                 *  <Code>SNAPSHOT_DELETED
                 *  <Description>{ID number}
                 *
                 */
                var ___deleteSnapshotCallback = function ($data) {
                    if ($("Code", $data).text() == "SNAPSHOT_DELETED") {
                        var id = $("Description", $data).text();
                        alert ("Snapshot " + id + " Deleted");
                        $("#snapshot_" + id, "#snapshotListTbody").hide();
                    } else {
                        switch ($("Code", $data).text()) {
                            case "USER_NOT_ALLOWED":
                                alert ("You tried to delete a snapshot that you don't have the priviledges to delete.");
                                break;
                            case "SNAPSHOT_NOT_FOUND":
                                alert ("Snapshot not found.");
                                break;
                            default:
                                alert ("System Error. Your snapshot could not be deleted.");
                        }
                    }
                };
                var params = {action: 'snapshot.delete', snapshotId: id};
                $.post("./snapshots.php", params, ___deleteSnapshotCallback, "xml");
            };

            HyperCities.debug(_id + "Manage My Snapshots callback called")
            var mainFrame = $(//'<div id="apDiv1">'
                /*+ '<div id="snapshotEditFrame">'
                + '<label>Current Snapshot: <input type="text" id="shapshotTitle" /></label><label>Id: <input type="text" disabled="disabled" id="shapshotId" width="5" /></label><label>Lat<input type="text" id="snapshotLat" width="10"></label><label>Lon<input type="text" id="snapshotLon" width="10"></label><label>Zoom<input type="text" id="snapshotZoom" width="3"></label>'
                + '<label>Start<input type="text" id="snapshotStart" width="10"></label>'
                + '<label>End<input type="text" id="snapshotEnd" width="10"></label>'
                + '<input type="button" name="Save Changes" id="snapshotSaveButton"/>'
                + '</div>'*/
                + '<div id="snapshotListTable">'
                + '<table>'
                + '<tbody id="snapshotListTbody">'
                + '<tr><th>Description</th>'
                //+ '<th>Center</th>'
                + '<th>Timespan</th><th>Created At</th><th>URL</th><th></th></tr>'
                + '</tbody></table></div>'
                //+ '</div>'
            );

            // TODO: Complete
            $("#saveSnapshotButton", mainFrame).click( function ($event) {
                if (!confirm("Are you sure you want to overwrite snapshot " + $("#snapshotId", mainFrame).text() + "?")) return;
                var params = {};
                params.title   = $("#snapshotTitle", mainFrame).text();
                params.id      = $("#snapshotId", mainFrame).text();
                params.startTime = $("#snapshotStartTime", mainFrame).text();

            });

            $($data).find("snapshot").each( function () {
                var newRow = $('<tr id="snapshot_' + $('id', this).text() + '">'
                           + '<td>' + $('description', this).text() + '</td>'
                           //+ '<td>' + $('center', this).text() + '</td>'
                           + '<td>' + $('timespan', this).text() + '</td>'
                           + '<td>' + $('created_at', this).text() + '</td>'
                           + '<td>' + HyperCities.linkController.generatePermalink('snapshots', $('id', this).text()) + '</td>'
                           + '<td> <input type="button" id="delete" name="Delete" value="Delete" /></td>' //onclick="_deleteSnapshot(' + $('id', this).text() + ');"
                           + '</tr>');
                $("#delete", newRow).attr("name", "deleteSnapshot_" + $('id', this).text());
                //$("#delete", newRow).click(function () {__deleteSnapshot();});
                $("#delete", newRow).click(function () {__deleteSnapshot($(this).attr('name').split('_')[1]);});

                newRow.dblclick(function () {
                    $(this).siblings().removeClass("highlighted");
                    $(this).addClass("highlighted");
                    _selectSnapshot($(this).text().split('_')[1]);
                }); // end newRow.dblclick(function ($event)

                $('#snapshotListTbody', mainFrame).append(newRow);
            }); // end $($data).find("snapshot").each( function ()

            var map = HyperCities.mainMap.getMapInstance();
            var infoWinOpenHandle = GEvent.addListener(map, "infowindowopen", function(){
                    HyperCities.mainMap.enableSync(false);
            });

            var infoWinCloseHandle = GEvent.addListener(map, "infowindowclose", function(){
                    HyperCities.mainMap.restoreSync();
                    GEvent.removeListener(infoWinOpenHandle);
            });

            HyperCities.debug(_id + "Opening Manage My Snapshots Window")

            HyperCities.mainMap.openInfoWindow("html", HyperCities.mainMap.getCenter(), mainFrame.get(0), {noCloseOnClick:true});

        };

        // Snapshot functions left to write:

        var _removeSnapshotListItem = function ($id) {
            $("#snapshotListTbody").removeChild("#snapshot_" + $id);
        }
        var _deleteSnapshot = function($id) {
            var __deleteCallback = function ($data) {

            }


        };

        var _selectSnapshot = function ($id) {

        };

        var _saveSnapshot = function ($elements) {

        };

	//add event listener to login page element
	var _addListener = function() {

		//add logout event handler
		if ($("#loginForm #logoutBtn"))
			$("#loginForm #logoutBtn").unbind("click").click(HyperCities.user.logout);
	
		//add login event handler
		if ($("#loginForm #loginBtn"))
		{
			$("#loginForm #loginBtn").unbind("click").click(HyperCities.user.login);
			$("#loginForm #username").focus();
		}

		//add set default collection event handler
		if ($("#loginForm #defaultCollection"))
		{
			$("#loginForm #defaultCollection").unbind("click").click(function(){
				var params = {func: "all", userId: _userId};
				$.post("./queryCollection.php", params, _setDefaultCollection, "xml");
			});
		}
		
		//add manage my collection event handler
		if ($("#loginForm #myCollection"))
		{
			$("#loginForm #myCollection").unbind("click").click(function(){
				var params = {func: "10", userId: _userId};
				$.post("./queryCollection.php", params, _manageMyCollection, "xml");
			});
		}
		
                if ($("#loginForm #mySnapshots"))
                    {
                        $("#loginForm #mySnapshots").unbind("click").click(function (){
                            var params = {action: "snapshot.list", userId: _userId ? _userId : 0};
                            $.post("./snapshots.php", params, _manageMySnapshots, "xml");
                        });
                    }

		//add zoom to default collection event handler
		if (_defaultCollection !== "No default collection")
		{
			//zoom to collection when click title
			$("#defaultCollectionTitle").click(function(){
				HyperCities.user.zoomToCollection(_neLat, _neLon, _swLat, _swLon);
			});
		}

		//add create new collection event handler
		if ($("#loginForm #addCollection"))
		{
			$("#loginForm #addCollection").unbind("click").click(function(){
				HyperCities.user.addCollection();
			});
		}
	};
	
	var _setDefaultCollection = function($data) {

		//HyperCities.debug("Set default collection");

		var tempDiv = $(document.createElement("div"));
		var temp = $(document.createElement("div"));
		temp.attr("class", "infoWinTitle");
		temp.text("Set a collection as the default collection:");
		tempDiv.append(temp);
		
		var allCollection = $(document.createElement("div"));
		allCollection.attr("id", "allCollection");
		allCollection.attr("class", "collectionPanel");

		var name = "radioCollection";

		$($data).find("Folders > Folder").each( function () {
			$("Folder", this).each( function () {

				var title = $("title", this).text();
				var collectionId = $("id", this).text();

				var input = $(document.createElement("input"));
				input.attr("type", "radio");
				input.attr("name", name);
				input.data("collectionId", collectionId);

				var text = $(document.createTextNode(title));

				allCollection.append($(document.createElement("div")).append(input).append(text));
				//allCollection.append(text);
				//allCollection.append($(document.createElement("BR")));
			});
		});

		var setDefaultCollection = function($userId, $collectionId)
		{
			var params = {command : "setDefaultCollection", userId: $userId, collectionId: $collectionId};
			$.post("./user.php", params, function($response){
				//var success = $($response).find("Success").text();
				var error   = $($response).find("Error > Message").text();

				if ( error.length > 0 )
				{
					alert(error);
				}
				else
				{
					_defaultCollection = $($response).find("title").text();
					_neLat = $($response).find("neLat").text();
					_neLon = $($response).find("neLon").text();
					_swLat = $($response).find("swLat").text();
					_swLon = $($response).find("swLon").text();
					$("#defaultCollectionTitle").text(_defaultCollection);
					
					if (_defaultCollection !== "No default collection")
					{
						//zoom to collection when click title
						$("#defaultCollectionTitle").click(function(){
							HyperCities.user.zoomToCollection(_neLat, _neLon, _swLat, _swLon);
						});
					}
					
					HyperCities.mainMap.closeInfoWindow();
				}
			}, "xml");
		};

		var saveChange = $(document.createElement("input"));
		saveChange.attr("type", "button");
		saveChange.attr("value", "save change");
		saveChange.click(function() {
			var collectionId = $("#allCollection input[name=radioCollection]:checked").data("collectionId");
			HyperCities.debug("collectionId="+collectionId);
			if (typeof(collectionId) === 'undefined' || collectionId === null)
			{
				alert("Please select one collection!");
				return;
			}
			setDefaultCollection(_userId, collectionId);
		});

		var reset = $(document.createElement("input"));
		reset.attr("type", "button");
		reset.attr("value", "clear settings");
		reset.click(function(){
			setDefaultCollection(_userId, null);
		});

		var searchBar = HyperCities.util.createSearchBar(allCollection);
		tempDiv.append(searchBar).append(allCollection).append(saveChange).append(reset);
		
		var map = HyperCities.mainMap.getMapInstance();
		var infoWinOpenHandle = GEvent.addListener(map, "infowindowopen", function(){
			HyperCities.mainMap.enableSync(false);
		});
		var infoWinCloseHandle = GEvent.addListener(map, "infowindowclose", function(){
			HyperCities.mainMap.restoreSync();
			GEvent.removeListener(infoWinOpenHandle);
			GEvent.removeListener(infoWinCloseHandle);
		});
		HyperCities.mainMap.openInfoWindow("html", HyperCities.mainMap.getCenter(), tempDiv.get(0), {maxWidth: 400, noCloseOnClick:true});
	};

	return {

		/**
		 * Basic user functions
		 */
		//called when user first click login tab
		init: function() {

			_addListener();

			if (HyperCities.user.isLogin())
			{
				$("#defaultCollectionTitle").text(_defaultCollection);

				//zoom to default collection at login time
				if (_defaultCollection !== "No default collection")
				{
					$("#defaultCollectionTitle").click();
				}
			}
		},
		
		// sync user data
		sync: function () {

			HyperCities.debug(_id + "Sync user");
			var params = { command : "sync" };
			//if server session does not have user info, nothing will happen (_parseSync will not be execute)
			$.post("./user.php", params, _parseSync, "xml");
		},

		// user logout
		logout: function () {
			this.blur();
			var data = { command : "logout" };
			$.post("./user.php", data , _parseLogout, "text");
		},

		// user login
		login: function () {
			HyperCities.debug(_id + "Login");
			this.blur();

			if ( $("#loginErrorBox").length > 0 )
			$("#loginErrorBox").remove();

			var data = { command  : "login",
				username : $("#username").val(),
				password : $("#password").val()
			};
			$.post("./user.php", data, _parseLogin, "xml");

			return false;
		},

		/**
		 * User utility functions
		 */
		//zoom to the collection
		zoomToCollection: function($neLat, $neLon, $swLat, $swLon) {
			
			if (($neLat===null || $neLon===null || $swLat===null || $swLon===null) || 
				($neLat==0 && $neLon==0 && $swLat==0 && $swLon==0) )
				return;	//invalid boundary
				
			var mainMap = HyperCities.mainMap.getMapInstance();
			var newBound = new GLatLngBounds();
			
			newBound.extend(new GLatLng($neLat, $neLon));
			newBound.extend(new GLatLng($swLat, $swLon));
			
			var newZoom = mainMap.getBoundsZoomLevel(newBound);
			mainMap.setCenter(newBound.getCenter(), newZoom);
		},
		
		hasUpdatePrivilege: function($objectId, $ownerId, $stateId) {

			$ownerId = parseInt($ownerId);
			$stateId = parseInt($stateId);
			//if ($.inArray($objectId, _unlockObjList) !== -1)
			//	return true;
			
			if ( _userId === HyperCities.config.HC_USER_ADMIN ||
				 _userId === $ownerId )
				return true;
			else return false;
		},

		hasDeletePrivilege: function($objectId, $ownerId, $stateId) {

			$ownerId = parseInt($ownerId);
			$stateId = parseInt($stateId);
			//if ($.inArray($objectId, _unlockObjList) !== -1)
			//	return true;
			
			if ( _userId === HyperCities.config.HC_USER_ADMIN ||
				 _userId === $ownerId )
				return true;
			else return false;
		},

		addCollection: function() {
			
			var tab1 = $('<div class="HCUpdateColDiv">'
					 +'<div class="form-item"><label> Title:  </label> <input type="text" id="title"></div>'
					 +'<div class="form-item"><label> Author: </label><input type="text" id="creator"></div>'
					 +'<div class="form-item"><label> Copyright: </label><input type="text" id="copyright"></div>'
					 +'<div class="form-item"><label> Description: </label><textarea rows="5" cols="30" id="description"></textarea></div>'
					 +'<div class="form-item"><div style="width:100px;height:80px;float:left"><label> State: </label></div>'
					 +'<div id="colState" style="position:relative; left:20px">'
					 +'<div id="publicDiv"><input type="radio" name="state" value="1" checked>Public</div>'
					 +'<div id="privateDiv"><input type="radio" name="state" value="2" id="private">Protected</div>'
					 +'<div><input type="radio" name="state" value="3" id="hidden">Hidden</div>'
					 +'</div> </div><br/>'
					 +'<div class="HCBottomBar"><input type="button" id="next" value="Next"></div>');
			
			$("#creator", tab1).val(HyperCities.user.getNickname());

			//add event listener
			$("#next", tab1).click( function() {
				HyperCities.mainMap.getInfoWindow().selectTab(1);
			});
			//show options for private state
			$("#private", tab1).click(function() {
	
				if ($("#priOption", tab1).length < 1)
				{
					var priOption = $("<div id='priOption' style='position:relative;left:20px'>"
									+ "keycode:<input type='password' id='password'></div>");
					$("#privateDiv", tab1).append(priOption);
				}
			});

			var tab2 = $("<div><b><span id='addOwnCTitle'>Add it to other collections:</span></b>"
						+ "<div id='treePanel' style='height:300px; overflow:auto'>"
						+ "<ul id='tree'></ul>"
						+ "</div>"
						//+ "<div><b><span id='addOtherCTitle'>Add it to other collections:</span></b>"
						//+ "<div id='other_collections'></div>"
						+ "<div class='HCBottomBar'><input type='button' id='updateBtn' value='Update'></div></div>");
			$("#updateBtn", tab2).unbind("click").click( function(){
				
				var title       = $("#title").val();
					creator     = $("#creator").val();
					copyright   = $("#copyright").val();
					description = $("#description").val();
					state       = ($("input[name=hidden]:checked").length > 0) ? 3 : $("input[name=state]:checked").val();
					password    = $("#password").val();
					addTo       = new Array();

				$("input[name=otherOption]:checked").each(function() {
					addTo.push($(this).data("collectionId"));	
				});

				$(".checkboxChecked").next().each(function(){
					addTo.push($(this).attr("id"));	
				});

				/*
				$("input[name=ownOption]:checked").each(function() {
					addTo.push($(this).data("collectionId"));	
				});
				*/
				if (addTo.length === 0)
				{
					alert("Please check at least one collection!");
					return;
				}

				var params = {title: title, 
							  creator: creator, 
							  copyright: copyright, 
							  description: description,
							  state: state,
							  password: password,
							  addTo: addTo.toString()};

				$.post("./addCollection.php", params, function($response){
					
					HyperCities.mainMap.closeInfoWindow();
					HyperCities.util.ajaxReport($response);
				
				}), "xml";

			});


			//tabInfoWindow variables
			var label1 = "1. Content";
			var label2 = "2. Add to";
			var addColWin = [ new GInfoWindowTab(label1, tab1.get(0)),
								 new GInfoWindowTab(label2, tab2.get(0)) ];

			var map = HyperCities.mainMap.getMapInstance();
			var infoWinOpenHandle = GEvent.addListener(map, "infowindowopen", function(){
				HyperCities.mainMap.enableSync(false);
				
				//load collection list after info window is opened
				var tree = HyperCities.util.loadCollectionTree($("#tree", tab2), null, null);
			});

			var infoWinCloseHandle = GEvent.addListener(map, "infowindowclose", function(){
				HyperCities.mainMap.restoreSync();
				GEvent.removeListener(infoWinOpenHandle);
			});
			HyperCities.mainMap.openInfoWindow("tabsHtml", HyperCities.mainMap.getCenter(), 
					addColWin, {maxWidth: 400, noCloseOnClick:true});

		},

		/**
		 * check user status functions
		 */
		//check if user data is synced.
		isSync: function() {
			return _sync;
		},

		isLogin: function () {
			//check login according to which page is loaded
			/*
			if ($("#loginBtn").length >= 1)
				_login = false;
			else
				_login = true;
			*/
			return _login;
		},

		isAdmin: function() {
			if (HyperCities.user.getUserId() === HyperCities.config.HC_USER_ADMIN)
				return true;
			else
				return false;
		},

		//refresh login page
		reload: function() {
			_loadLoginForm();		
		},

		/**
		 * getter and setter functions
		 */
		getUserId: function() {
			return _userId;
		},

		getNickname: function() {
			return _nickname;
		}
	};
}(); // end of Object

// end of file
