﻿function OpenNewWindow(url) {
	var width = 300;
	var height = 350;
	leftVal = (screen.width - width) / 2;
	topVal = (screen.height - height) / 2;
	var win = window.open(url, 'PSN','width=' +width + ',height=' + height+ ',left=' + leftVal + ',top=' + topVal + ', location=no, toolbar=no, directories=no, status=no, resizable=no, scrollbars=no, fullsize=no');
	win.focus();
}

//метод добавляет параметр в урл и открывает стр. в новом окне
function OpenNewWindowWithParam(url, key, cssClassName) {
	//проверка:
	var value = $('.' + cssClassName).val();
	OpenNewWindow(SetQueryParam(url, key, value));
}

//метод меняет значение параметра в url или добавляет если его нет
function SetQueryParam(url,key, value) {
	url = url == null ? window.location.search : url;
	var q = url + "&";
	//the replace
	var re = new RegExp("[?|&]" + key + "=.*?&");
	if (!re.test(q))
		q += key + "=" + encodeURI(value);
	else
		q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
	//Triming &
	q = q.replace(/^&/, '');
	q = q.replace(/&$/, '');
	return q.indexOf('?') > -1 ? q : "?" + q;
}

var individualInActionInterval;
function ShowPopup(popupId, popupOverlayCssClass,popupIntelliNameId) {

	//*** код интеллитрекера (должен передавать параметры pqry с уникальным параметром Popup) **/
	try {
		//если задан Popup имя => вызываем передаем Intelli интересующие их параметры
		if (popupIntelliNameId && popupIntelliNameId != '') {
			if (pqry == "iAddPAR" || pqry == "")
				pqry = "%26Popup=" + popupIntelliNameId;
			else
				pqry += "%26Popup=" + popupIntelliNameId;
			itrc();
		}
	}
	catch(err)
	{
		//alert('в методе ShowPopup возникла ошибка при отправки статистики в IntelliTracker');
	}	
	//******//

	
	if ($.browser.msie
		&& $.browser.version.substr(0, 3)=='6.0')	//when IE6
	{
		$('select').hide();
		$('#' + popupId + ' select').show();
	}



//	$.blockUI({
//		message: $('#' + popupId),
//		css: { top: '7%', left: '25%',border:'none',cursor:'default'}
//	});

	$('#' + popupId).show();

	/*ради поддержки IE6*/
	var width = $(document).width();
	var heightDoc = $(document).height();
	if ($.browser.opera) heightDoc = document.documentElement.clientHeight;
	/*IE6 не поддерживает width:100%;*/
	$('#' + popupId).width(width);
	$('.' + popupOverlayCssClass).width(width);
	/*IE6 не поддерживает position:fixed;*/
	$('.' + popupOverlayCssClass).height(heightDoc);
	individualInActionInterval=setInterval(
		function() {
			$('.class_el_main_div').hide();
		}, 1000); /*every 2 seconds*/
	
}

function HidePopup(popupId){
	if($.browser.msie 
		&& $.browser.version.substr(0, 3)=='6.0')
		$('select').show();
	$('#' + popupId).hide();
	clearInterval(individualInActionInterval);
}

function AnswerCheck(cBox, callId, questionId, spnId, persent) {
	var currPersent = parseInt($("#" + spnId).html());
	if (!cBox.checked)
		persent = -1 * persent;
	currPersent = currPersent - (-1 * persent);
	if (currPersent <= 0)
		currPersent = "0";
	$("#" + spnId).html(currPersent);


	$.ajax({
		type: "POST",
		url: "/site/WebServices/UserOffice.asmx/AnswerCheck",
		contentType: "application/json; charset=utf-8",
		data: '{ "callId": "' + callId + '", "questionId": "' + questionId + '", "isChecked": "' + cBox.checked+ '" }',
		dataType: "json",
		success: function() {},
		error: function() { }
	});
}

function SWFCallUploader() {
	$("#" + "fu").uploadify(
					{
						'uploader': '/images/uploadify.swf',
						'script': '/site/admin/cabinet/handlers/callupload.ashx',
						'buttonImg': '/images/importirovat.jpg',
						'fileDesc': 'Медиа файли(*.wav)',
						'fileExt': '*.wav',
						'scriptData': { ASPSESSID: sessionId, AUTHID: authId, UserId: userId, CurrUserId: currUserId, CallId :callId },
						'auto': true,
						'width': 120,
						'multi': false,
						'onComplete': function(event, queueID, fileObj, response, data) { ; $("#" + spnId).html(response); },
						'onProgress' : function(event, queueID, fileObj,data){  $("#" + spnId).html("загружено: " + data.percentage); } 
					});

				}
				function SWFWebinarUploader(fuId, spnId, hfOldValueId, uploaderContainerId) {
					$("#" + fuId).uploadify(
					{
						'uploader': '/images/uploadify.swf',
						'script': '/site/admin/learning/handlers/webinarupload.ashx',
						'buttonImg': '/images/importirovat.jpg',
						'fileDesc': 'Файли(.pdf;.txt;.doc;.docx;.xls;.xlsx;.ppt;.pptx;.avi;.flv;.wav;.mp3)',
						'fileExt': '*.pdf;*.txt;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx;*.avi;*.flv;*.wav;*.mp3',
						//'scriptData': { ASPSESSID: sessionId, AUTHID: authId, UserId: userId, CurrUserId: currUserId, CallId: callId },
						'scriptData': { CurrUserId: currUserId, SpnId: spnId, HfOldValueId: hfOldValueId, UploaderContainerId: uploaderContainerId },
						'auto': true,
						'width': 120,
						'multi': false,
						'queueID': "dvQueue",
						'onComplete': function(event, queueID, fileObj, response, data) {
							$("#" + spnId).html(response);
							$("#" + uploaderContainerId).hide();
						},
						'onProgress': function(event, queueID, fileObj, data) {
						},
						'onError': function() { alert('ошибки на сервере или в обращении'); }
					});

				}


function DeleteCall(userId, currId, path, callId) {
	if (confirm("Вы действительно хотите удалить файл?")) {
		$.ajax({
			type: "POST",
			url: "/site/WebServices/UserOffice.asmx/DeleteCall",
			contentType: "application/json; charset=utf-8",
			data: '{ "userId": "' + userId + '", "currId": "' + currId + '", "callId": "' + callId + '", "path": "' + path + '" }',
			dataType: "json",
			success: function() { $("#" + spnId).html("Прослушать"); },
			error: function() { }
		});
	}
}

//удаляет файл вебинара (как из временной (fake) папки так и из постоянной папки
//parameters={webinarId:'{0}', currUserId:'{1}', fakeFileName:'{2}', fileName:'{3}'}
function DeleteWebinar(parameters) {
	if (confirm("Вы действительно хотите удалить файл?")) {
		$.ajax({
			type: "POST",
			url: "/site/WebServices/Webinar.asmx/DeleteWebinar",
			contentType: "application/json; charset=utf-8",
			data: '{ "webinarId": "' + parameters.webinarId + '", "currUserId": "' + parameters.currUserId + '", "fakeFileName": "' + parameters.fakeFileName + '", "fileName": "' + parameters.fileName + '" }',
			dataType: "json",
			success: function() {
				$("#" + parameters.spnId).html("Скачать"); /*удаляем ссылку*/
				$("#" + parameters.hfOldValueId).val('');	/*очищаем старый файл (возможно его удалили)*/
				$("#" + parameters.uploaderContainerId).show(); /*показываем кнопку типорта*/
			},
			error: function() { }
		});
	}
}

function AddVoteToReview(tagA, imgActive, imgNotActive, spCount, commentId) {
    aValue = spCount;
    $.ajax({
        type: "POST",
        url: "/site/WebServices/Comment.asmx/AddVoteToReview",
        contentType: "application/json; charset=utf-8",
        data: '{ "commentId": "' + commentId + '"}',
        dataType: "json",
        success: onAddVoteToReview,
        error: function() {alert("Error") }
    });

    tagA.href = "javascript:void(0);";
    imgActive.style.display = "none";
    imgNotActive.style.display = "inline";
    imgNotActive.style.cursor = "default";
}

function onAddVoteToReview(data) {
    var value = eval(data.d);
    if (value.IsSuccess) {
        aValue.innerHTML = "голосов: "  + value.UpCount;
    } else {
        alert(value.Message);
    }
}

function RedirectAfter(url, spnId) {
    var sec = 10;
    var spn = document.getElementById(spnId);
    setInterval(function() {
        if (sec == 0) { window.location.href = url; }
        spn.innerHTML = (sec < 0) ? "0" : sec;
        sec = sec - 1;
    }, 1000);
}

