var responseText = '';

function show_AjaxLoader(obj) {
	//вычислим высоты для блоков
	var tw,th,th2;	
	$('#'+obj).width()<100 ? tw=768 :  tw=$('#'+obj).width();
	$('#'+obj).height()<100 ? th=416 :  th=$('#'+obj).height();
	$('#'+obj).height()<100 ? th2=416 :  th2=$('#'+obj).innerHeight();	
	//создаем фон и крутилку
	var ajBg= $('<div id="ajBg"></div>');
	var ajL= $('<div id="ajL"></div>');		
	$('#'+obj).css({
		'width' : tw+'px',
		'height': th+'px'
	});	
	$(ajBg).css({
		'position' : 'absolute',
		'right' : '0px',
		'top' : '0px',
		'width' : tw+'px',
		'height': th2+'px',
		'background' : '#fff',
		'opacity' : '0'
	});		
	$(ajL).css({
		'position' : 'absolute',
		'right' : '0px',
		'top' : '0px',
		'width' : tw+'px',
		'height': th2+'px',
		'background' : 'transparent url(/images/icons/al-big.gif) no-repeat center center'
		
	});		
	//добавляем объекты в ДОМ
	ajBg.appendTo($('#'+obj));
	ajL.appendTo($('#'+obj));	
	//анимация
	$(ajBg).animate({opacity:0.8},'fast');
}

function hide_AjaxLoader(obj) {
	//убираем стили с основного контейнера и убиваем фон и картинку
	$('#'+obj).css({
		'width' : 'auto',
		'height': 'auto'
	});	
	$('#ajBg').remove();
	$('#ajL').remove();	
}

function ajaxSend(url,data,listener) {
    var agent = null;
    var method = (data ? data : null) ? 'POST' : 'GET';
    try{agent=new XMLHttpRequest();}catch(e){try{agent=new ActiveXObject('Msxml2.XMLHTTP.3.0');}catch(e){try{agent=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){try{agent=new ActiveXObject('Microsoft.XMLHTTP');}catch(e){alert('AJAX MESSAGE: initialization error')}}}}
    agent.open(method, url, true);
    agent.setRequestHeader('Connection', 'close');
    agent.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    agent.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
    agent.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    agent.onreadystatechange = function() {
        if(agent.readyState==4) {
            if(agent.status==200) {
                responseText = agent.responseText;
                listener(agent.responseText)
            }
            else {
                alert('AJAX MESSAGE: '+agent.status+' '+agent.statusText)
            }
        }
    }
    agent.send(data);
    return false;
}

/**
* Функция для Ajax форм - возвращает POST/GЕТ строку... name1=value1&name2=value2...
* frm - объект формы
* Вариант использования:
* <form onsubmit="return ajaxSend(<ссылка на скрипт обработчик>, getFormData(this), <функция обработчик>)"
*/
function getFormData(frm) {
	var data = new Array();
	for(var i=0; i<frm.length; i++) {
		if(!frm[i].name) continue;
		if ((frm[i].type=='radio' || frm[i].type=='checkbox')) {
			if(!frm[i].checked) continue;
			if(!frm[i].value) frm[i].value = 'on';
		}
		if ((frm[i].type=='select-multiple')) {
			for(var j;j<frm[i].options.length;j++) {
				if(frm[i].options[j].selected) {
					data.push(frm[i].name+'='+frm[i].options[j].value);
				}
			}
		} else {
			data.push(frm[i].name+'='+frm[i].value);
		}
	}
	return data.join('&');
}

/**
* Класс AjaxHistory для навигации по якорям <URL>#hash
* Инициалируем в после элемента в с динамическим содержимым:
* <div id="элемент_с_динамическим_содержимым"></div>
* <script>
* var ajaxHistory = new AjaxHistory('<ссылка_на_пхп_обработчик>',<js_функция_обработчик_результата>);
* </script>
*/
var AjaxHistory = function(_url, _listener, def_vars) {
	var inited = false;
	var frame = null;
	var lastHash = '';
	var cur_vars = {};

	var init = function() {
		if(location.hash=='') setDefaultVars(); else makeVars();
		processHash();
		if(/msie [^8]/i.test(navigator.userAgent.toLowerCase())) {
		    frame = document.createElement('iframe');
		    frame.style.position = 'absolute';
		    frame.style.visibility  = 'hidden';
		    frame.style.width = '0px';
		    frame.style.height = '0px';
		    frame.id= 'testtest';
			frame.onreadystatechange = function() {
				if(inited) {
					location.hash = getFrameHash();
					processHash();
				}
			}
		    document.body.appendChild(frame);
			setFrameHash();
		} else {
			setInterval(processHash,100);
		}
		inited = true;
	}
	var setDefaultVars = function() {
		cur_vars = {};
		for(var i in def_vars) cur_vars[i]=def_vars[i];
	}
	var getFrameHash = function() {
		try{
			return decodeURIComponent(frame.contentWindow.document.getElementById('hash').innerHTML);
		} catch(e) {
			return '';
		}
	}
	var setFrameHash = function() {
		frame.contentWindow.document.open();
		frame.contentWindow.document.write('<div id="hash">'+encodeURIComponent(location.hash)+'</div>');
		frame.contentWindow.document.close();
	}
	var processHash = function() {
		if(lastHash==location.hash.replace('#','')) return;
		lastHash = location.hash.replace('#','');
		if(lastHash=='') setDefaultVars();
		ajaxSend(_url,'hash='+encodeURIComponent(lastHash),_listener);
	}
	var makeVars = function() {
		var _var;
		var hash = location.hash.split('/');
		for(var i in def_vars) {
			_var = hash.shift();
			cur_vars[i] = _var ? _var : def_vars[i];
		}
	}
	var makeHash = function() {
		var hash = [];
		for(var i in cur_vars) {
			hash.push(cur_vars[i]);
		}
		return hash.join('/');
	}
	this.get = function(key) {
		return cur_vars[key];
	}
	this.set = function(key,val) {
    	if(typeof(def_vars[key])!='undefined') {
    		cur_vars[key] = val;
    		return true;
    	} else {
    		alert('Ключ '+key+' не указан при инициализации AjaxHistory');
    		return false;
    	}
	}
    this.go = function(key,val) {
    	if(this.set(key,val)) {
			location.hash = makeHash();
			if(frame) setFrameHash();
    	}
    	return false;
	}
	this.refresh = function() {
		lastHash = 'Refreshing_Ajax_Content_At_'+(new Date().getTime());
	}
	init();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
*   Устанавливаем главную страницу
*/
function setMainPage(sid, cid){
    ajaxSend('setMainPage/?',
    	'sectionid='+sid+'&cid='+cid,
    	function(text){
    		if(text=='ERR')
    			alert('Не удалость установить главную страницу');
    	}
    );
}

function setThumbVideo(sid,tid,vid){
    ajaxSend('?',
        'b=setThumbVideo&videoid='+vid+'&thumbid='+tid,
        function(responseText){
            document.getElementById('thumb').innerHTML=responseText;
        }
    );
}

function gid(obj){return document.getElementById(obj);}

/*
var channelid = 0;
var cChannel = function(){
    this.section_id = 0;
    this.path = '/private_channels/';
    this.action = '';
    this.searchQuery = '';
    this.contentBlock = 'contentintetv';
    this.page = 0;
    this.orderBy = 'date';
    this.timeRange = 'year';
    this.inner = 0;
    this.year = 2010;

    this.setYear = function(act){this.year=act;}
    this.setAction = function(act){this.action=act;}
    this.setSectionId = function(id){this.section_id=id;}
    this.setContentBlock = function(cb){this.contentBlock=cb;}
    this.getContentBlock = function(){return this.contentBlock;}
    this.setInner = function(){this.inner = !this.inner;}
    this.setPath = function(ph){this.path = ph;}
    this.setPage = function(pg){this.page = pg;}
    this.setOrderBy = function(by){this.orderBy = by;}
    this.setTimeRange = function(tr){this.timeRange = tr;}
    this.setSearchQuery = function(sq){this.action='search'; this.searchQuery = sq;}

    // загружаем канал
    this.load = function(item_id){
        channelid = item_id;

        ajaxSend(
            this.path,
                'section_id=' + this.section_id + '&item_id=' + item_id + '&page=' + this.page + '&orderby=' + this.orderBy + '&timerange=' + this.timeRange + '&inner=' + this.inner + '&a=' + this.action + '&year=' + this.year + '&q=' + encodeURIComponent(this.searchQuery),
            writeAnswer
        );
    }

    function writeAnswer(text){
        if(!text) alert('Error show page');
            gid(channel.getContentBlock()).innerHTML = text;
    }
}
var channel = new cChannel();
*/


///////////////////////////////////// WATCH SECTION /////////////////////////////////////

    var vote=0;
    var rate_off = false;
    var force = false
    var new_rate = 0;
    var new_votes = 0;

    function show_rate(rate, itemid, stopit) {
    		for(i=1;i<=5;i++) {
    			var obj = document.getElementById('rate'+i+'_'+itemid);
    			obj.src = '/images/icons/v' + i + (i<=rate ? '' : 'gray') + '.png';

    			if(stopit)
		   			obj.onmouseover = obj.onmouseout = obj.onclick =
   					document.getElementById('rate_block').onmouseout = null;
    		}
    }

    function rate(itemid, rate, sid) {
    	ajaxSend('/rate/','item_id=' + itemid + '&rate=' + rate + '&sid=' + sid,
			function(text) {
				eval(text);
				show_rate(new_rate, itemid, 1);
            }
		);
    }
    function rateC(itemid, rate, sid, contestid) {
    	ajaxSend('/rate/','item_id=' + itemid + '&rate=' + rate + '&sid=' + sid+'&contestid='+contestid,
			function(text) {
				eval(text);
				show_rate(new_rate, itemid, 1);
            }
		);
    }

/////////////////////////// end rate ///////////////////////////////////

//////////////////////////// WIDGET TABS///////////////////////
	function widget_switch_tabs(broadcastid){
		ajaxSend('/tv/','broadcastid='+broadcastid,
			function(responseText) {
				gid('air-tv-slider').innerHTML=responseText;
				var slider = new CorbinaSlider('air-tv-slider','left-arrow','right-arrow');
            }
		);
	}
	function widget_channels_switch_tabs(broadcastid){
		ajaxSend('?','broadcastid='+broadcastid+'&channels=1',
			function(responseText) {
				gid('widget_channels_content').innerHTML=responseText;
            }
		);
	}
/////////////////////////////////// REGISTRATION////////////////////////////////////
	function local_login_form_check(obj,met){
		if(met=='login') {
			var p_sender = gid('login').value.toString();
			if(p_sender != "") {
				if(p_sender.length<3 || p_sender.length>50) {
					gid('loginerr').innerHTML='Укажите Логин(3-50 символов)!';
					gid('loginerr').style.display='block';
					return false;
				}
			} else {
				gid('loginerr').innerHTML='Необходимо заполнить поле Логин!';
				gid('loginerr').style.display='block';
				return false;
			}
			gid('loginerr').innerHTML='';
		}
		else if(met=='pass'){

		}
	}

//	function login_form_check(){
//	//LOGIN
//		var p_login = gid('login').value.toString();
//		if(p_login != "") {
//			if(p_login.length<3 || p_login.length>50) {
//				gid('loginerr').innerHTML='Укажите Логин(3-50 символов)!';
//				return false;
//			}
//		} else {
//			gid('loginerr').innerHTML='Необходимо заполнить поле Логин!';
//			return false;
//		}
//		gid('loginerr').innerHTML='';
//	//PASS
//		var p_pass = gid('pass').value.toString();
//		if (gid('pass').value.toString().length <= 10) {
//			gid('passerr').innerHTML='Укажите пароль!';
//			gid('passerr').style.display='block';
//			gid('pass').focus();
//			return false;
//		}
//		gid('passerr').innerHTML='';
//	}

	//login
	function login_check(){
		var login = gid('login').value.toString();
		ajaxSend('/registration/login/?',
		        'login='+login,
		        function(responseText){
		        	eval('var result='+responseText);
		        	if(result.status==200){
		        		gid('loginerr').innerHTML=result.text;
		        		gid('loginerr').style.display='block';
		        		pass_check();
		        	}else if(result.status==400){
		        		gid('loginerr').innerHTML=result.text;
		        		gid('loginerr').style.display='block';
		        		pass_check();
		        	}
		        }
		);

	}

	function pass_check(){
		var login = gid('login').value.toString();
		var pass = gid('pass').value.toString();
		var remember = gid('remember').checked;
		ajaxSend('/registration/login/?',
		        'login='+login+'&pass='+pass+'&remember='+remember,
		        function(responseText){
		        	eval('var result='+responseText+';');
		        	if(result.status==400){
		            	gid('passerr').innerHTML=result.text;
		            	gid('passerr').style.display='block';
		            	gid('pass').value='';
		        	}else if(result.status==300){
		        		gid('passerr').innerHTML=result.text;
		        		gid('passerr').style.display='block';
		            	load_activation_form('center','center',login,pass);
		        	}else if(result.status==200){
		        		close_tooltip2('login_form',1);
		        		if(location.search.substr(1,4)=='code'){
		        			location.href='http://'+document.location.hostname;
		        		}else{
		        			location.href=document.location.href;
		        		}
		        	}
		        }
		);
	}

	//end login
	//registration

	function setDays(seln,link){

	    var day = gid("day").value;
	    var month = gid("month").value;
	    var year = gid("year").value;

	    var p = new Date(year, month-1, 32).getDate();

	    var dayCount = 32 - p;
	    
		if(dayCount<=(day)){
			day=dayCount;
		}
		var t='';
	    ajaxSend(link+'?',
		        'day='+day+'&days='+dayCount,
		        function(responseText){
		        	t='<select name="day" id="day">'+responseText+'</select>';
		        	$("#cuselFrame-day").replaceWith(t);
		        	var params = {
				        changedEl: "#day",
				        visRows: 12,
				        scrollArrows: true
				    }
				    cuSel(params);
		        }
		);
	}

	function reg_check(){
		var name = gid('name').value.toString();
		var surname = gid('surname').value.toString();
		var country = gid('country').value.toString();
		var city = gid('city').value.toString();
		var day = gid('day').value.toString();
		var month = gid('month').value.toString();
		var year = gid('year').value.toString();
		
		var reg_login = gid('reg_login').value.toString();
		
		var pass1 = gid('pass1').value.toString();
		var pass2 = gid('pass2').value.toString();
		var email = gid('email').value.toString();
		var ivalid = gid('ivalid').value.toString();
		var agreement = gid('agreement').checked;
		var subscribe = gid('subscribe').checked;
		var reg_form = gid('reg_form');

		var sex=null;
		for (i=0;i<document.forms['reg_form'].sex.length;i++) {
			if(document.forms['reg_form'].sex[i].checked)
			sex=document.forms['reg_form'].sex[i].value.toString();
		}
		
		gid('reg_submit').onblur='';

		ajaxSend('/registration/registration/?',
		        'name='+name+'&surname='+surname+'&country='+country+'&city='+city+'&day='+day+'&month='+month+'&year='+year+'&sex='+sex+'&reg_login='+reg_login+'&pass1='+pass1+'&pass2='+pass2+'&email='+email+'&ivalid='+ivalid+'&subscribe='+subscribe+'&agreement='+agreement,
		        function(responseText){
		        	var arr = responseText.split("spacer");
		        	for(var i = 0; i < arr.length; i++){
		        	///невероятный хак, избавляющий от пустых элементов массива
		        		if(arr[i]!=''){
			        		eval('var result='+arr[i]);
		        		}
		        		if(result.status==400){
		       				for (var y = 0; y < reg_form.elements.length; y++) {
	        					el = reg_form.elements[y];
	        					if(el.name==result.field){
				       				gid(result.field+'_err').innerHTML=result.text;
				       				gid(result.field+'_err').style.display='block';
	        					}
		       				}
		       			}else{
		       				show_user_tooltip(result.text,1,'activation-tooltip','activation-tooltip-content','simple-tooltip','center','center');
		       				form.all('actform');
		       				//gid('reg_form').innerHTML=result.text;		       				
//							close_tooltip2('login_form',1);
//			        		location.href=document.location.href;
						}
		       		}
		        }
		);
		return false;
	}


	function activation(code){
		if(!code){
			var code = gid('code').value.toString();
			var email = gid('email').value.toString();
			var act_login = gid('act_login').value.toString();
			var act_form = gid('act_form');

			ajaxSend('/registration/activate/?',
			        'act_login='+act_login+'&email='+email+'&code='+code,
			        function(responseText){
			        	act_form.innerHTML=responseText;
			        	form.all('actform');
			        }
			);
		}else{
			ajaxSend('/registration/activate/?',
			        'code='+code,
			        function(responseText){
			        	show_user_tooltip(responseText,1,'alert-tooltip','alert-tooltip-content','simple-tooltip','center','center');
			        }
			);
		}
	}

	function get_activation_code(email,act_login){
		ajaxSend('/registration/getactivate/?',
			 'act_login='+act_login+'&email='+email,
			 function(responseText){
			 	if(responseText=='ok'){
//			 		show_user_tooltip("Код активации отправлен на email: "+email,1,'act_alert-tooltip','act_alert-tooltip-content','','center','center');
			 		alert("Код активации отправлен на email: "+email);
			 	}else{
//			 		show_user_tooltip("Ваш аккаунт уже активирован!",1,'act_alert-tooltip','act_alert-tooltip-content','','center','center');
			 		alert("Ваш аккаунт уже активирован!");
			 	}
			 }
		);
	}

	function remind_pass(){
		var remind_form = gid('remind_form');
		var login = gid('login2').value.toString();
		ajaxSend('/registration/remind_pass/?',
			        'login='+login,
			        function(responseText){
			        	remind_form.innerHTML=responseText;
			        	form.all('remind_form');
			        }
			);
	}

//	       			имя
//	       				if(result.field='name_err'){
//	       					gid('name_err').innerHTML=result.text;
//	       				}else if(result.field='name_ok'){
//	       					gid('name_err').innerHTML=result.text;
//	       				}
//	       			фамилия
//	       				if(result.field='surname_err'){
//	       					gid('surname_err').innerHTML=result.text;
//	       				}else if(result.field='surname_ok'){
//	       					gid('surname_err').innerHTML=result.text;
//	       				}
//	       			страна
//	       				if(result.field='country_err'){
//	       					gid('country_err').innerHTML=result.text;
//	       				}else if(result.field='country_ok'){
//	       					gid('country_err').innerHTML=result.text;
//	       				}
//	       			город
//	       				if(result.field='city_err'){
//	       					gid('city_err').innerHTML=result.text;
//	       				}else if(result.field='city_ok'){
//	       					gid('city_err').innerHTML=result.text;
//	       				}
//	       			пол
//	       				if(result.field='sex_err'){
//	       					gid('sex_err').innerHTML=result.text;
//	       				}else if(result.field='sex_ok'){
//	       					gid('sex_err').innerHTML=result.text;
//	       				}
//	       			логин
//	       				if(result.field='login_err'){
//	       					gid('login_err').innerHTML=result.text;
//	       				}else if(result.field='login_ok'){
//	       					gid('login_err').innerHTML=result.text;
//	       				}
//	       			пароль
//	       				if(result.field='pass1_err'){
//	       					gid('pass1_err').innerHTML=result.text;
//	       				}else if(result.field='pass1_ok'){
//	       					gid('pass1_err').innerHTML=result.text;
//	       				}
//	       			подтверждение пароля
//	       				if(result.field='pass2_err'){
//	       					gid('pass2_err').innerHTML=result.text;
//	       				}else if(result.field='pass2_ok'){
//	       					gid('pass2_err').innerHTML=result.text;
//	       				}
//	       			email
//	       				if(result.field='email_err'){
//	       					gid('email_err').innerHTML=result.text;
//	       				}else if(result.field='email_ok'){
//	       					gid('email_err').innerHTML=result.text;
//	       				}
//	       			ivalid
//	       				if(result.field='ivalid_err'){
//	       					gid('ivalid_err').innerHTML=result.text;
//	       				}else if(result.field='ivalid_ok'){
//	       					gid('ivalid_err').innerHTML=result.text;
//	       				}
	//end registration
////////////END REGISTRATION//////////////

     function get_m(obj) {
        textarea = obj.parentNode.getElementsByTagName('textarea')[0];
        text=textarea.value;
        return text;
    }

    function loadContest(id, page){
    	if(!page) page = 1;    	
    	show_AjaxLoader('contentintetv');		
        ajaxSend('my_video','type=contests&contestid='+id+'&page='+page,function(text){
        	hide_AjaxLoader('contentintetv');
            gid('contentintetv').innerHTML = text;
        });
        loadContestInfo(id);
    }
    function loadContestInfo(id){
        ajaxSend('my_video','type=contests&a=info&contestid='+id,function(text){
           gid('comp-rules').innerHTML = text;
        });
        gid('comp-rules').style.display = 'block';
    }
    function hideContestInfo(){
        gid('comp-rules').style.display = 'none';
    }

