


ii.Login = function(id, username, key)
{
	this.id = id;
	this.username = username;
	this.key = key;

	if (document.getElementById('ii_user_status_state'))
	{
//		document.getElementById('ii_user_status_state').innerHTML = 'Hi <a href="#rel&item=ME.0&pane=">' + this.username + '</a>! | '
		document.getElementById('ii_btn_logout').style.display='inline';
		document.getElementById('ii_btn_signup').style.display='none';
		document.getElementById('ii_btn_login').style.display='none';
		document.getElementById('ii_btn_add').style.display='block';
		document.getElementById('ii_btn_myinbox').style.display='block';
	}

	// we always need ourself
	if (!ii.Query) return;
	this.query = new ii.Query('user', {interval:10000}, {me:true,fields:'full'});
	this.query.start();

	if (ii.anonQuery)
	{
		ii.anonQuery.stop();
		ii.anonQuery = 0;
	}

	if (ii.anonMe) {
		ii.anonMe.remove();
	
	}

    // a view for the header status
	var that = this;

    this.query.addListener({
        addItem: function(item){
			that.item = item;
            item.createView('MyStatusState', {});
			that.setUnread();
			ii.app.map.addItem(item);

			document.getElementById('ii_locatemebtn').style.display 
				= ((item.status == 'live') ? 'none' : 'block');
			ii.setText(document.getElementById('ii_locatemebtn'), 
				'Locate Me');

        }
    });
	if (ii.tracker) ii.tracker._trackEvent('Session', 'Login', username);

    if (ii.watchId !== undefined)
    {
        ii.app.isLocated = false;
        ii.watchId = navigator.geolocation.clearWatch(ii.watchId);
        delete ii.watchId;
        ii.watchId = undefined;

    }
}

ii.Login.softLogout = function(){
	ii.get('s-logout', function(resp) {}, {soft:true});
}

ii.Login.prototype.logout = function(){

	window.location	= '#rel&item=&tab=';
	ii.get('s-logout', function(resp){

	    ii.removeCookie('id');
	    ii.removeCookie('username');
	    ii.removeCookie('key');

		delete ii.login;
		ii.app.state.refresh();
	});
	delete this.key;

    document.getElementById('ii_user_status_state').innerHTML = '';
	document.getElementById('ii_btn_logout').style.display='none';
	document.getElementById('ii_btn_signup').style.display='inline';
	document.getElementById('ii_btn_login').style.display='inline';
	document.getElementById('ii_btn_add').style.display='none';
	document.getElementById('ii_btn_myinbox').style.display='none';
    ii.log('stopping me-query');

	this.query.stop();
    ii.log('stopped me-query');

	ii.app.isLocated = false;

	ii.tracker._trackEvent('Session', 'Logout', this.username);

    if (ii.watchId !== undefined)
    {
        ii.app.isLocated = false;
        ii.watchId = navigator.geolocation.clearWatch(ii.watchId);
        delete ii.watchId;
        ii.watchId = undefined;

    }
	document.getElementById('ii_locatemebtn').style.display 
		= ('block');
	ii.setText(document.getElementById('ii_locatemebtn'), 
		'Locate Me');
}

ii.Login.prototype.updateAvatars = function()
{
	// for each view, with a div, update the imgs
	for(var n=0; n < this.item.itemviews.length; n++)
	{
		var vw = this.item.itemviews[n];
		var div = vw.div;
		if (!div && vw.details)
			div = vw.details.form;

		if (!div)
			continue;

		var imgs = div.getElementsByTagName('img');
		for (var m=0; m < imgs.length; m++)
		{
			if (/d-media/.test(imgs[m].src))
			{
				imgs[m].src += '&t=' + Math.random();
			}
		}
		if (div.style.backgroundImage &&
			/d-media/.test(div.style.backgroundImage))
		{
			ii.log('Reloading background-img');
			div.style.backgroundImage =
				div.style.backgroundImage.replace(')',
						'&t=' + Math.random()+')');
		}
	}
}

ii.Login.prototype.setUnread = function()
{
	var total = parseInt(this.item.unreadmsg)
		+ parseInt(this.item.unreadcmt);

	ii.log('setting unread: ' + total);
	var sp = ii.views.unreadIndicator(total);
	sp.id = 'ii_unread';

	var ur = document.getElementById('ii_unread');
	ur.parentNode.replaceChild(sp, ur);

	function setElm(id, count)
	{
		var ur = document.getElementById(id);
		if (ur && ur.parentNode)
		{
			var sp = ii.views.unreadIndicator(count);
			sp.id = id;
			ur.parentNode.replaceChild(sp, ur);
		}
	}
	setElm('ii_unread_msg', this.item.unreadmsg);
	setElm('ii_unread_cmt', this.item.unreadcmt);
	setElm('ii_unread_msg2', this.item.unreadmsg);
	setElm('ii_unread_cmt2', this.item.unreadcmt);

	if (total>0)
		var icon = 'favicon_notify.ico';
	else
		var icon = 'favicon.ico';

	document.getElementById('ii_favicon').innerHTML =
		'<link rel="shortcut icon" href="'+icon+'">';

}

ii.Login.isLoggedIn = function()
{
	return ii.login;
}

ii.Login.landingLoginBox = function()
{
	var loginBoxContainer = ii.elm('div', {
    		style: {
    			background: 'white',
    			left: '0px',
    			padding: '15px 16px 35px',
    			position: 'absolute',
    			top: '0px',
    			width: '294px',
    			zIndex: '999'
    		}
    	},
        ii.Login.loginBox({
            displayHeader: true,
            displayBorder: true,
            initOnSuccess: true
        })
    );

	return loginBoxContainer;
}

/**
 * the login box presented defined with the according options
 *
 * @param {Object} options an object defining the options for the loginbox
 */
ii.Login.loginBox = function(options)
{

    var options = (options !== undefined ? options : {});

	var error_p = ii.elm('p', { style:{color:'#FF0000', margin:'5px', position:'relative', textAlign:'center'}}, '');

	var username_input = ii.elm('input', { name:'username', style:{width:'100%'} } );
	var password_input = ii.elm('input', { name:'password', type:'password', style:{width:'100%'} } );
	var checkbox_input = ii.elm('input', { name:'remember_me', type: 'checkbox'});
	var login_button   = ii.elm('input', {type:'submit', value:'Log in', style:{margin:'0px', position:'absolute', right:'0px'}});

    var header = '';
    if(options.displayHeader && options.displayHeader !== false){
        header = ii.elm('h1', {style:{borderBottom:'solid 1px #b7b7b7', marginBottom:'20px', padding:'5px 0px'}}, 'Log in for bliin');
    }

	var forgetPasswordForm = ii.elm('form', {
				style: {
					display:'none',
					padding: '10px 25px 10px 11px',
					margin: '0px 0px 5px'
				},
				className:'forgotpassword',
				onsubmit:function(){
					if (!this.username.value && !this.email.value)
					{
						alert('Please enter your bliin-username or your email');
						return false;
					}

					ii.get('p-new-password', function(resp){},
						{
							username:this.username.value,
							email:this.email.value
						});
					alert('A new password has been send to your email address');
					form_fields.style.display = '';
					forgetPasswordForm.style.display='none';
					return false;
				}
			},
			ii.elm('p',
				'A new password will be generated and sent to your ',
				'email address. Type your email address or your bliin-username'
			),
			ii.elm('p',
				ii.elm('label',
					{style:{cssFloat:'left',styleFloat:'left',
						display:'block', width:'50px'}},
					'username:'
				),
				ii.elm('input', {style:{width:'160px',margin:'0px 1em'}, name:'username'})
			),
			ii.elm('p', '... or ...'),
			ii.elm('p',
				ii.elm('label',
					{style:{cssFloat:'left',styleFloat:'left',
						display:'block', width:'50px'}},
					'email:'
				),
				ii.elm('input', {style:{width:'160px',margin:'0px 1em'}, name:'email'})
			),
			ii.elm('input', {type:'submit',value:'Send',
				style:{cssFloat:'right', styleFloat:'right',
					margin:'0px 0px 1em 1em'}}),

			ii.elm('input', {type:'button',value:'Cancel',
				style:{cssFloat:'right', styleFloat:'right',
					margin:'0px 0px 1em 1em'},
				onclick:function() {

					form_fields.style.display = '';
					forgetPasswordForm.style.display='none';

				}}),
			ii.elm('div', {style:{clear:'both'}})
		);
    if(options.displayBorder && options.displayBorder !== false){
        forgetPasswordForm.style.border = 'solid 1px #b7b7b7';
	}

	var form_fields;

	var forgetPasswordLink = ii.elm('a', {
			href:'#rel',
			onclick:function() {
				{
					form_fields.style.display = 'none';
					forgetPasswordForm.style.display='';
				}
			}
		},
		'Forgot Password?');


    form_fields = ii.elm('div', {
            style:{
                margin:'0px 0px 5px',
                padding:'10px 25px 10px 11px',
                position:'relative'}
        },
		ii.elm('div', {style:{left:'0px', position:'absolute', top:'0px', width:'100%'}},
			error_p
		),
		ii.elm('p',
			ii.elm('label', {style:{display:'block', width:'100%'}}, 'Username'),
			username_input
		),
		ii.elm('p',
			ii.elm('label', {style:{display:'block', width:'100%'}}, 'Password'),
			password_input
		),
		ii.elm('p',
			checkbox_input,
			ii.elm('span', 'Remember Me')
		),
		ii.elm('p', {style:{position:'relative'}},
			forgetPasswordLink,
			forgetPasswordForm,
			login_button
		),
		ii.elm('p', {style:{padding:'5px 0px 0px'}},
			ii.elm('b', 'Need a login?'),
			ii.elm('br'),
			ii.elm('a', {href:"#rel&tab=Signup"}, 'Signup for an account ... it\'s free')
		)
	);

    if(options.displayBorder && options.displayBorder !== false){
        form_fields.style.border = 'solid 1px #b7b7b7';
    }

	var loginBox = ii.elm('form', {
            name:'ii_login_form'
        },
		header,
        form_fields,
		forgetPasswordForm
	);

	//loginBox.onmousedown = function(ev) { ii.stopPropagation(ev); };

	loginBox.onsubmit = function()
	{

		ii.Login.doLogin(
			username_input.value,
			password_input.value,
			function(login) {
				/* success */

				try {
					var error_text = document.createTextNode('');
					error_p.replaceChild(error_text, error_p.firstChild);
				}
				catch (err) {
					// no error, success
				}

				ii.login = login;

				if (checkbox_input.checked){

					ii.setCookie('id', ii.login.id, 365);
					ii.setCookie('username', ii.login.username, 365);
					ii.setCookie('key', ii.login.key, 365);
				}
                else {

                    ii.setCookie('id', ii.login.id, 0);
                    ii.setCookie('username', ii.login.username, 0);
                    ii.setCookie('key', ii.login.key, 0);
                }

				ii.app.landing.remove();

				// re-intialize to show the map
                if(options.initOnSuccess && options.initOnSuccess !== false){
    				ii.app.init();
					ii.app.state.setState({item:'ME.0'});
                }
                else {
                    ii.app.state.refresh();
                }


			},
			function(error) {
				/* fail */

				var error_text = document.createTextNode(error);
				try {
					error_p.replaceChild(error_text, error_p.firstChild);
				}
				catch (err) {
					error_p.appendChild(error_text);
				}
			}
		);

		return false;
	}

    return loginBox;
}



/* call without resp
   performs full login procedure
 */
ii.Login.doLogin = function(username, password, onSuccess, onFail, resp)
{

	if (!resp)
	{
	    // first step, get tempkey
        ii.get('s-getkey', function(resp) {
            ii.Login.doLogin(username, password, onSuccess, onFail, resp)
        }, {loginname: username});
    }
    else if (resp.tempkey){
        // use tempkey as seed for password-hash,
        var hash = MD5(password+resp.tempkey);

        ii.get('s-login', function(resp) {
            ii.Login.doLogin(username, password, onSuccess, onFail, resp)
        }, {loginname: username, password: hash});

        // ii.get('s-login', function(resp) { ii.Login.doLogin(username, password, onSuccess, onFail, resp); }, {loginname: username, password: password});
    }
	else if (resp.loginresult=='OK')
	{
		var login = new ii.Login(resp.id, username, resp.key);
		onSuccess(login);
	}
	else
	{
		onFail(resp.loginresult);
	}

}



