
var original_width;
var original_height;
var keksi;

function ci(obj, default_value)
{
	if (obj.value == default_value)
	{
		obj.value = '';
	}
}

if (window.ActiveXObject) loader = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) loader = new XMLHttpRequest();

function global_onload()
{
	if (document.forms['login'])
	{
		document.forms['login']['username'].onfocus = function()
		{
			ci(document.forms['login']['username'], 'Käyttäjätunnus');
		}
		
		document.forms['login']['user_password'].onfocus = function()
		{
			ci(document.forms['login']['user_password'], 'Salasana');
		}
		
		document.forms['login']['username'].value = 'Käyttäjätunnus';
		document.forms['login']['user_password'].value = 'Salasana';
		
		document.getElementById('login_button').onclick = function()
		{
			return login();
		}
		
		document.getElementById('register_button').onclick = function()
		{
			return register();
		}
	}
	else if (document.getElementById('logout'))
	{
		document.getElementById('logout').onclick = function()
		{
			return logout();
		}
	}
	
	if (location.href == 'http://www.kuvamaja.com/my_images.php')
	{
		if (document.links)
		{
			for (i in document.links)
			{
				if (document.links[i].innerHTML == 'Poista' && document.links[i].href)
				{
					document.links[i].onclick = function()
					{
						return delete_image(this.href.replace(/http:\/\/www\.kuvamaja\.com\/my_images\.php\?delete=/, ''));
					}
				}
			}
		}
	}
	
	if (location.href.indexOf('http://www.kuvamaja.com/p/') != -1)
	{
		original_width = document.getElementById('image').width;
		original_height = document.getElementById('image').height;
		
		document.getElementById('scale_table').style.display = 'block';
		
		keksi = Cookie.get('scale');
		stored_value = keksi.getValue(get_image_filename());
		
		if (stored_value != -1)
		{
			document.getElementById('value_display_1').value = stored_value + '%';
			document.getElementById('horizontal_slider_1').style.left = stored_value + 'px';
			scale_image(stored_value);
		}
	}
}

function delete_image(image)
{
	return true;
	alert(image);
	return false;
}

function URLencode(sStr)
{
	return escape(sStr).
			replace(/\+/g, '%2B').
			replace(/\"/g,'%22').
			replace(/\'/g, '%27').
			replace(/\//g,'%2F');
}

function login()
{
	if (loader)
	{
		username = URLencode(document.forms['login']['username'].value);
		password = URLencode(document.forms['login']['user_password'].value);
		
		data = 'username=' + username + '&user_password=' + password + '&ajax=1&s=Kirjaudu';
		
		loader.open('POST', 'http://www.kuvamaja.com/login.php', true);
		loader.setRequestHeader('Content-Length', data.length);
		loader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
		
		loader.onreadystatechange = function()
		{
			if (loader.readyState==4)
			{
				response = loader.responseText;
				
				if (response.indexOf('ERROR') == 0)
				{
					if (response.indexOf('|') == -1)
					{
						alert('Virhe kirjautumisessa.');
					}
					else
					{
						alert(response.replace(/.*\|/, ''));
					}
				}
				else if (response.indexOf('OK') == 0)
				{
					login_ok();
				}
			}
		}
		
		loader.send(data);
		
		return false;
	}
	
	return true;
}

function register()
{
	if (loader)
	{
		username = URLencode(document.forms['login']['username'].value);
		password = URLencode(document.forms['login']['user_password'].value);
		
		data = 'username=' + username + '&user_password=' + password + '&ajax=1&s=' + URLencode('Rekisteröidy');
		
		loader.open('POST', 'http://www.kuvamaja.com/login.php', true);
		loader.setRequestHeader('Content-Length', data.length);
		loader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
		
		loader.onreadystatechange = function()
		{
			if (loader.readyState==4)
			{
				response = loader.responseText;
				
				if (response.indexOf('ERROR') == 0)
				{
					if (response.indexOf('|') == -1)
					{
						alert('Virhe rekisteröitymisessä.');
					}
					else
					{
						alert(response.replace(/.*\|/, ''));
					}
				}
				else if (response.indexOf('OK') == 0)
				{
					login_ok();
				}
			}
		}
		
		loader.send(data);
		
		return false;
	}
	
	return true;
}

function login_ok()
{
	document.getElementById('login').innerHTML = document.forms['login']['username'].value + ' - <a href="/my_images.php">Omat kuvat</a> - <a href="/login.php?logout" id="logout">Kirjaudu ulos</a>';
	global_onload();
}

function logout_ok()
{
	document.getElementById('login').innerHTML = '<form action="login.php" name="login" method="post"><input type="text" name="username" value="Käyttäjätunnus" /> <input type="password" value="Salasana" name="user_password" /> <input type="submit" value="Kirjaudu" name="s" id="login_button" /> <input type="submit" value="Rekisteröidy" name="s" id="register_button" /></form>';
	global_onload();
}

function logout()
{
	if (loader)
	{
		loader.open('GET', 'http://www.kuvamaja.com/login.php?logout', true);
		
		loader.onreadystatechange = function()
		{
			if (loader.readyState==4)
			{
				logout_ok();
			}
		}
		
		loader.send(null);
		
		return false;
	}
	else
	{
		return true;
	}
}


// from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function window_size(stat)
{
	var myWidth = 0, myHeight = 0;
	
	if ( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}
	else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	if (stat == 'width')
	{
		return myWidth;
	}
	else
	{
		return myHeight;
	}
}

// from http://www.codepost.org/view/135
function Cookie()
{
	var name, value = new Array(), expires, path="/", domain, secure=false, string = '';
	this.setName = function(sName) { name=sName; }
	this.getName = function() { return name; }
	
	this.getNumValues = function()
	{
		return value.length;
	}
	
	this.getValue = function(key)
	{
		if (!value[key])
		{
			return -1;
		}
		
		return value[key];
	}

	this.setValue = function(sValue)
	{
		tmp = sValue.split('&');
		
		for (i in tmp)
		{
			tmp2 = tmp[i].split('=');
			value[tmp2[0]] = tmp2[1];
		}
	}
	
	this.add = function(key, val)
	{
		value[key] = val;
	}
	
	this.setExpires = function(date) { expires=date; }
	this.getExpires = function() { return expires; }
	this.setDomain = function(sD) { domain=sD; }
	this.getDomain = function() { return domain; }
	this.setSecure = function(scr) { secure = !!scr; }
	this.getSecure = function() { return secure; }
	
	this.save = function()
	{
		if(name && value)
		{
			string = '';
			if(value instanceof Array)
			{
				for (i in value)
				{
					string += '&' + i + '=' + value[i];
				}
			}
			string = string.substr(1); // remove first &
			
			document.cookie = name+'='+escape( string ) +
				( ( expires ) ? ';expires='+expires.toGMTString() : '' ) + //expires.toGMTString()
				( ( path ) ? ';path=' + path : '' ) +
				( ( domain ) ? ';domain=' + domain : '' ) +
				( ( secure ) ? ';secure' : '' );
		}
	}
	
	this.remove = function()
	{
		// The cookie removed if the expires date is before today
		expires = new Date(new Date().getTime()-1000*60*60*24);
		this.save();
	}
};

Cookie.get = function(name)
{
	/*
		the document.cookie return a string contains all the cookies available in the browser for the specific domain in format of: Name=Value;Name=Value;Name=Value
		this function take only the cookie with the requested name and return a Cookie object with it's value.
		if there isn't a cookie with the requested name, the function returns an empty cookie object with the requested name
	*/
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	var cookie = new Cookie();
	if ( !((( !start ) && ( name != document.cookie.substring( 0, name.length ) )) || (start==-1) ) )
	{
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		cookie.setValue(unescape( document.cookie.substring( len, end ) ));
	}
	
	cookie.setName(name);
	return cookie;
}

function get_image_filename()
{
	return location.href.replace('http://www.kuvamaja.com/p/', '');
}

function scale_image(percent)
{
	img = carpeGetElementById('image');
	img.width = original_width * (percent / 100);
	img.height = original_height * (percent / 100);
	
	if ((img.width + 30) > 350)
	{
		carpeGetElementById('content').style.width = (img.width + 30) + 'px';
		carpeGetElementById('content').style.height = img.height + 'px';
	}
}

