/*-------------------------------------------------------------------
							Config
-------------------------------------------------------------------*/

X_ROOT_URL = "http://schtv.ru";
X_SITE_PATH = "/";
X_PLAYER_PATH = X_ROOT_URL+X_SITE_PATH+"player/";
X_NEWS_ID_POSTFIX = "_news_id";

/*-------------------------------------------------------------------
						channelSwitcher
-------------------------------------------------------------------*/

//Каждой ссылке назначает обработчик
function set_links(links)
{
	links.each(function(one_link){
		one_link.addEvent('click', change_news);
		one_link.setProperty('href', 'javascript:void(0);');
	});
};

function change_news()
{	
	var id = this.getProperty('id').toInt();
	load_main(id);
};

//Меняет главную  новость
function load_main(id)
{	
	if (id_main_news != id)
	{
		id_main_news = id;
		channelSwitcher(id);
		create_player(id_main_news, id_player_cont, id_player);
	}
};
function embedFunc(id) {
		var embedCode = "Код для размещения: <br /><input name='embed_code' width='100%' id='embedInput' type='text' value=\"<embed src='http://schtv.ru/player/mediaplayer.swf' width='380' height='305' type='application/x-shockwave-flash' quality=high pluginspage='http://www.macromedia.com/go/getflashplayer' allowscriptaccess='always' allowfullscreen='true' flashvars='width=380&height=305&file=http://schtv.ru/player/playlist.php?id="+id+"&recommendations=http://schtv.ru/player/recommendations.php?id="+id+"&lightcolor=0x345829&logo=http://schtv.ru/player/sch.png' />\" class='vidURLField' onClick='javascript:this.focus();this.select();' readonly='true' style='width:400px' /><br /><br />";
		embedCode += "Код для ЖЖ: <br /><input name='embed_code' width='100%' id='embedLJ' type='text' value=\"<lj-embed><embed src='http://schtv.ru/player/mediaplayer.swf' width='380' height='305' type='application/x-shockwave-flash' quality=high pluginspage='http://www.macromedia.com/go/getflashplayer' allowscriptaccess='always' allowfullscreen='true' flashvars='width=380&height=305&file=http://schtv.ru/player/playlist.php?id="+id+"&recommendations=http://schtv.ru/player/recommendations.php?id="+id+"&lightcolor=0x345829&logo=http://schtv.ru/player/sch.png' /></lj-embed>\" class='vidURLField' onClick='javascript:this.focus();this.select();' readonly='true' style='width:400px' /><br /><br />";
		embedCode += "Код для блога LiveInternet	<br /><input name='embed_code' width='100%' id='embedLJ' type='text' value=\"[flash=380,305,http://schtv.ru/player/mediaplayer.swf?width=380&height=305&file=http://schtv.ru/player/playlist.php?id="+id+"&recommendations=http://schtv.ru/player/recommendations.php?id="+id+"&lightcolor=0x345829&logo=http://schtv.ru/player/sch.png]\" class='vidURLField' onClick='javascript:this.focus();this.select();' readonly='true' style='width:400px' />";			
		return embedCode;
	}
//Меняет окружение новости
function channelSwitcher(id)
{
	//$$("a.smoothbox").each(function(link){link.removeEvents();});
	$('header').setHTML(mainArray[id].footer);
	$('footer').setHTML(mainArray[id].header);
	//$('ms_num').setHTML(mainArray[id].number);
	
	//$('embedCode').setHTML(embedFunc(id));
	//TB_init();
};

function emb(id)
{
	$('embedCode').setHTML(embedFunc(id));
	TB_init();
}

/*-------------------------------------------------------------------
							Player API
-------------------------------------------------------------------*/

//Фун-я создает стандартный плеер
function create_player(id_content, id_container, id_player, screen)
{
	var rnd = Math.round(Math.random() * 1000000000);
	var so = new SWFObject(X_PLAYER_PATH+'mediaplayer.swf', id_player,'380','305','8');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','true');
	so.addParam('wmode','opaque');
	//so.addParam('bufferlengtht','2');
	//so.addParam('streamscript','lighttpd');
	so.addVariable('wmode','opaque');
	so.addVariable('width','380');
	so.addVariable('height','305');
	so.addVariable('file',X_PLAYER_PATH+'playlist.php?id='+id_content+'&rnd='+rnd);
	//so.addVariable('autostart','true');
	//so.addVariable('streamscript','lighttpd');
	so.addVariable('recommendations',X_PLAYER_PATH+'recommendations.php?id='+id_content);
	so.addVariable('lightcolor', '0x345829');
	so.addVariable('id', id_content);
	so.addVariable('javascriptid', id_player);
	so.addVariable('enablejs','true');
	so.addVariable('base_url', X_ROOT_URL+X_SITE_PATH);
	so.addVariable('screenshot', screen);
	so.addVariable('playerLocation', 'schtv');
	if (!so.write(id_container)) $(id_container).setHTML("<div style='height: 300px; width: 330px; font-size: 13px;'>У вас не установлен Flash плеер, либо установлена его старая версия. Для того, чтобы вы могли смотреть новости на ЩТВ, установите, пожалуйста, последнюю версию Flash плеера с официального сайта Adobe.<br /><br />Установить flash плеер вы можете <a href='http://adobe.com/go/getflashplayer'>http://www.adobe.com/products/flashplayer/</a></div>");
}

function loadFile(swf,obj) {
	thisMovie(swf).loadFile(obj); 
};

function thisMovie(movieName) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};

/*-------------------------------------------------------------------
							Uploader API
-------------------------------------------------------------------*/

/**
	Класс для переключения типа файлов
*/
var changeType = new Class({

	options: {
		changes: {
		0: {
			filelimit: 1,
			types: {'Films (*.avi, *.wmv, *.3gp, *.mp4, *.mov, *.flv, *.asf, *.mpg, *.mpeg)': '*.avi; *.wmv; *.3gp; *.mp4; *.mov; *.flv; *.asf; *.mpg; *.mpeg'}
			},
			
		1: {
			filelimit: 1,
			types: {'Music (*.mp3, *.wav, *.wma, *.amr, *.aac, *.ogg, *.mid, *.midi)': '*.mp3; *.wav; *.wma; *.amr; *.aac; *.ogg; *.mid; *.midi'}
			},
			
		2: {
			filelimit: 10,
			types: {'Images (*.jpg, *.gif, *.png)': '*.jpg; *.gif; *.png'}
			}
		}
	},

    initialize: function(elem, uploader){
        this.radioArr = elem;
        this.uploader = uploader;
		var ref = this;
		this.radioArr.each(function(item){
			item.addEvent('change', ref.changeSelected.bind(ref, item));
		});
	},

	changeSelected: function(item) {
		this.uploader.clearList(1);
		this.uploader.changeLimitFiles(this.options.changes[item.value].filelimit);
		this.uploader.changeType(this.options.changes[item.value].types);
	}
});

/**
	Класс для вывода ошибок 
*/
var ErrorHandler = new Class({

    initialize: function(elem){
        this.errorCont = $(elem);
    },
	
	getError: function(type, prm) {
		switch(type) {
		case 'limitFiles':
			this.showError('Нельзя загрузить больше '+prm+' файла(ов) одновременно');
			break;	
		case 'limitSize':
			this.showError('Нельзя загружать файлы размером более '+prm+' мегабайт');
			break;
		case 'duplicateFile':
			this.showError('Файл '+prm+' уже содержится в списке');
			break;
		case 'limitAllSize':
			this.showError('Общий размер файлов не должен превышать '+prm+' мегабайт');
			break;	
		case 'transferFiled':
			this.showError('Произошла ошибка при передаче файла '+prm+' . Вы можете начать загрузку заного');
			break;	
		case 'filesNotFound':
			this.showError('Файлы не выбраны');
			break;
		case 'hideCont':
			this.hideError();
			break;
		}
	},
	
	showError: function(msg) {
		this.errorCont.setStyle('display', 'block');
		this.errorCont.effect('opacity', {duration: 0}).start(0, 1);
		this.errorCont.setText(msg);
	},
	
	hideError: function() {
		this.errorCont.setStyle('display', 'none');
		this.errorCont.effect('opacity', {duration: 0}).start(1, 0);
		this.errorCont.empty();
	}
	
});

/*-------------------------------------------------------------------
							FormChecker
-------------------------------------------------------------------*/

/**
	Класс для проверки полей формы
*/
var formChecker = new Class({

	/**
		Опции
	*/
	options: {
		/**
			Флаг, показывает соответствует ли содержание полей формы регулярным выражениям
		*/
		validate: true,
		/**
			Ид кнопки отправки формы
		*/
		submitBtn: false,
		/**
			Массив регулярных выражений, применяемых к элементам формы
				name - имя поля к которому должно применяться это выражение
				NOTE: name = 'general' - выражения, которые применяються ко всем полям
				type - способ применеия выражения. Допустимые значения: test, replace
				exp - регулярное выражение
				replaceTxt - необязательный параметр, обозначает на какой текст производится замена
		*/
		regulars: [],
		onSuccess: false
	},

	/**
		Конструктор
	*/
    initialize: function(formId, options){
		this.setOptions(options);
		/**Запоминаем ссылку на форму */
        this.form = $(formId);
		/**Запоминаем елементы формы*/
		this.formElms = [];
		if (this.options.submitBtn != false) 
		{
			$(this.options.submitBtn).removeEvents();
			$(this.options.submitBtn).addEvent('click', this.checkForm.bind(this));
		}
		this.form.getFormElements().each(function(item, index){
				/** Если в форме есть кнопка отправки - назначаем на нее функцию checkForm */
				if (item.type == 'submit')
				{
					item.setProperty('type', 'button');
					if (this.options.submitBtn == false)
					{
						item.addEvent('click', this.checkForm.bind(this));
					}
				}
				if (['text', 'textarea', 'password', 'select-one'].contains(item.type)) 
				{
					this.formElms.push(item);
				};
		}, this);
		/** К каждому полю формы добавляем поле вывода ошибки */
		/**this.formElms.each(function(field){
			new Element('div', {
			'styles': {
				'display': 'block',
				'color' : 'red',
				'font-size' : '10px'
				},
			'class': 'errorLabel'
			}).injectAfter(field);
		}, this);*/
	},

	/**
		Проверка всех полей формы
		В цикле проходим регулярные выражения.  По каждому выражению проверяем массив полей.
		NOTE: В следующей версии будет добавлена возможность замены по регулярным выражениям и порядок их применнеия к полям. С этой целью и была создана эта функция.
	*/
	checkForm: function() {
		this.errors = false;
		this.options.validate = true;
		this.formElms.each(function(field){
			this.clearErrorCont(field);
		}, this);
	
		this.options.regulars.each(function(regExp){
			this.formElms.each(function(field){
				this.checkField(regExp, field);			
			}, this, regExp);
		}, this);
		if (this.options.validate == true)
		{
			this.formSubmit();
		}
		this.errors ? alert(this.errors) : null;
	},

	/**
		Проверка одного поля
	*/
	checkField: function(regExp, field) {
		if ((regExp.name.contains(field.name) || regExp.name.contains('!general','!select')) && !regExp.name.contains('!'+field.name)) 
		{    
			switch(regExp.type)
			{
				case 'test': 
					if (!regExp.exp.test(field.value))
					{
						/** Произошла ошибка */
						this.options.validate = false;
						this.showError(field, regExp.errorText);
					}
					break;
				/**case 'replace': 
					field.value = field.value.replace(regular.exp, regular.replacingTxt);
					break;*/
				default:
					break;
			}
		}
	},
	
	formSubmit: function() {
		if (!this.options.onSuccess)
		{
			this.form.submit();
		}
		else
		{
			this.fireEvent('onSuccess');
		}
	},
	
	/**
		Отображает ошибку в контейнере определеного поля
	*/
	showError: function(field, txt) {
		/**var errCont = field.getNext();
		var errTxt = errCont.getText();
		if 	(errTxt)
		{
			errCont.setHTML(errTxt + '<BR>' + txt);
		}
		else
		{
			errCont.setHTML(txt);
		}*/
		if (this.errors)
		{
			this.errors = this.errors+field.id+': '+txt+'\n';
		}
		else
		{
			this.errors = field.id+': '+txt+'\n';
		}
	},
	
	clearErrorCont: function(field) {
		/**var errCont = field.getNext();
		errCont.empty();*/
	}
		
});

formChecker.implement(new Events, new Options);

/*-------------------------------------------------------------------
							Прочее
-------------------------------------------------------------------*/

//Раскрывает поля для коментариев
function vis(me){
	ne = document.getElementById(me);
	if (ne.style.display=="none")
	{
		ne.style.display="inline";
	}
}

/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

//Проверяет длину введеного в поле текста
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute('maxlength')) : ''
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}