/*
 * Класс общего функционала
 *
 * Включает в себя ряд следующих функций: AJAX запросы; управление блоками и т.д.
 */
var start_time_reload_content = 0;
var MP = {
	preloadingimageajax : '/a_php/common/icon/ajax-loader.gif',	// Путь до изображения AJAX
	preloadingtext : 'Загрузка...',								// Текст, отображаемый во время AJAX запроса
	showpreloadingimage : true,									// Показывать изображение AJAX или нет
	datatypesend : 'html',										// Формат получаемых данных
	statusajaxquery: 0,											// Статус выполнения запроса. 1 - идет запрос; 0 - не идет
	checkstatusajaxquery: 1,									// Следует ли проверят статус AJAX запроса. Если проверять - можно будет выполнить только 1 запрос за раз
	resultData: false,											// Результат запроса метода LoadContent в формате json
	sync: false,												// Выполнять ли запрос синхронно - true или асинхронно - false


	// url - адрес отправки (ссылка, объект)
	// block - блок вывода полученного ajax-результата
	// param - параметры в виде GET-строки
	// datatype - html, json
	// complete_func - callback
	// +++ sync - false - синхронно, true-undefined - асинхронно (по-умолчанию)
	LoadContent : function(url,block,param,datatype,complete_func,sync) {
		// Не даем выполнять одновременно несколько запросов
		if(MP.checkstatusajaxquery==1 && MP.statusajaxquery==1) {
			return false;
		}
		if(!MP.preloadingtext) {
			MP.preloadingtext = 'Загрузка...';
		}
		MP.statusajaxquery = 1;
		if (typeof(url) == 'object') {
			url = url.href;
		}
		if(typeof(datatype)=='undefined' || datatype == '') {
			datatype = MP.datatypesend;
		}
		if(typeof(block) == 'undefined') {
			block = '';
		}
		if(typeof(complete_func) == 'undefined') {
			complete_func = '';
		}
		if (MP.showpreloadingimage === true) {
			message_preload = '<div style="text-align:center;font-weight:bold;"><img src="'+MP.preloadingimageajax+'" border="0" style="vertical-align:middle;" hspace="5">'+MP.preloadingtext+'</div>';
			jQuery("#"+block).html(message_preload);
		}
		if(typeof(param)!='undefined' && param.length > 0 && typeof(param)=='string') {
			param = MP.ParseQueryString(param);
		}
		data_param = '';
		if (typeof(param)=='object') {
			jQuery.each(param,function(key,val) {
				data_param += key + '=' + val + '&';
			});
			data_param = jQuery.trim(data_param.substring(0,data_param.length-1));
		}
		// Передавать данные синхронно или асинхронно
		sync = (typeof(sync)!='undefined' && sync==1)?false:true;
		// Если возвратить нужно json формате обнуляем внутреннюю переменную
		if(datatype == 'json') {
			MP.resultData = false;
		}
		method_send = data_param.length<1? 'GET' : 'POST';
		jQuery.ajax({
			type : method_send,
			timeout: 10000,
			dataType: datatype,
			url : url,
			data : data_param,
			complete : '',
			error : function(XMLHttpRequest) {
				if(datatype == 'json') {
					alert(XMLHttpRequest.status==200?'Ошибка формирования JSON формата':MP.SetErrorQuery(XMLHttpRequest));
					jQuery("#" + block).empty();
				}
				else {
					msg_error = MP.SetErrorQuery(XMLHttpRequest);
					msg_error = '<div style="text-align:center;font-weight:bold;color:red;">'+msg_error+'</div>';
					jQuery("#"+block).html(msg_error);
					msg_error = null;
				}
			},
			cache : false,
			async : sync,
			success : function(msg) {
				// Данные в html формате выводим напрямую
				// Json данные выводим через callback-функцию или сохраняем во внутреннюю переменную
				if (datatype=='html') {
				   if(block!='') jQuery("#" + block).html(msg);
				   else if(complete_func!='') {
					   setTimeout(function(){eval('complete_func(msg)')},100);
				   }
				}
				else {
					if (typeof(complete_func)=='undefined' || complete_func=='') {
						MP.resultData = msg;
					}
					else {
						eval('complete_func(msg)');
					}
					jQuery("#" + block).empty();
				}
				msg = null;
			}
		});
		MP.statusajaxquery = 0;
		return false;
	},

	// Функция определяет код ошибки и возвращает описание
	SetErrorQuery : function(XMLHttpRequest) {
		var array_error = new Array();
		array_error[200] = 'OK';
		array_error[201] = 'Created (объект создан)';
		array_error[202] = 'Accepted (информация принята)';
		array_error[203] = 'Non-Authoritative Information (не заслуживающая доверия информация)';
		array_error[204] = 'No Content (нет содержания)';
		array_error[205] = 'Reset Content (восстановить исходное содержание)';
		array_error[206] = 'Partial Content (частичное содержание)';
		array_error[300] = 'Multiple Choices (несколько вариантов на выбор)';
		array_error[301] = 'Moved Permanently (ресурс перемещен на постоянной основе)';
		array_error[302] = 'Moved Temporarily (ресурс временно перемещен)';
		array_error[303] = 'See Other (смотрите другой ресурс)';
		array_error[304] = 'Not Modified (не изменился)';
		array_error[305] = 'Use Proxy (используйте прокси-сервер)';
		array_error[400] = 'Bad Request (некорректный запрос)';
		array_error[401] = 'Unauthorized (нет разрешения)';
		array_error[402] = 'Payment Required (требуется оплата)';
		array_error[403] = 'Forbidden (доступ запрещен)';
		array_error[404] = 'Not Found (запрашиваемый документ не найден)';
		array_error[405] = 'Method Not Allowed (недопустимый метод)';
		array_error[406] = 'Not Acceptable (неприемлемый запрос)';
		array_error[407] = 'Proxy Authentication Required (необходима регистрация на сервере-представителе)';
		array_error[408] = 'Request Timeout (время обработки запроса истекло)';
		array_error[409] = 'Conflict (конфликт)';
		array_error[410] = 'Gone (ресурса больше нет)';
		array_error[411] = 'Length Required (необходимо указать длину)';
		array_error[412] = 'Precondition Failed (не выполнено предварительное условие)';
		array_error[413] = 'Request Entity Too Large (запрашиваемый элемент слишком велик)';
		array_error[414] = 'Request-URI Too Long (идентификатор ресурса в запросе слишком длинный)';
		array_error[415] = 'Unsupported Media Type (неподдерживаемый тип устройства)';
		array_error[500] = 'Internal Server Error (внутренняя ошибка сервера)';
		array_error[501] = 'Not Implemented (функция не реализована)';
		array_error[502] = 'Bad Gateway (дефект шлюза)';
		array_error[503] = 'Service Unavailable (служба недоступна)';
		array_error[504] = 'Gateway Timeout (время прохождения через шлюз истекло)';
		array_error[505] = 'HTTP Version Not Supported (неподдерживаемая версия HTTP)';
		msg_error = 'Ошибка ' + XMLHttpRequest.status + ' - ';
		if (typeof(array_error[XMLHttpRequest.status]) != 'undefined' && XMLHttpRequest.status != 200) {
			msg_error += array_error[XMLHttpRequest.status];
		} else {
			msg_error += XMLHttpRequest.statusText;
		}
		return msg_error;
	},

	ParseQueryString : function(str) // Функция парсит URL строку и возвращает ассоциативный массив
	{
		if(typeof(str)=='undefined' || str === '') {
			str = window.location.search;
			// Если получаем из URI, нужно декодировать
			encode = true;
		}
		else {
			// Если получаем не из URI, НЕ декодируем
			encode = false;
		}
		pos = str.indexOf('?');
		if (pos > -1) {
			str = str.substring(pos+1, str.length);
		}
		var glue1 = '=';
		var glue2 = '&';
		var array2 = str.split(glue2);
		var array3 = new Object();
		for(x = 0;x<array2.length;x++) {
			tmp = array2[x].split(glue1);
			array3[unescape(tmp[0])] = encode?unescape(tmp[1]).replace(/[+]/g, ' '):tmp[1];
		}
		if(typeof(array3['an'])=='undefined') {
			array3['an'] = 'index';
		}
		return array3;
	},

	QuerySrtringParam : function (variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
				if (pair[0] == variable) {
				   return pair[1];
				}
			}
		return null;
	},

	HideBlock : function (block,time,animation) {	// Функция прячет блок
		if(typeof(time)=='undefined') {time=0;}
		if(block.indexOf('.')==-1) {
			if(block.indexOf('#')==-1) {block = '#'+block;}
		}
		if(animation) {
			jQuery(block).animate({height: "hide",opacity: "hide"},time);
		}
		else {
			jQuery(block).hide(time);
		}
		return false;
	},
	ShowBlock : function (block,time,animation) {	// Функция показывает блок
		if(typeof(time)=='undefined') {time=0;}
		if(block.indexOf('.')==-1) {
			if(block.indexOf('#')==-1) {block = '#'+block;}
		}
		if(animation) {
			jQuery(block).animate({height: 'show',opacity: 'show'},time);
		}
		else {
			jQuery(block).show(time);
		}
		return false;
	},
	getCookie : function(name)	//Функция чтения значения cookie
	{
	   prefix = name + '=';
	   cookieStartIndex = document.cookie.indexOf(prefix);
	   if (cookieStartIndex == -1) {
		   return null;
	   }
	   cookieEndIndex = document.cookie.indexOf(';', cookieStartIndex + prefix.length);
	   if (cookieEndIndex == -1) {
		   cookieEndIndex = document.cookie.length;
	   }
	   return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
	},
	setCookie : function(name, value, time) {	// Установка  cookie. Значение time подается в днях
	      valueEscaped = escape(value);
	      expiresDate = new Date();
	      expiresDate.setTime(expiresDate.getTime() + time * 24 * 3600 * 1000);
	      expires = expiresDate.toGMTString();
	      newCookie = name + '=' + valueEscaped + '; path=/; expires=' + expires + ';';
	      if (valueEscaped.length <= 4000) {
	    	  document.cookie = newCookie;
	      }
	},
	AboutSystem : function()	// Определяем браузер и версию
	{
		var userAgent = navigator.userAgent.toLowerCase();
		jQuery.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
		var version = 0;
		if(jQuery.browser.msie){
			userAgent = jQuery.browser.version;
			userAgent = userAgent.substring(0,userAgent.indexOf('.'));
			version = userAgent;
			browser = 'MSIE';
		}
		if(jQuery.browser.chrome){
			browser = 'Chrome';
			tmp =  navigator.userAgent.split('Chrome/');
			tmp = tmp[1].split(' ');
			version = tmp[0];
			jQuery.browser.safari = false;	// Принудительно убиваем сафари, чтобы не перекликались
		}
		if(jQuery.browser.safari){
			userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);
			userAgent = userAgent.substring(0,userAgent.indexOf('.'));
			version = userAgent;
			browser = 'Safari';
		}
		if(jQuery.browser.mozilla){
			if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
				userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
				userAgent = userAgent.substring(0,userAgent.indexOf('.'));
				version = userAgent;
				browser = 'FireFox';
			}
		}
		if(jQuery.browser.opera){
			userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
			userAgent = userAgent.substring(0,userAgent.indexOf('.'));
			version = userAgent;
			browser = 'Opera';
		}
		// Определяем систему
		pos1 = navigator.userAgent.indexOf('(');
		pos2 = navigator.userAgent.indexOf(')',pos1+2);
		tmp = navigator.userAgent.substring(pos1+1,pos2);
		tmp = tmp.split(';');
		var array_system = new Array();
		array_system['Windows NT 5.0']='Windows 2000';array_system['Windows NT 5.01']='Windows 2000 Service Pack 1';
		array_system['Windows NT 5.1']='Windows XP'; array_system['Windows NT 5.2']='Windows Server 2003';
		array_system['Windows NT 5.2; WOW64']='Windows XP 64-bit';array_system['Windows NT 6.0']='Windows Vista';
		array_system['Windows NT 6.1']='Windows 7';array_system['Windows CE']='Windows Mobile';
		array_system['']='';array_system['']='';array_system['']='';array_system['']='';array_system['']='';array_system['']='';
		system = jQuery.trim(tmp[2]);
		if(typeof(array_system[system])!='undefined') {
			system = array_system[system];
		}
		language = jQuery.trim(tmp[3]);
		return {0:browser,1:version,2:system,3:language};
	},
	// Кроссбраузерная функция для получения размера документа.
	// Функция возвращает массив со значениями ширины и высоты страницы вместе с прокруткой (pageWidth, pageHeight)
	// и ширины и высоты видимой части страницы (windowWidth, windowHeight):
	getPageSize : function getPageSize()
	{
	   var xScroll, yScroll;
	   if (window.innerHeight && window.scrollMaxY) {
	      xScroll = document.body.scrollWidth;
	      yScroll = window.innerHeight + window.scrollMaxY;
	   }
	   else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	      xScroll = document.body.scrollWidth;
	      yScroll = document.body.scrollHeight;
	   }
	   else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
	      xScroll = document.documentElement.scrollWidth;
	      yScroll = document.documentElement.scrollHeight;
	   }
	   else { // Explorer Mac...would also work in Mozilla and Safari
	      xScroll = document.body.offsetWidth;
	      yScroll = document.body.offsetHeight;
	   }
	   var windowWidth, windowHeight;
	   if (self.innerHeight) { // all except Explorer
	      windowWidth = self.innerWidth;
	      windowHeight = self.innerHeight;
	   }
	   else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	      windowWidth = document.documentElement.clientWidth;
	      windowHeight = document.documentElement.clientHeight;
	   }
	   else if (document.body) { // other Explorers
	      windowWidth = document.body.clientWidth;
	      windowHeight = document.body.clientHeight;
	   }
	   if(yScroll < windowHeight){	// for small pages with total height less then height of the viewport
	      pageHeight = windowHeight;
	   }
	   else {
	      pageHeight = yScroll;
	   }
	   if(xScroll < windowWidth){	// for small pages with total width less then width of the viewport
	      pageWidth = windowWidth;
	   }
	   else {
	      pageWidth = xScroll;
	   }
	   return [pageWidth,pageHeight,windowWidth,windowHeight];
	},
	PaintDiv : function(block,color,type) {	// Функция меняет класс или заливку элемента
		list = jQuery(document).find(block);
		jQuery.each(list,function(key,val){
			if((key%2)) {
				if(type=='class') {
					jQuery(val).addClass(color);
				}
				else {
					jQuery(val).css('background',color);
				}
			}
		});
	},
	PaintTable : function(block,color,type) {	// Функция меняет заливку у строки таблицы
		if(type == 'class') {
			jQuery(block+' tr:nth-child(even)').addClass(color);
		}
		else {
			jQuery(block+' tr:nth-child(even)').css('background',color);
		}
	},
	SetCityProfile : function(block) {	// Функция запрашивает список городов для профайла пользователя
	   val = jQuery("select#country_ank").val();
	   if(val > 0){
	      url = '/a_php/sessauth/a_dmin/profile/list_town.php?country='+val;
	      MP.preloadingtext = 'Загружаем список городов...';
	      setTimeout(function(){MP.preloadingtext = ''},500);
	      return MP.LoadContent(url,block);
	   }
	   else {
	      mess = '<select id="city" name="city" class="select_city"><option value="0">Выберите страну</option></select>';
	      jQuery("#"+block).html(mess);
	      mess = null;
	   }
	   return false;
	},
	// Динамическое подключение файла
	IncludeFile : function (file) {
		var script  = document.createElement('script');
		script.src  = file;
		script.type = 'text/javascript';
		script.defer = true;
		document.getElementsByTagName('head').item(0).appendChild(script);
	},
	// +++ Вешаем на форму ajax обработчик, формируем строку параметров
	BindFormSubmit : function (options) {
		jQuery('#'+options.formID).bind('submit', function() {
			var queryString = jQuery('#'+options.formID).serialize();

			// Ставим признак "синхронного выполнения", чтобы MP.resultData отработал
			MP.LoadContent(jQuery('#'+options.formID).attr('action'),options.errorBlock,queryString,'json','',1);
			if (false!=MP.resultData) {
				if (MP.resultData.error==1) {
					alert(MP.resultData.text);
				}
				else {
					MP.LoadContent(options.reloadFuncPage,options.updateBlock);
				}
				MP.resultData = false;
			}
			return false;
		});
	},
	GetStringTo1251: function(str){
		return MP.CP1251ToUTF8(unescape(str));
	},
	CP1251ToUTF8 : function(str) {
		var result = original = converted = "", 
		length = str.length; 
		while(length--){ 
			original = str.charCodeAt(length); 
			if(original === 184){ 
				converted = 1105; 
			} 
			else if(original === 168){ 
				converted = 1025; 
			} 
			else if(original > 191 && original < 256){ 
				converted = original + 848; 
			} 
			else { 
				converted = original; 
			} 
			result = String.fromCharCode(converted) + result; 
		} 
		return result; 
	},
	// Функция обновляет какой-либо контент в заданный промежуток времени
	UpdateContentAction : function(url,container,time_limit,typecontent){
		var curtime = Math.floor(new Date().getTime() / 1000);
		if (start_time_reload_content - curtime + time_limit > 0) {
			return false;
		}
		start_time_reload_content = Math.floor(new Date().getTime() / 1000);
		return MP.LoadContent(url,container,'',typecontent);
	}
};

jQuery(document).ready(function(){
	if(typeof(hs)=='object') {
	    hs.graphicsDir = '/static/js/jquery/plugin/highslide/graphics/';
	    hs.outlineType = 'rounded-white';
	    hs.wrapperClassName = 'wide-border';
	    hs.creditsText = hs.creditsTitle = window.location.hostname;
	    hs.creditsHref = 'http://'+window.location.hostname;
	    hs.closeTitle = hs.closeText = 'Закрыть';
	    hs.resizeTitle = 'Изменить размер';
	    hs.loadingText = 'Загрузка...';
	    hs.loadingTitle = 'Кликните для закрытия';
	    hs.moveText = hs.moveTitle = 'Переместить';
	    hs.fullExpandTitle = 'Развернуть на фактический размер';
	}
});
