var ACN = new Object();

ACN.ToggleCheckboxes = Class.create();
ACN.ToggleCheckboxes.prototype = {

	initialize : function(options) 
	{
		this.mainCheckbox = $(options.mainCheckboxId);
		this.cbClassName = options.cbClassName;
		this.checkboxes = $A($$('input.' + this.cbClassName));

		this.confirmTemplate = new Template(options.templateString);	
		this.buttons = $A(options.buttons);		
		this.form = $(options.form);
		this.operationType = $(options.operationType);
		this.toggleCheckboxes = this.toggleCheckboxes.bindAsEventListener(this);
		this.doConfirm = this.doConfirm.bindAsEventListener(this);
		
		this.bindListeners();
	},
	
	bindListeners : function()
	{
		Event.observe(this.mainCheckbox, 'click', this.toggleCheckboxes);
		this.buttons.each(function(item)
		{
			Event.observe($(item), 'click', this.doConfirm);
		}.bind(this));
	},
	
	doConfirm : function(e)
	{
		var counter = 0;
		Event.stop(e);
		this.checkboxes.each(function(item){
			if (item.checked)
			{
				counter++;
			}
		});
		if (counter == 0)
		{
			alert('Вы не выбрали ни одного элемента.');
		}
		else
		{
			var element = Event.element(e);	
			this.operationType.value = element.id;
			var confirmString = this.confirmTemplate.evaluate({text: element.value});
			if (confirm(confirmString))
			{
				this.form.submit();
			}
		}
	},
	
	toggleCheckboxes : function()
	{
		this.checkboxes.each(function(item){
			item.checked = this.mainCheckbox.checked;
		}.bind(this));
	}		
};

ACN.SearchAC = Class.create();
ACN.SearchAC.prototype = {

	initialize : function(options) 
	{
		this.textbox = $(options.textboxID);
		this.button = $(options.buttonID);
		this.sampleLinks = $$(options.sampleLinksSelector);
		this.waiting = $(options.waitingID);
		this.result = $(options.resultID);
		this.url = options.url;
		this.acRegex = options.acRegex;
		this.emailRegex = options.emailRegex;

		this.errorTemplate = new Template(options.errorTemplate);
		this.successTemplate = new Template(options.successTemplate);

		this.makeRequest = this.makeRequest.bindAsEventListener(this);
		this.putSample = this.putSample.bindAsEventListener(this);

		this.samples = {
			'wmid'	: '123456789012',
			'wmr'	: 'R123456789012',
			'wmz'	: 'Z123456789012',
			'wme'	: 'E123456789012',
			'email'	: 'mail@example.com'
		};

		this.bindListeners();
	},
	
	bindListeners : function()
	{
		Event.observe(this.button, 'click', this.makeRequest);
		this.sampleLinks.each(function(item){
			Event.observe(item, 'click', this.putSample);
		}.bind(this));
	},

	removeListeners : function()
	{
		Event.stopObserving(this.button, 'click', this.makeRequest);
	},

	putSample: function(e)
	{
		Event.stop(e);
		var el = Event.element(e);
		var ids = el.id.split('-');
		var id = ids[1];
		var sample = this.samples[id];
		this.textbox.value = sample;
	},

	makeRequest : function(e)
	{
		Event.stop(e); //stop submitting a form
		var value = this.textbox.value;
		if (value.length == 0 || !(this.regexTest(this.acRegex, value) || this.regexTest(this.emailRegex, value)))
		{
			alert('Неверные параметры поиска: значение должно соответствовать формату WMID, формату кошелька WebMoney или формату e-mail адреса.');
		}
		else
		{
			this.removeListeners();
			this.result.hide();
			//this.waiting.show();
			
			var currentRequest = new Ajax.Request(
				this.url,
				{
					method: 'post',
					parameters: {value: value},
					onSuccess: this.processRequest.bind(this)
				});		
		}
	},

	processRequest : function(originalRequest)
	{
		var data = originalRequest.responseText.evalJSON();
		if (data['success'] == 1)
		{
			this.result.innerHTML = this.successTemplate.evaluate({type: data['type'], value: data['value']});
		}
		else
		{
			this.result.innerHTML = this.errorTemplate.evaluate({type: data['type'], value: data['value']});
		}
		//this.waiting.hide();
		this.result.show();
		this.bindListeners();
	},

	regexTest : function(regexText, testString)
	{
		var regex = new RegExp(regexText);
		return regex.test(testString);
	}	
	
};

ACN.Samples = Class.create();
ACN.Samples.prototype = {

	initialize : function(options) 
	{
		this.textbox = $(options.textboxID);
		this.sampleLinks = $$(options.sampleLinksSelector);
		this.putSample = this.putSample.bindAsEventListener(this);

		this.samples = {
			'wmid'	: '123456789012',
			'wmr'	: 'R123456789012',
			'wmz'	: 'Z123456789012',
			'wme'	: 'E123456789012',
			'email'	: 'mail@example.com'
		};
		
		this.bindListeners();
	},
		
	bindListeners : function()
	{
		this.sampleLinks.each(function(item){
			Event.observe(item, 'click', this.putSample);
		}.bind(this));
	},

	putSample: function(e)
	{
		Event.stop(e);
		var el = Event.element(e);
		var ids = el.id.split('-');
		var id = ids[1];
		var sample = this.samples[id];
		this.textbox.value = sample;
	}
};


ACN.UsersFav = Class.create();
ACN.UsersFav.prototype = {

	initialize : function(options) 
	{
		this.addUrl		= options.addUrl;
		this.delUrl		= options.delUrl;
		this.selector	= options.selector;
		
		this.emailsLink = options.emailsLinkId ? $(options.emailsLinkId) : null;
		this.emailsPlaceholderId = options.emailsPlaceholderId ? options.emailsPlaceholderId : null;
		this.emailsSelector = options.emailsSelector ? options.emailsSelector : null;
		this.eventHandler = this.eventHandler.bindAsEventListener(this);
		this.addEventListeners();
		
		if (this.emailsLink != null)
		{
			Event.observe(this.emailsLink, 'click', this.showEmails);
		}
	},
	
	addEventListeners: function(event)
	{
		$$(this.selector).each(function(item){
			Event.observe(item, 'click', this.eventHandler);
		}.bind(this));
	},

	removeEventListeners: function(event)
	{
		$$(this.selector).each(function(item){
			Event.stopObserving(item, 'click', this.eventHandler);
		}.bind(this));
	},
	
	eventHandler: function(event)
	{
		this.removeEventListeners();
		var el = Event.element(event);
		if (el.checked)
		{
			this._makeRequest(this.addUrl, el.id);
		}
		else
		{
			this._makeRequest(this.delUrl, el.id);
		}
	},

	_makeRequest: function(url, value)
	{
		var currentRequest = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: {value: value},
				onSuccess: this._processRequest.bind(this)
			});
	},

	_processRequest : function(originalRequest)
	{
		var data = originalRequest.responseText.evalJSON();
		this.addEventListeners();
	},

	showEmails: function(event)
	{
		Event.stop(event);
		var emails = new Array();
		$$('.email_fav').each(function(item){
			emails.push(item.innerHTML);
		});
		$("emails_fav").show();
		$("emails_fav").innerHTML = emails.join(', ');
	}
};

ACN.AdmEm = Class.create();
ACN.AdmEm.prototype = {

	initialize : function(options) 
	{
		this.cbClass = options.cbClass;
		this.mainCbId = options.mainCbId;
		this.emailsContainer = options.emailsContainer;
		this.emailsClass = options.emailsClass;
		this.emails = new Array();
		
		this.eventHandler = this.eventHandler.bindAsEventListener(this);
		this.eventHandlerMain = this.eventHandlerMain.bindAsEventListener(this);
		this.bindListeners();
	},
	
	bindListeners: function()
	{
		Event.observe($(this.mainCbId), 'click', this.eventHandlerMain);
		$$(this.cbClass).each(function(item){
			Event.observe(item, 'click', this.eventHandler);
		}.bind(this));
	},
	
	eventHandler: function(event)
	{
		var el = Event.element(event);
		var id = el.id.replace('item_', '');
		var val = $('email_' + id).innerHTML;
		if (el.checked)
		{
			if (this.emails.indexOf(val) == -1)
			{
				this.emails.push(val);
			}
		}
		else
		{
			if (this.emails.indexOf(val) != -1)
			{
				this.emails = this.emails.without(val);
			}
		}
		$(this.emailsContainer).innerHTML = this.emails.join(', ');
	},
	
	eventHandlerMain: function(event)
	{
		var el = Event.element(event);
		if (el.checked)
		{
			$$(this.emailsClass).each(function(item)
			{
				var val = item.innerHTML;
				if (this.emails.indexOf(val) == -1)
				{
					this.emails.push(val);
				}
			}.bind(this));
		}
		else
		{
			$$(this.emailsClass).each(function(item)
			{
				var val = item.innerHTML;
				if (this.emails.indexOf(val) != -1)
				{
					this.emails = this.emails.without(val);
				}
			}.bind(this));
		}
		$(this.emailsContainer).innerHTML = this.emails.join(', ');
	}
};

ACN.Translit = Class.create();
ACN.Translit.prototype = {

	initialize : function(options)
	{
		this.o = options;
		this.onKeyup = this.onKeyup.bindAsEventListener(this);
		Event.observe($(this.o.inputEl), 'keyup', this.onKeyup);
		this._setDefaultOptions();
	},

	onKeyup: function(event)
	{
		var str = $(this.o.inputEl).value;
		var result = '';
		for (var i = 0; i < str.length; i++) {
			result += this.transliterate(str.charAt(i))
		}
		
		var regExp = new RegExp('[' + this.o.urlSeparator + ']{2,}', 'g');
		result = result.replace(regExp, this.o.urlSeparator);
		
		$(this.o.outputEl).value = result;
	},

	transliterate: function(char)
	{
		var opts = this.o;
		var charIsLowerCase = true, trChar;
		if (char.toLowerCase() != char) {
			charIsLowerCase = false;
		}
		
		char = char.toLowerCase();

		var index = opts.dictOriginal.indexOf(char);
		if (index == -1) {
			trChar = char;
		} else {
			trChar = opts.dictTranslate[index];
		}
		
		if (opts.type == 'url') {
			var code = trChar.charCodeAt(0);

			if (code >= 33  && code <= 47 && code != 45
				|| code >= 58  && code <= 64
				|| code >= 91  && code <= 96
				|| code >= 123 && code <= 126
				|| code >= 1072
			) {
				return '';
			}
			if (trChar == ' ' || trChar == '-') {
				return opts.urlSeparator;
			}
		}
		
		if (opts.caseStyle == 'upper') {
			return trChar.toUpperCase();
		} else if (opts.caseStyle == 'normal') {
			if (charIsLowerCase) {
				return trChar.toLowerCase();
			} else {
				return trChar.toUpperCase();
			}
		}
		return trChar;
	},
	
	_setDefaultOptions: function()
	{
		this.o.urlSeparator = '-';
		this.o.caseStyle = 'lower';
		this.o.type = 'url';
		this.o.dictOriginal = ['а', 'б', 'в', 'г', 'д', 'е',
								'ё', 'ж', 'з', 'и', 'й', 'к',
								'л', 'м', 'н', 'о', 'п', 'р',
								'с', 'т', 'у', 'ф', 'х', 'ц',
								'ч', 'ш', 'щ', 'ъ', 'ы', 'ь',
								'э', 'ю', 'я',
								'і', 'є', 'ї', 'ґ',
								'Ě', 'Š', 'Č', 'Ř', 'Ž', 'Ý', 'Á', 'Í', 'É', 'Ú', 'Ů', 
								'ě', 'š', 'č', 'ř', 'ž', 'ý', 'á', 'í', 'é', 'ú', 'ů', 
								'Š', 'š', 'Ð', 'd', 'Ž', 'ž', 'C', 'c', 'C', 'c',
								'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É',
								'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô',
								'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß',
								'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é',
								'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó',
								'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ý', 'ý', 'þ',
								'ÿ', 'R', 'r'
								];
		this.o.dictTranslate = ['a', 'b', 'v', 'g', 'd', 'e',
								'e', 'zh','z', 'i', 'j', 'k',
								'l', 'm', 'n', 'o', 'p', 'r',
								's', 't', 'u', 'f', 'h', 'ts',
								'ch','sh','sch', '', 'y', '',
								'e', 'ju', 'ja',
								'i', 'je', 'ji', 'g',
								'E', 'S', 'C', 'R', 'Z', 'Y', 'A', 'I', 'E', 'U', 'U', 
								'e', 's', 'c', 'r', 'z', 'y', 'a', 'i', 'e', 'u', 'u', 
								'S', 's', 'Dj', 'd', 'Z', 'z', 'C', 'c', 'C', 'c',
								'A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E',
								'E', 'E', 'I', 'I', 'I', 'I', 'N', 'O', 'O', 'O',
								'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'B', 'Ss',
								'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e',
								'e', 'e', 'i', 'i', 'i', 'i', 'o', 'n', 'o', 'o',
								'o', 'o', 'o', 'o', 'u', 'u', 'u', 'y', 'y', 'b',
								'y', 'R', 'r'
								];
	}

};
