I18n.setLocale(App.lang);

function redirect(url, sec) {
	if (sec > 0) {
		setTimeout(function(){ redirect(url); }, sec * 1000);
	} else {
		document.location.href = url;
	}
}

StylesManager = (function(){
	var printStyles = $$("link[media='print']");
	
	return {
		switchToPrintVersion: function(options){
			printStyles.each(function(link){
				link.media = "";
			});
			Util.Dom.getBody().addClassName("print-version");
		},
		switchToNormalVersion: function(options){
			printStyles.each(function(link){
				link.media = "print";
			});
			Util.Dom.getBody().removeClassName("print-version");
		}
	}
})();

Notifier = (function(){
	var msgCt;

    function createMessage(cls, text){
        return new Element('div', {'class':'notifier roundtangle-5 ' + (cls || ''), 'style':'display:none'}).update(text);
    }
    
	function show(o){
		if(!msgCt){
			document.body.appendChild(msgCt = new Element('div', {id:'notifiers-ct'}));
		}
		var m = createMessage(o.cls, o.text);
		msgCt.appendChild(m);
		
		msgCt.alignTo(document.body, 't-t');
		m.appear({queue: {scope: 'notifiers', position: 'front'}, duration: 0.5})
		 .fade({queue: {scope: 'notifiers', position: 'with-last'}, delay: 1, afterFinish: function(effect){effect.element.remove()}});
	}
	
	return {
		notification: function(text){
			return show({
				text: text,
				cls: 'notification'
			});
		},
		warning: function(text){
			return show({
				text: text,
				cls: 'warning'
			});
		}
	}
})();

function addToMyFavorites(id, options, e){
	var myFavorites = StateManager.get("kh-favorites"),
		success  = false;

	options = options || {};
	
	if (myFavorites && myFavorites.isJSON()){
		myFavorites = myFavorites.evalJSON();
		if (Object.isArray(myFavorites)){
			if (!myFavorites.include(id)){
				myFavorites.push(id);
				Notifier.notification(__("Object was successfully added to your favorites"));
			} else {
				Notifier.warning(__("Object is already in your favorites"));
			}
			success = true;
		}
	}
	if (!success){
		myFavorites = [id];
		Notifier.notification(__("Object was successfully added to your favorites"));
	}
	
	$("user-favorites-count").update(myFavorites.length);
	StateManager.set("kh-favorites", myFavorites.toJSON());
	
	if (e) {
		Event.stop(e);
		var el = e.element();
		if (el.tagName.toLowerCase() == "span"){
			el = el.up("a");
		}
		el.removeClassName('add-to-my-objects').addClassName('remove-from-my-objects');
		options.addText = el.down("span").innerHTML;
		el.title = __("Удалить обьект из избранных");
		el.down("span").update(options.deleteText || __("Удалить"));
		if (Browser.IE){
			el.onclick = function(){
				removeFromMyFavorites(id, options, e)
			};
		} else {
			el.onclick = Prototype.emptyFunction;
			el.stopObserving("click"); 
			el.observe("click", function(e){
				removeFromMyFavorites(id, options, e);
			});
		}
	}
}

function removeFromMyFavorites(id, options, e){
	var myFavorites = StateManager.get("kh-favorites"),
		success  = false;
	
	options = options || {};
	
	if (myFavorites && myFavorites.isJSON()){
		myFavorites = myFavorites.evalJSON();
		if (Object.isArray(myFavorites)){
			if (myFavorites.include(id)){
				myFavorites = myFavorites.without(id);
				Notifier.notification(__("Object was successfully deleted from your favorites"));
			} else {
				//Notifier.warning(__("Object not in your favorites"));
			}
			success = true;
		}
	}
	if (!success){
		myFavorites = [];
	}
	
	$("user-favorites-count").update(myFavorites.length);
	StateManager.set("kh-favorites", myFavorites.toJSON());
	
	if (e) {
		Event.stop(e);
		var el = e.element();
		if (el.tagName.toLowerCase() == "span"){
			el = el.up("a");
		}
		el.removeClassName('remove-from-my-objects').addClassName('add-to-my-objects');
		options.deleteText = el.down("span").innerHTML;
		el.title = __('Добавить обьект в избранные');
		el.down("span").update(options.addText || __('Add to favorites'));
		if (Browser.IE){
			el.onclick = function(){
				addToMyFavorites(id, options, e)
			};
		} else {
			el.onclick = Prototype.emptyFunction;
			el.stopObserving("click"); 
			el.observe("click", function(e){
				addToMyFavorites(id, options, e);
			});
		}
	}
	
	if (options.refresh !== false){
		redirect(document.location.href);
	}
}

document.observe('dom:loaded', function() {

	// Login/Register/Fogot popup
	
	var userLoginLink  = $('user-login-link');
	
	if (userLoginLink) {
		var userLoginPopup = $('user-login-popup'),
			userLoginForm  = $('user-login-form'),
			userRegisterForm  = $('user-register-form'),
			userForgotForm  = $('user-forgot-form'),
			userLoginPopupReducer = userLoginPopup.down('div.reducer'),
			userLoginPopupCloseBtn = userLoginPopup.down('ins.close-button');
		
		userLoginLink.observe('click', function(e){
			Event.stop(e);
			Overlay.show(true, {
				afterFinish: function(){
					if (Browser.IE){
						userLoginPopup.removeClassName('hidden').show().alignTo(Util.Dom.getBody(), 'c-c', [-40, -40]);
					}
					userLoginForm.focusFirstElement();
				}
			});
			if (!Browser.IE){
				userLoginPopup.removeClassName('hidden').show().alignTo(Util.Dom.getBody(), 'c-c', [-40, -40]).hide().appear({from:0, to:1, duration:0.2});
			}
		});
		userLoginPopupCloseBtn.observe('click', function(){
			userLoginPopup[Browser.IE ? 'hide' : 'fade']({from:1, to:0, duration:0.2});
			Overlay.hide(true);
		});
		
		userLoginForm.observe('submit', function(e){
			Event.stop(e);

			this.request({
				onCreate: function() {
					userLoginPopupReducer.mask(null, __('Processing..'));
					userLoginPopupCloseBtn.hide();
				},
				onSuccess: function(transport) {
					var response = transport.responseJSON;
					if (response.success) {
						redirect(App.appUrl + '/' + App.lang + '/user/');
					} else {
						userLoginPopupReducer.unmask();
						userLoginPopupCloseBtn.show();
						var errorsHtml = [];
						response.errors.each(function(error){
							errorsHtml.push(error.text);
						});
						$('user-login-form').hide();
						$('user-login-form-errors-ct').show().down('ul').update('<li>'+errorsHtml.join('</li><li>')+'</li>');
					}
					
				},
				onFailure: function(transport) {
					userLoginPopupReducer.unmask();
					userLoginPopupCloseBtn.show();
					$('user-login-form').hide();
					$('user-login-form-errors-ct').show().down('ul').update('<li>'+__('An error occurred.')+'</li>');
				}
			});
		});
		
		userRegisterForm.observe('submit', function(e){
			Event.stop(e);

			this.request({
				onCreate: function() {
					userLoginPopupReducer.mask(null, __('Processing..'));
					userLoginPopupCloseBtn.hide();
				},
				onSuccess: function(transport) {
					var response = transport.responseJSON;
					if (response.success) {
						var email = $('user-register-form-email').value;
						redirect(App.appUrl + '/' + App.lang + '/user/activation/?user[email]=' + email);
					} else {
						userLoginPopupReducer.unmask();
						userLoginPopupCloseBtn.show();
						var errorsHtml = [];
						response.errors.each(function(error){
							errorsHtml.push(error.text);
						});
						$('user-register-form').hide();
						$('user-register-form-errors-ct').show().down('ul').update('<li>'+errorsHtml.join('</li><li>')+'</li>');
					}
					
				},
				onFailure: function(transport) {
					userLoginPopupReducer.unmask();
					userLoginPopupCloseBtn.show();
					$('user-register-form').hide();
					$('user-register-form-errors-ct').show().down('ul').update('<li>'+__('An error occurred.')+'</li>');
				}
			});
		});
		
		userForgotForm.observe('submit', function(e){
			Event.stop(e);

			this.request({
				onCreate: function() {
					userLoginPopupReducer.mask(null, __('Processing..'));
					userLoginPopupCloseBtn.hide();
				},
				onSuccess: function(transport) {
					var response = transport.responseJSON;
					if (response.success) {
						$('user-forgot-form').hide();
						$('user-forgot-form-success-ct').show()
					} else {
						var errorsHtml = [];
						response.errors.each(function(error){
							errorsHtml.push(error.text);
						});
						$('user-forgot-form').hide();
						$('user-forgot-form-errors-ct').show().down('ul').update('<li>'+errorsHtml.join('</li><li>')+'</li>');
					}
					userLoginPopupReducer.unmask();
					userLoginPopupCloseBtn.show();					
				},
				onFailure: function(transport) {
					userLoginPopupReducer.unmask();
					userLoginPopupCloseBtn.show();
					$('user-forgot-form').hide();
					$('user-forgot-form-errors-ct').show().down('ul').update('<li>'+__('An error occurred.')+'</li>');
				}
			});
		});
	}
	
	//get object info popup
	
	var getObjectInfoLink  = $$('.get-object-info-link')[0];
	
	if (getObjectInfoLink) {
		var getObjectInfoPopup = $('get-object-info-popup'),
			getObjectInfoForm  = $('get-object-info-form'),
			getObjectInfoPopupReducer = getObjectInfoPopup.down('div.reducer'),
			getObjectInfoPopupCloseBtn = getObjectInfoPopup.down('ins.close-button');
		
		getObjectInfoLink.observe('click', function(e){
			Event.stop(e);
			Overlay.show(true, {
				afterFinish: function(){
					if (Browser.IE){
						getObjectInfoPopup.removeClassName('hidden').show().alignTo(Util.Dom.getBody(), 'c-c', [-40, -40]);
					}
					getObjectInfoForm.focusFirstElement();
				}
			});
			if (!Browser.IE){
				getObjectInfoPopup.removeClassName('hidden').show().alignTo(Util.Dom.getBody(), 'c-c', [-40, -40]).hide().appear({from:0, to:1, duration:0.2});
			}
		});
		getObjectInfoPopupCloseBtn.observe('click', function(e){
			Event.stop(e);
			getObjectInfoPopup[Browser.IE ? 'hide' : 'fade']({from:1, to:0, duration:0.2});
			Overlay.hide(true);
			$('get-object-info-form').show();
			$('get-object-info-form-errors-ct').hide();
			$('get-object-info-form-success-ct').hide();		
		});
		
		getObjectInfoForm.observe('submit', function(e){
			Event.stop(e);

			this.request({
				onCreate: function() {
					getObjectInfoPopupReducer.mask(null, __('Processing..'));
					getObjectInfoPopupCloseBtn.hide();
				},
				onSuccess: function(transport) {
					var response = transport.responseJSON;
					if (response.success) {
						getObjectInfoPopupReducer.unmask();
						getObjectInfoPopupCloseBtn.show();
						$('get-object-info-form').hide();
						$('get-object-info-form-success-ct').show();
						//redirect(App.appUrl + '/' + App.lang + '/user/');
						
					} else {
						getObjectInfoPopupReducer.unmask();
						getObjectInfoPopupCloseBtn.show();
						var errorsHtml = [];
						response.errors.each(function(error){
							errorsHtml.push(error.text);
						});
						$('get-object-info-form').hide();
						$('get-object-info-form-errors-ct').show().down('ul').update('<li>'+errorsHtml.join('</li><li>')+'</li>');
					}
					
				},
				onFailure: function(transport) {
					getObjectInfoPopupReducer.unmask();
					getObjectInfoPopupCloseBtn.show();
					$('get-object-info-form').hide();
					$('get-object-info-form-errors-ct').show().down('ul').update('<li>'+__('An error occurred.')+'</li>');
				}
			});
		});	
		
	}
	
});

FeedbackPopup = (function(){
	
	var popup, reducer, closeBtn, form, successCt, errorsCt;
	
	function getPopup(){
		if (!popup){
			popup = $('objects-feedback-popup');
			reducer = popup.down('div.reducer');
			closeBtn = popup.down('ins.close-button');
			form = popup.down("form");
			successCt = $("objects-feedback-success-ct");
			errorsCt = $("objects-feedback-errors-ct");
			
			closeBtn.observe('click', hide);
			form.observe('submit', function(e){
				Event.stop(e);

				this.request({
					onCreate: function() {
						mask(__('Processing..'));
						closeBtn.hide();
					},
					onSuccess: function(transport) {
						var response = transport.responseJSON;
						reducer.unmask();
						closeBtn.show();
						form.hide();
						if (response.success) {
							successCt.show();
						} else {
							var errorsHtml = [];
							response.errors.each(function(error){
								errorsHtml.push(error.text);
							});
							form.hide();
							errorsCt.show().down('ul').update('<li>'+errorsHtml.join('</li><li>')+'</li>');
						}
						
					},
					onFailure: function(transport) {
						reducer.unmask();
						closeBtn.show();
						form.hide();
						//errorsCt.show().down('ul').update('<li>'+__('An error occurred.')+'</li>');
					}
				});
			});
		}
		return popup;
	}
	
	function mask(msg){
		var popup = getPopup();
		reducer.mask(null, msg);
	}
	
	function unmask(){
		var popup = getPopup();
		reducer.unmask();
	}
	
	function showOverlay(){		
		var popup = getPopup();
		Overlay.show(true, {
			afterFinish: function(){
				if (Browser.IE){
					popup.removeClassName('hidden').show().alignTo(Util.Dom.getBody(), 'c-c', [-40, -40]);
				}
				form.focusFirstElement();
			}
		});
		if (!Browser.IE){
			popup.removeClassName('hidden').show().alignTo(Util.Dom.getBody(), 'c-c', [-40, -40]).hide().appear({from:0, to:1, duration:0.2});
		}
	}
	
	function hide(){
		var popup = getPopup();
		popup[Browser.IE ? 'hide' : 'fade']({from:1, to:0, duration:0.2});
		Overlay.hide(true);
	}
	
	return {
		show: function(data){
			var popup = getPopup().show();
			
			for(var name in data){
				if (data.hasOwnProperty(name)){
					var field = form.down("*[name='feedback["+name+"]']");
					if (field){
						field.setValue(data[name]);
					}
				}
			}
			
			successCt.hide();
			errorsCt.hide();
			form.show();
			showOverlay();
			
			return false;
		},
		hide: function(){
			hide();
			
			return false;
		}
	}

})();
