/* make a wrapper for json evaluation.. it's genericly faster than prototype's one */
if (!window.JSON) {
	if (navigator.userAgent.indexOf('Gecko/') + 1) {
		window.JSON = {
			parse: function(text) {
				return new Function('return ' + text)();
			}
		}
	} else {
		window.JSON = {
			parse: function(text) {
				return eval('(' + text + ')');
			}
		}
	}
}

var Theme = {
	set: function(theme, anchor) {
		var date = new Date(),
			themes = { empty: 0, red: 1, black: 2 };

		$('logo').src = $('public').href + 'images/site_images/logo' + themes[theme] + '.png';
		$('theme').href = $('public').href + 'css/' + theme + '.css';
		if ($('theme-ie')) {
			if ($('theme-ie').href.indexOf('.css') + 1) {
				$('theme-ie').href = $('public').href + 'css/fixes/static/' + theme + '.css';
			} else {
				$('theme-ie').href = $('root').href + 'public/css/fixes/' + theme + '.php';
			}
		}

		date.setTime(date.getTime() + 1209600000);
		document.cookie = 'theme=' + theme + '; expires=' + date.toGMTString() + '; path=/';

		$A(anchor.parentNode.parentNode.getElementsByTagName('a')).each(function(a) {
			a.className = a.className.replace(' active', '').replace('active ', '').replace('active', '');
		});
		anchor.className = anchor.className + ' active';

		if ($('flash_animation')) {
			$('flash_animation').setBackgroundTheme(themes[theme]);
		}
	}
}

var Weather = {
	tmpid: 0,
	setCity: function(select, hack) {
		var element = $('weather_city_' + select.value);
		if (element) {
			$$('#weather_container ul').each(function(ul) {
				ul.style.display = 'none';
			});
			element.style.display = 'block';
			$('weather_city').value = select.value;
			return;
		}

		new Ajax.Request($('root').href + 'public/weather.php', {
			method: 'post',
			parameters: {
				weather_city_id: select.value
			},
			onComplete: function(response) {
				$('weather_city').value = select.value;

				var data = JSON.parse(response.responseText);

				$$('#weather_container ul').each(function(ul) {
					ul.style.display = 'none';
				});

				var ul = Builder.node('ul', {id: 'weather_city_' + data['weather_city_id']});
				ul.style.left = '-' + (parseInt(data['offset']) * (hack || 95)) + 'px';

				var flash = '';

				for (var x = 0; x < data['weather_forecasts'].length; ++x) {
					++Weather.tmpid;
					ul.appendChild(
						Builder.node('li', {}, [
							Builder.node('dl', {}, [
								Builder.node('dt', {}, [
									Builder.node('strong', {}, data['weather_forecasts'][x]['day_of_week'])
								]),
								Builder.node('dd', {className: 'date'}, data['weather_forecasts'][x]['date']),
								Builder.node('dd', {className: 'flash', id: 'flash_' + Weather.tmpid}, ''),
								Builder.node('dd', {className: 'temp'}, data['weather_forecasts'][x]['temp_max']),
								Builder.node('dd', {}, data['weather_forecasts'][x]['weather_type'])
							])
						])
					);

					if (Prototype.Browser.IE) {
						flash += '$(\'flash_' + Weather.tmpid + '\').innerHTML = \'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="70" height="70"><param name="movie" value="' + $('public').href + 'files/weather_types/' + data['weather_forecasts'][x]['weather_type_id'] + '-1.swf" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" /></object>\';';
					} else {
						flash += '$(\'flash_' + Weather.tmpid + '\').innerHTML = \'<embed type="application/x-shockwave-flash" width="70" height="70" bgcolor="#ffffff" wmode="transparent" src="' + $('public').href + 'files/weather_types/' + data['weather_forecasts'][x]['weather_type_id'] + '-1.swf"></embed>\';';
					}
				}

				$('weather_container').appendChild(ul);

				setTimeout(flash, 1);
			}
		});
	},
	realScroll: function(obj) {
		if (obj.iterations > 0) {
			obj.iterations--;
			obj.element.style.left = (parseInt(obj.element.style.left) + obj.step) + 'px';
		} else {
			Weather.scrolling = false;
			clearInterval(obj.interval);
		}
	},
	scroll: function(offset, hack) {
		if (Weather.scrolling) {
			return;
		}

		var obj = {
			element: $('weather_city_' + $F('weather_city')),
			iterations: Math.round(Math.abs(offset) / (hack || 3)),
			step: offset > 0 ? -3 : 3
		};

		if (obj.step > 0) {
			if (parseInt(obj.element.style.left) >= 0) {
				return;
			}
		} else {
			var count = obj.element.getElementsByTagName('li').length - Math.abs(parseInt(parseInt(obj.element.style.left) / 95)) - (hack || 3);
			if (count <= 0) {
				return;
			}
		}

		Weather.scrolling = true;
		new Effect.Move(obj.element, {x: -offset, duration: .7, afterFinishInternal: function() { Weather.scrolling = false; }});
	}
}

var Poll = {
	takeVote: function(button) {
		var radio = $(button.form).select('[name="answer"]').findAll(function(radio) {
			return radio.checked;
		});

		if (radio && radio.length) {
			Poll.results(radio[0].value);
		} else {
			$('poll_error').show();
		}
	},
	results: function(vote, poll_id) {
		var blah = {};

		if (vote) {
			blah.vote = vote;
		}
		if (poll_id) {
			blah.poll_id = poll_id;
		}

		new Ajax.Request($('root').href + 'public/ajax/poll.php', {
			method: 'post',
			parameters: blah,
			onComplete: function(response) {
				$('inquiry').update(response.responseText);
				return;

				var data = JSON.parse(response.responseText);
				console.log(data);
				$A(data.answers).each(function(answer) {
					console.log(answer)
					$('answer_' + answer.id + '_container').update(answer.html);
				});
				$('poll_error').remove();
				$('poll_results').remove();
				$('poll_button').replace(
					Builder.node('div', {}, [
						Builder.node('span', {style: 'float: left;'}, [
							Builder.node('strong', {}, 'Общо '),
							Builder.node('span', {}, data.votes + ' гласа')
						]),
						Builder.node('span', {style: 'float: right; margin-right: 10px;'}, [
							Builder.node('a', {href: 'javascript:;', onclick: 'Poll.showPoll();'}, 'гласувай »')
						])
					])
				);
			}
		});
	},
	showPoll: function() {
		new Ajax.Request($('root').href + 'public/ajax/poll.php', {
			method: 'post',
			parameters: {
				action: 'show_poll'
			},
			onComplete: function(response) {
				$('inquiry').update(response.responseText);
			}
		});
	}
}

var FileBox = function(element) {
	if (!(element = $(element))) {
		return;
	}

	element.addClassName('file');
	element.setStyle({opacity: 0, zIndex: 2});
	if (navigator.userAgent.indexOf('Firefox') + 1) {
		element.setStyle({width: '185px'});
	}

	var container = Element.Methods.wrap(element, 'div', {className: 'file_input text_input'});
	container.appendChild(new Element('input', {type: 'text', readonly: true, className: 'text_box', id: element.id + '_text'}));

	element.onchange = element.onmouseout = function() {
		$(this.parentNode).select('input[type="text"]')[0].value = this.value;
	}
}

var TabSwitcher = {
	setActive: function(tab, element) {
		if (!(element = $(element))) {
			return;
		}

		var active = $(element.parentNode.parentNode).select('span.active')[0],
			activeTab = active.className.replace(/.*__/, '').split(' ')[0];

		active.parentNode.replaceChild(
			Builder.node('a', {href: 'javascript:;', className: '__' + activeTab, onclick: 'TabSwitcher.setActive(\'' + activeTab + '\', this);'}, [
				Builder.node('span', {}, active.innerHTML.stripTags())
			]),
			active
		);

		element.parentNode.replaceChild(
			Builder.node('span', {className: 'active ' + element.className}, [
				Builder.node('span', {}, element.innerHTML.stripTags())
			]),
			element
		);

		$(activeTab).setStyle({display: 'none'});
		$(tab).setStyle({display: 'block'});
	}
};

var Feedback = {
	'__construct'	: function(id){
		$(id).observe('submit', Feedback.validate);
	},

	'validate'		: function(eve){
		var form	= Event.element(eve);
		var failed	= false;

		if(!form.comment.value.strip()){
			form.comment.focus();
			alert('Не сте въвели запитване!');
			failed++;
		}

		if(!form.email.value.match(/^[0-9A-Za-z._-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})$/)){
			form.email.focus();
			alert('E-mail адресът е невалиден!');
			failed++;
		}

		if(!form.name.value.strip()){
			form.name.focus();
			alert('Не сте въвели име!');
			failed++;
		}

		if(failed){
			eve.stop();
		}
	}
}

var Reportage = {
	validate: function() {
		var tmp, element;
		if (!$F(element = $$('#reportage #author').first())) {
			alert('Не сте въвели име!');
			element.focus();
			return false;
		}
		if (!(tmp = $F(element = $$('#reportage #email').first()))) {
			alert('Не сте въвели e-mail адрес!');
			element.focus();
			return false;
		}
		if (!tmp.match(/^[0-9A-Za-z._-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})$/)) {
			alert('E-mail адресът е невалиден!');
			element.focus();
			return false;
		}
		if (!$F(element = $$('#reportage #title').first())) {
			alert('Не сте въвели тема на репортажа!');
			element.focus();
			return false;
		}
		if (!$F(element = $$('#reportage #file').first())) {
			alert('Не сте посочили файл!');
			element.focus();
			return false;
		}
		return true;
	}
}

var Zoom = {
	min: 0.8,
	max: 1.8,
	element: null,
	initialize: function(element) {
		if (Zoom.element = $(element || 'zoomable')) {
			if (!Zoom.element.style.fontSize) {
				Zoom.element.style.fontSize = '1.1em';
			}
		}
	},
	zoomIn: function() {
		if (Zoom.element) {
			var fontsize = parseFloat(Zoom.element.style.fontSize) + 0.1;
			if (fontsize > Zoom.max) {
				fontsize = Zoom.max;
			}
			Zoom.element.style.fontSize = fontsize + 'em';
		}
	},
	zoomOut: function() {
		if (Zoom.element) {
			var fontsize = parseFloat(Zoom.element.style.fontSize) - 0.1;
			if (fontsize < Zoom.min) {
				fontsize = Zoom.min;
			}
			Zoom.element.style.fontSize = fontsize + 'em';
		}
	}
}

var Send = {
	toFriend: function() {
		var element,
			size = Send.getPageSize(),
			offset = document.viewport.getScrollOffsets();

		if (!(element = $('send_to_friend'))) {
			element = new Element('div', {id: 'send_to_overlay'}).setStyle({
				width: size[0] + 'px',
				height: size[1] + 'px'
			});
			element.observe('click', function() {
				Send.hideForm();
			});
			document.body.appendChild(element);

			element = new Element('div', {id: 'send_to_friend'}).setStyle({
				display: 'none'
			});
			document.body.appendChild(element);

			new Ajax.Request($('root').href + 'public/send.html', {
				onComplete: function(response) {
					element.update(response.responseText);
					Send.showForm();
				}
			});
		}

		element.setStyle({
			top: (document.viewport.getScrollOffsets().top + (Prototype.Browser.IE || Prototype.Browser.WebKit ? document.documentElement.offsetHeight : document.body.scrollHeight) / 2 - 100) + 'px'
		});

		Send.showForm();
	},
	validate: function() {
		var element;

		if (!(element = $('send_name')).value) {
			alert('Не сте въвели Вашето име!');
			element.focus();
			return false;
		}

		if (!(element = $('send_from')).value) {
			alert('Не сте въвели Вашият e-mail!');
			element.focus();
			return false;
		}

		if (!element.value.match(/^[0-9A-Za-z._-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})$/)) {
			alert('E-mail адресът Ви е невалиден!');
			element.focus();
			return false;
		}

		if (!(element = $('send_email')).value) {
			alert('Не сте въвели e-mail на вашият приятел!');
			element.focus();
			return false;
		}

		if (!element.value.match(/^[0-9A-Za-z._-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})$/)) {
			alert('E-mail адреса на вашият приятел е невалиден!');
			element.focus();
			return false;
		}

		new Ajax.Request($('root').href + 'send_to_friend', {
			method: 'post',
			parameters: {
				name: $F('send_name'),
				from: $F('send_from'),
				email: $F('send_email'),
				url: location.href
			}
		});

		setTimeout(Send.hideForm, 1);
		return false;
	},
	getPageSize: function(){
		var xScroll, yScroll,
			wWidth, wHeight,
			pWidth, pHeight;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight) {
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else {
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		if (self.innerHeight) {
			if (document.documentElement.clientWidth) {
				wWidth = document.documentElement.clientWidth;
			} else {
				wWidth = self.innerWidth;
			}
			wHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			wWidth = document.documentElement.clientWidth;
			wHeight = document.documentElement.clientHeight;
		} else /*if (document.body)*/ {
			wWidth = document.body.clientWidth;
			wHeight = document.body.clientHeight;
		}

		/** for small pages we take the smaller width */
		if (xScroll < wWidth) {
			pWidth = xScroll;
		}
		else {
			pWidth = wWidth;
		}
		/** but the highest height */
		if (yScroll > wHeight) {
			pHeight = yScroll;
		}
		else {
			pHeight = wHeight;
		}

		return [pWidth, pHeight];
	},
	showForm: function() {
		new Effect.Appear('send_to_overlay', {
			to: .333,
			afterFinish: function() {
				new Effect.Appear('send_to_friend', {
					duration: .333
				});
			}
		})
	},
	hideForm: function() {
		new Effect.Fade('send_to_friend', {
			duration: .333,
			afterFinish: function() {
				new Effect.Fade('send_to_overlay', {
					duration: .333
				})
			}
		});
	}
}

Event.observe(window, 'load', function() {
	SelectBox('weather_day_select');
	SelectBox('weather_city_select');
	SelectBox('file_type_select');
	SelectBox('show_id_select');
	SelectBox('week1');
	SelectBox('week2');
	SelectBox('view1');
	SelectBox('view2');
	SelectBox('day');

	FileBox('file');

	Zoom.initialize();

	$$('.tools .mail a').each(function(element) {
		element.onclick = Send.toFriend;
	});

	if($('videos_calendar_button') && $('videos_calendar_value') && Calendar){
		Calendar.setup({
			triggerElement	: 'videos_calendar_button',
			dateField		: 'videos_calendar_value',
			showTime		: false,
			dateFormat		: '%Y-%m-%d'
		});

		$('videos_calendar_value').onchange = function(){
			var query		= self.location.search;
			var path		= self.location.pathname;
			var redirect	= path + '?published=' + this.value;

			if(query.length > 1){
				if(query.match(/(\?|&)(published=)(\d{4}-\d{2}-\d{2})(\&|$)/)){
					redirect = path + query.replace(/(\?|&)(published=)(\d{4}-\d{2}-\d{2})(\&|$)/, '$1$2' + this.value + '$4');
				}else{
					redirect = path + query + '&published=' + this.value;
				}
			}

			self.location.href = redirect;
		};
	}
});
