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));
		}
	});
};
 
$(document).ready(function() {
	SteamProfile = new SteamProfile();
	SteamProfile.init();
});

function SteamProfile() {
	var basePath;
	var themePath;
	var showGameBanner;
	var showSliderMenu;
	var showTF2ItemsIcon;
	var profiles = new Array();
	var profileCache = new Object();
	var loadLock = false;
	var configLoaded = false;
	var configData;
	var profileTpl;
	var loadingTpl;
	var errorTpl;

	this.init = function() {
		var scriptElement = $('script[src$=\'steamprofile.js\']');
		
		if(scriptElement.length == 0) {
			return;
		}
		
		basePath = scriptElement.attr('src').replace('steamprofile.js', '');
		
		jQuery.ajax({
			type: 'GET',
			url: basePath + 'steamprofile.xml',
			dataType: 'html',
			complete: function(request, status) {
				configData = $(request.responseXML);
				loadConfig();
			}
		});
	}
	
	this.refresh = function() {

		if(!configLoaded || loadLock) {
			return;
		}
		
		loadLock = true;
		

		profiles = $('.steamprofile[title]');
		
		if(profiles.length == 0) {
			return;
		}

		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);
		
		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);
	}
	
	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');
	
		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);
		
		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) {
			jQuery.ajax({
				type: 'GET',
				url: getXMLProxyURL(profileID),
				dataType: 'xml',
				complete: function(request, status) {
					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) {
			if (profileData.find('profile > steamID').text() == '') {
				return createError('Uzytkownik nie ustawil profilu Steam.');
			} else {
				var 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('Profil STEAM jest prywatny.');
				} 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-iconchat')
						.attr('href', 'steam://friends/message/' + profileData.find('profile > steamID64').text());
					
					profile.find('.sp-avatar a, .sp-info a')
						.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) {
			return createError(profileData.find('response > error').text());
		} else {
			return createError('Blad w danych Steam.');
		}
	}
	
	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;
	}
};






