/**
 * Этот файл является частью модификации SteamProfile.
 *
 * Автор скрипта: Nico Bergemann <barracuda415@yahoo.de>
 * Copyright 2009 Nico Bergemann
 *
 *      Перевод на русский язык: Gl0BuZ
 *      <globuz@no-steam.ru>
 *      Copyright 2009 Gl0BuZ
 *
 *      Автор модификации: Alex 'Gl0BuZ' Shchepilov
 *      <globuz@no-steam.ru>
 *      Copyright 2010 Gl0BuZ
 *
 */

jQuery.fn.attrAppend = function(name, value) {
	var elem;
	return this.each(function(){
		elem = $(this);
		
		// использовать, если атрибут существует
		if(elem.attr(name) !== undefined && elem.attr(name) != "") {
			elem.attr(name, value + elem.attr(name));
		}
	});
};

function SteamProfile() {
	var basePath;
	var themePath;
	var showGameBanner;
	var showSliderMenu;
	var showTF2ItemsIcon;
	var profiles = [];
	var profileCache = {};
	var loadLock = false;
	var configLoaded = false;
	var configData;
	var profileTpl;
	var loadingTpl;
	var errorTpl;
	var lang = "russian";
	var langLocal = "russian";
	var langData = {
		english : {
			loading : "Loading...",
			no_profile : "This user has not yet set up their Steam Community profile.",
			private_profile : "This profile is private.",
			invalid_data : "Invalid profile data.",
			join_game : "Join Game",
			add_friend : "Add to Friends",
			view_tf2items : "View TF2 Backpack"
		},
		russian : {
			loading : "Загрузка...",
			no_profile : "Этот пользователь ещё не создал свой Steam Community профиль.",
			private_profile : "Этот профиль приватный.",
			invalid_data : "Неверные данные профиля.",
			join_game : "Присоединиться к игре",
			add_friend : "Добавить в друзья",
			view_tf2items : "Посмотреть TF2 Рюкзак"
		},
		german : {
			loading : "Lade…",
			no_profile : "Dieser Benutzer hat bisher kein Steam Community Profil angelegt.",
			private_profile : "Dieses Profil is privat.",
			invalid_data : "Ungultige Profildaten.",
			join_game : "Spiel beitreten",
			add_friend : "Als Freund hinzufugen",
			view_tf2items : "TF2 Rucksack ansehen"
		},
		portuguese : {
			loading : "Carregando…",
			no_profile : "This user has not yet set up their Steam Community profile.",
			private_profile : "This profile is private.",
			invalid_data : "Invalid profile data.",
			join_game : "Entrar",
			add_friend : "Adicionar a sua lista de amigos",
			view_tf2items : "Ver Itens do TF2"
		}
	};

	this.init = function() {
		  // получаем наш тег <script>
		var scriptElement = $('script[src$=\'steamprofile.js\']');
		
		  // в некоторых случаях скрипт может использоваться без тега <script>
		if(scriptElement.length === 0) {
			return;
		}
		
		 // извлекаем путь из атрибута src
		basePath = scriptElement.attr('src').replace('steamprofile.js', '');
		
		 // загружаем xml конфиг
		jQuery.ajax({
			type: 'GET',
			url: basePath + 'steamprofile.xml',
			dataType: 'html',
			complete: function(request, status) {
				configData = $(request.responseXML);
				loadConfig();
			}
		});
	};
	
	this.refresh = function() {
		 // проверяем, что конфиг загружен
                 // и доходит до профиляds
		if(!configLoaded || loadLock) {
			return;
		}
		
		 // блокируем загрузку
		loadLock = true;
		
		// выбираем значение заполнителя профиля
		profiles = $('.steamprofile[title]');
		
		// есть профили для создания?
		if(profiles.length === 0) {
			return;
		}

		// сохраняем id профиля для дальнейшего использования
		profiles.each(function() {
			var profile = $(this);
			profile.data('profileID', $.trim(profile.attr('title')));
			profile.removeAttr('title');
		});

		// заменяем значение заполнителя согласно шаблону загрузки и делаем его видимым
		profiles.empty().append(loadingTpl);
		
		// загружаем первый профиль
		loadProfile(0);
	};
	
	this.load = function(profileID) {
		// проверяем, что конфиг загружен
                // и доходит до профиля
		if(!configLoaded || loadLock) {
			return;
		}
		
		// создаём основу профиля
		profile = $('<div class="steamprofile"></div>');
		
		// загружаем тему
		profile.append(loadingTpl);
		
		// загружаем xml даные
		jQuery.ajax({
			type: 'GET',
			url: getXMLProxyURL(profileID),
			dataType: 'xml',
			complete: function(request, status) {
				// создаём профиль и заменяем значение заполнителя на профиль
				profile.empty().append(createProfile($(request.responseXML)));
			}
		});
		
		return profile;
	};
	
	this.isLocked = function() {
		return loadLock;
	};
	
	function getXMLProxyURL(profileID) {
		return basePath + 'xmlproxy.php?id=' + escape(profileID) + '&lang=' + escape(lang);
	}
	
	function getConfigString(name) {
		return configData.find('vars > var[name="' + name + '"]').text();
	}
	
	function getConfigBool(name) {
		return getConfigString(name).toLowerCase() == 'true';
	}
	
	function loadConfig() {
		showSliderMenu = getConfigBool('slidermenu');
		showGameBanner = getConfigBool('gamebanner');
		showTF2ItemsIcon = getConfigBool('tf2items');
		lang = getConfigString('language');
		langLocal = lang;
		
		// откатываемся к английскому языку, если выбранный перевод не существет
		if(langData[langLocal] == null) {
			langLocal = "russian";
		}
	
		// задаём стиль темы
		themePath = basePath + 'themes/' + getConfigString('theme') + '/';
		$('head').append('<link rel="stylesheet" type="text/css" href="' + themePath + 'style.css">');
		
		// загружаем шаблон
		profileTpl = $(configData.find('templates > profile').text());
		loadingTpl = $(configData.find('templates > loading').text());
		errorTpl   = $(configData.find('templates > error').text());
		
		// добавляем путь темы к источнику изображения
		profileTpl.find('img').attrAppend('src', themePath);
		loadingTpl.find('img').attrAppend('src', themePath);
		errorTpl.find('img').attrAppend('src', themePath);
		
		 // задаём перевод
		profileTpl.find('.sp-joingame').attr('title', langData[langLocal].join_game);
		profileTpl.find('.sp-addfriend').attr('title', langData[langLocal].add_friend);
		profileTpl.find('.sp-viewitems').attr('title', langData[langLocal].view_tf2items);
		loadingTpl.append(langData[langLocal].loading);
		
		// теперь мы можем разблокировать функцию обновления
		configLoaded = true;
		
		// старт загрузки профиля
		SteamProfile.refresh();
	}

	function loadProfile(profileIndex) {
		// проверяем, загрузились ли все профили
		if(profileIndex >= profiles.length) {
			// разблокируем загрузку
			loadLock = false;
			return;
		}
		
		var profile = $(profiles[profileIndex++]);
		var profileID = profile.data('profileID');
		
		if(profileCache[profileID] == null) {
			// загружаем данные xml 
			jQuery.ajax({
				type: 'GET',
				url: getXMLProxyURL(profileID),
				dataType: 'xml',
				complete: function(request, status) {
					// создаём профиль и кэш DOM для данных ID
					profileCache[profileID] = createProfile($(request.responseXML));
					// заменяем значение заполнителя на профиль
					profile.empty().append(profileCache[profileID]);
					// загружаем следующий профиль
					loadProfile(profileIndex);
				}
			});
		} else {
			// профиль был создан ранее, только копируем его
			var profileCopy = profileCache[profileID].clone();
			createEvents(profileCopy);
			profile.empty().append(profileCopy);
			// загружаем следующий профиль
			loadProfile(profileIndex);
		}
	}

	function createProfile(profileData) {
		if (profileData.find('profile').length !== 0) {
			var profile;
		
			if (profileData.find('profile > steamID').text() == '') {
				// профиль ещё не существует
				return createError(langData[langLocal].no_profile);
			} else {
				// данные профиля подходят
				profile = profileTpl.clone();
				var onlineState = profileData.find('profile > onlineState').text();
				
				// задаём состояние класса, изображения аватара и имени
				profile.find('.sp-badge').addClass('sp-' + onlineState);
				profile.find('.sp-avatar img').attr('src', profileData.find('profile > avatarIcon').text());
				profile.find('.sp-info a').append(profileData.find('profile > steamID').text());
				
				// выводим сообщение о состоянии
				if (profileData.find('profile > visibilityState').text() == '1') {
					profile.find('.sp-info').append(langData[langLocal].private_profile);
				} else {
					profile.find('.sp-info').append(profileData.find('profile > stateMessage').text());
				}
				
				// задаём фон игры
				if (showGameBanner && profileData.find('profile > inGameInfo > gameLogoSmall').length !== 0) {
					profile.css('background-image', 'url(' + profileData.find('profile > inGameInfo > gameLogoSmall').text() + ')');
				} else {
					profile.removeClass('sp-bg-game');
					profile.find('.sp-bg-fade').removeClass('sp-bg-fade');
				}
				
				if(showSliderMenu) {
					if (profileData.find('profile > inGameInfo > gameJoinLink').length !== 0) {
						// добавляем ссылку 'Присоединиться' 
						profile.find('.sp-joingame').attr('href', profileData.find('profile > inGameInfo > gameJoinLink').text());
					} else {
						 // пользователь не в многопользовательской игре, убираем ссылку 'Присоединиться'
						profile.find('.sp-joingame').remove();
					}
				
					if(showTF2ItemsIcon) {
						// добавляем ссылку 'Посмотреть предметы'
						profile.find('.sp-viewitems')
							.attr('href', 'http://tf2items.com/profiles/' + profileData.find('profile > steamID64').text());
					} else {
						profile.find('.sp-viewitems').remove();
					}
					
					// добавляем ссылку 'Добавить в друзья' 
					profile.find('.sp-addfriend')
						.attr('href', 'steam://friends/add/' + profileData.find('profile > steamID64').text());
					
					// добавляем остальные ссылки
					profile.find('.sp-avatar a, .sp-info a.sp-name')
						.attr('href', 'http://steamcommunity.com/profiles/' + profileData.find('profile > steamID64').text());
					
					createEvents(profile);
				} else {
					profile.find('.sp-extra').remove();
				}
			}
			
			return profile;
		} else if (profileData.find('response').length !== 0) {
			// steam community возвращает ссобщение
			return createError(profileData.find('response > error').text());
		} else {
			// мы получаем недействительные данные xml
			return createError(langData[langLocal].invalid_data);
		}
	}
	
	function createEvents(profile) {
		// добавляем события для меню
		profile.find('.sp-handle').click(function() {
			profile.find('.sp-content').toggle(200);
		});
	}

	function createError(message) {
		var errorTmp = errorTpl.clone();
		errorTmp.append(message);	
		return errorTmp;
	}
}

$(document).ready(function() {
	SteamProfile = new SteamProfile();
	SteamProfile.init();
});
