var _wishlistPopup;

window.addEvent('domready', function() {
	var _wishlistpopupText = 
	'<center><h4 style="color: green;">' + Locale.get('Product was added to loved list') + '.<h4></center>'
	+'<div style="margin-top: 10px;">'
	+'<a style="font-size: 10pt;" href="'+ wishlistFbAppAddress +'wishlist/view">' 
	+ Locale.get('Visit Loved products facebook application') + '</a>'
	+ '<br/><a style="font-size: 10pt;" href="JavaScript:_wishlistPopup.hide();FB.Connect.showBookmarkDialog();">' 
	+ Locale.get('Bookmark loved products application now') + '!</a></div>';
	
	$$('.add_to_wishlist').addEvent('click', function(e) {
		e = new Event(e);
		e.stop();
		
		var el = this;
		
		//Create wishlist popup
		_wishlistPopup = new InfoPopup({
			container: $('centerCell'),
			resources: '/accounting_res',
			width: 300,
			height: 120
		});
	
		_wishlistPopup.setTitle(Locale.get('Loved products info'));
		_wishlistPopup.setMessage(_wishlistpopupText);
		
		var pos = el.getPosition();
		_wishlistPopup.setPosition({'top': pos.y+16, 'left': pos.x});
		_wishlistPopup.show();
		_wishlistPopup.setBusyState(true);
		
		//Send request closure
		var sendRequest = function() {
			//Check, has app permission to publish on user wall. If no - ask user for it.
			FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(hasPublishPermission) {
				if(hasPublishPermission != 1) {
					FB.Connect.showPermissionDialog('publish_stream', function(givenPerms) {});
				}
			});

			//Send add to wishlist request
			var request = new Json.Remote(el.href, {
				onComplete: function(response) {
	    			if(response == 1) {
	    				_wishlistPopup.setMessage(_wishlistpopupText);
	    				_wishlistPopup.setBusyState(false);
	    			}
	    			else {
	    				_wishlistPopup.setMessage(Locale.get('Error occure while adding product to wishlist'));
	    				_wishlistPopup.setBusyState(false);
	    			}
				}
			}).send();
		}

		//Connect FB user and then send add request
		FB.Connect.ifUserConnected(
			sendRequest,
			FB.Connect.requireSession
		);
	});
});

//This small hack added ONLY for wishlist client compatibility with mootools 1.2

if(!Json) {
	var Json = {};
}

if(!$defined(Json.Remote)) {
	Json.Remote = function(url, options) {
		options.url = url;
		
		return new Request.JSON(options);
	}
}