// basic
document.observe('dom:loaded', function () {
	initLoginForm();
	initSearchForm();
});

// registration form
document.observe('dom:loaded', function () {
	if ($('select_account_type')) {
		// default
		var company_selected = Boolean($F('select_account_type') * 1);
		$$('.company_only').each(function(e){
			company_selected ? e.show() : e.hide();
		});
		// onchange
		Event.observe('select_account_type', 'change', function(){
			$$('.company_only').each(function(e){
				e.toggle();
			});
		}, false);
	}
});

// disable submit button after form is sent
document.observe('dom:loaded', function () {
	$$('form').each(function(e){
		Event.observe(e, 'submit', function() {
			var button = e.getElementsByTagName('button')[0];
			if (button) {
				button.disabled = true;
				button.blur();
				// IE 8+
				// button.style.cssText += '-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"';
				// IE 5 to IE 7
				button.style.filter = 'alpha(opacity=50)';
				// prototype implementation is not complete
				button.setOpacity(0.4);
			}
		}, false);
	});
});

// submit forms with only one select
document.observe('dom:loaded', function () {
	var sorting_options = $('sorting_options');
	if (sorting_options) {
		Event.observe('sorting_options', 'change', function(){
			$('sorting_form').submit();
		}, false);
		$('set_sorting_button').hide();
	}
});

// replace simple form select with rich html content (flags images for conuntries)
document.observe('dom:loaded', function () {
	var set_language_button = $('set_language_button');
	if (set_language_button) {
		$('set_language_button').hide();
	}
	
	var current_language = '';
	var ul = new Element('ul');
	
	$$('select#set_language option').each(function(e){
		var li	= new Element('li', { 'class' : e.value });
		var img	= new Element('img', { 'src' : '/img/flag/' + e.value + '.png'});
		var a	= new Element('a', { 'href' : '?setLanguage=' + e.value });

		a.insert(img);
		a.insert(' ' + e.innerHTML);
		
		li.insert(a);

		if (e.selected) {
			current_language = e.value;	
			ul.insert({ 'top' : li });
		} else {
			li.hide();
			ul.insert({ 'bottom' : li });
		}
	});
	
	Event.observe(ul, 'mouseover', function(){
		ul.childElements().each(function(li){
			li.show();
		});
	}, false);

	Event.observe(ul, 'mouseout', function(){
		ul.childElements().each(function(li){
			if (li.hasClassName(current_language) == false){
				li.hide();
			}
		});
	}, false);

	Element.replace('set_language', Element.wrap(ul, 'div', { 'id': 'set_language_list' }));
	Element.absolutize(ul);
	Element.setStyle(ul, { 'height':'auto' }); // fix
});


// watchlist
document.observe('dom:loaded', function () {	
	var watchlist = [];
	if (userLogged()) {
		if (Cookie.get('watchlist_private')) {
			watchlist = Cookie.get('watchlist_private').split(',');
			markWatchlistItems(watchlist);
		} else {
			new Ajax.Request('/ajax/watchlist', { method: 'get', parameters: 'id=0', onComplete: function(){
				watchlist = Cookie.get('watchlist_private', '').split(',');
				markWatchlistItems(watchlist);
			} });
		}
	} else {
		if (Cookie.get('watchlist_private')) {
			Cookie.erase('watchlist_private');
		}
		if (Cookie.get('watchlist_public')) {
			watchlist = Cookie.get('watchlist_public').split(',');
		}
		markWatchlistItems(watchlist);
	}
});


function markWatchlistItems(watchlist) {
	$$('a.watchlist').each(function(e){
		if (watchlist.include(e.getAttribute('rel'))) {
			e.addClassName('saved');
		}

		Event.observe(e, 'click', function(onclick){
			e.toggleClassName('saved');
			e.blur();

			var url_property = e.getAttribute('rel') * 1;
			var saved = e.hasClassName('saved');

			if (saved) {
				watchlist.push(url_property);
			} else {
				watchlist = watchlist.without(url_property);
				var table_row = $('tr_' + url_property);
				if (table_row) {
					table_row.childElements().each(function(td){
						td.style.background = 'transparent';
					});
					new Effect.Highlight(table_row, {
						afterFinish: function() {
							table_row.remove();
							var i = 0;
							$$('#rows tr').each(function(tr){
								tr.className = ++i % 2 ? 'odd':'';
							});
							if (i == 0) {
								reload();
							}
						}
					});
				}
			}
			
			if (userLogged()) {
				new Ajax.Request('/ajax/watchlist', { method: 'get', parameters: 'id=' + url_property + (saved ? '':'&delete') });
			} else {
				Cookie.set('watchlist_public', watchlist.toString(), watchlist.length ? 90 : -1);
			}

			// stop event - return false
			onclick.stop();
		});
	});
}


// make all textare auto-resizable
document.observe('dom:loaded', function () {
	$$('textarea').each(function(e){
		e.onkeyup = function() {
			resizeTextarea(this, 400);
		};
	});
});


// suggestion_box only ajax
var defaultText = '';
document.observe('dom:loaded', function () {

	defaultText = $F('suggestion_textarea');

	Event.observe($('suggestion_textarea'), 'focus', function() {
		if ($F('suggestion_textarea') == defaultText) {
			$('suggestion_textarea').update();
		}
	});

	Event.observe($('suggestion_textarea'), 'blur', function() {
		if ($F('suggestion_textarea') == '') {
			$('suggestion_textarea').update(defaultText);
		}
	});

	Event.observe($('suggestion_form'), 'submit', function(onsubmit) {
		if ($F('suggestion_textarea') != defaultText && $F('suggestion_textarea') != '') {
			// save
			new Ajax.Request('/ajax/suggestion-box', { parameters: $('suggestion_form').serialize(true) });
			// info message
			new Effect.BlindUp('suggestion_box', { duration: 0.3, afterFinish: function() {
				var message = new Element('p').update($F('success_message'));
				$('suggestion_box').update(message);
				new Effect.BlindDown('suggestion_box', { duration: 0.3 });
			} });
		} else {
			$('suggestion_submit_button').disabled = false;
			$('suggestion_submit_button').setOpacity(1);
			$('suggestion_textarea').update(defaultText);
			new Effect.Highlight('suggestion_textarea');
		}
		onsubmit.stop();
	});
});


function userLogged() {
	return ($('login_user') == null);
}

function initSearchForm() {
	var input_fulltext = document.getElementById('fulltext');
	if (input_fulltext) {
		var default_value = input_fulltext.value;
		input_fulltext.onfocus = function() {
			if (this.value == default_value) {
				this.value = '';
			}
		};
		input_fulltext.onblur = function() {
			if (this.value == '') {
				this.value = default_value;
			}
		};
	}
}


function changeInputType(obj, show) {
	try {
		obj.type = show ? 'text' : 'password';
	} catch(e) {
		// IE always suck
		var input = document.createElement('INPUT');
		input.type = show ? 'text' : 'password';
		input.id = obj.id;
		input.name = obj.name;
		input.value = obj.value;
		input.onfocus = obj.onfocus;
		input.onblur = obj.onblur;
		obj.parentNode.replaceChild(input,obj);
		if (!show) {
			setTimeout("document.getElementById('login_pass').focus()", 100);
		}
	}
}

function initLoginForm() {
	var input_user = document.getElementById('login_user');
	if (input_user) {
		var default_value_user = input_user.value;
		input_user.onfocus = function() {
			if (this.value == default_value_user) {
				this.value = '';
			}
		};
		input_user.onblur = function() {
			if (this.value == '') {
				this.value = default_value_user;
			}
		};
	}

	var input_pass = document.getElementById('login_pass');
	if (input_pass) {
		var default_value_pass = input_pass.value;
		input_pass.onfocus = function() {
			if (this.value == default_value_pass) {
				this.value = '';
				changeInputType(this, false);
				if (window.opera) {
					this.focus();
				} else {
					try {
						this.value.select(); // firefox problem: no cursor
					} catch(e) {}
				}
			}
		};
		input_pass.onblur = function() {
			if (this.value == '') {
				this.value = default_value_pass;
				changeInputType(this, true);
			}
		};
		changeInputType(input_pass, true);
	}
}

function resizeTextarea(element, maxHeight) {
	var textarea = $(element);
	var adjustedHeight = textarea.clientHeight;
	if (!maxHeight || maxHeight > adjustedHeight) {
		adjustedHeight = Math.max(textarea.scrollHeight, adjustedHeight);
		if (maxHeight)
			adjustedHeight = Math.min(maxHeight, adjustedHeight);
		if (adjustedHeight > textarea.clientHeight)
			textarea.style.height = adjustedHeight + "px";
	}
}



/* COMMON */
function reload() {
	window.location.href = window.location.href;
	// window.location.reload(); // znovu nacitava obrazky atd. ako F5
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function isEmail(str) {
	return !str.search(/^[^.]+(\.[^.]+)*@([^.]+[\.])+[a-z]{2,4}$/);
}

function checkExt(str, ext) {
	return str.substr(str.lastIndexOf('.')+1).toLowerCase() == ext;
}

function isInt(str) {
	var reg = /^\d+$/;
	return reg.test(str);
}

// overovanie vstupu pre INPUT ak ma byt integer
function isNumber(t) {
	if (!isInt(t.value)) {
		// alert('Povolená je iba numerická hodnota, bez medzier ci ciarok.');
		new_val = parseInt(t.value.replace(/\s/g, ''));
		t.value = isNaN(new_val) ? '' : new_val;	
	} else {
		t.value = t.value * 1;
	}
}

