/*
Based on the Simple OpenID Plugin
http://code.google.com/p/openid-selector/

This code is licenced under the New BSD License.
*/

var selections = {
	email: {
		id: 'email',
		name: 'Email',
		icon: 'wikiicons/email.png',
		label: 'Enter your email address:',
		url: null
	},
	openid: {
		id: 'openid',
		name: 'OpenID',
		icon: 'wikiicons/openidlogin-bg.png',
		label: 'Enter your OpenID:',
		url: null
	}
};

var selector = {

	ajaxHandler: null,
	cookie_expires: 6*30,	// 6 months.
	cookie_name: 'openid_selection', // historical name
	cookie_path: '/',
	
	img_path: 'images/',
	
	input_id: null,
	selection_url: null,
	selection_id: null,
	othersignin_id: null,
	
    init: function(input_id, login_methods, othersignin_id, othersignin_label) {
        
	var selector_btns = document.getElementById('login_btns');
        
        this.input_id = input_id;
        
	document.getElementById('login_input_area').textContent = '';
	// show element; override display:none
	document.getElementById('login_choice').style.display = 'block';
        
        // add box for each selection
	if (login_methods['openid']) {
		selector_btns.append(this.getBoxHTML(selections['openid']));
	}
	if (login_methods['email']) {
		selector_btns.prepend(this.getBoxHTML(selections['email']));
	}

	if (othersignin_label != "") {
		this.othersignin_label=othersignin_label;
	}
	else {
		this.othersignin_label="other";
	}
	if (othersignin_id != "") {
		this.othersignin_id=othersignin_id;
		selector_btns.prepend(this.getBoxHTML({
			id:    'othersignin',
			name:  this.othersignin_label,
			icon:  'favicon.ico',
		}));
		document.getElementById(this.othersignin_id).style.display = 'none';
	}

	document.getElementById('login_selector_form').addEventListener('submit', this.submit);
        
        var box_id = this.readCookie();
        if (box_id) {
        	this.signin(box_id, true);
        }
    },
    getBoxHTML: function(selection) {
	var div = document.createElement('div');
	var a = document.createElement('a');
	var img = document.createElement('img');

        var box_id = selection["id"];
	a.onclick = function() { selector.signin(box_id); };
	a.classList.add(box_id, 'login_large_btn');

	img.alt = "";
	img.width = img.height = 16;
	img.src = selection["icon"];

	a.appendChild(img);
	a.appendChild(document.createTextNode(' ' + selection["name"]));

	div.appendChild(a);
	return div;
    },
    /* selection image click */
    signin: function(box_id, onload) {

	if (box_id == 'othersignin') {
	    	this.highlight(box_id);
		document.getElementById('login_input_area').textContent = '';
		document.getElementById(this.othersignin_id).style.display = 'block';
		this.setCookie(box_id);
		return;
	}
	else {
		if (this.othersignin_id) {
			document.getElementById(this.othersignin_id).style.display = 'none';
		}
	}

    	var selection = selections[box_id];
  		if (! selection) {
  			return;
  		}
		
		this.highlight(box_id);
		
		this.selection_id = box_id;
		this.selection_url = selection['url'];
		
		// prompt user for input?
		if (selection['label']) {
			this.setCookie(box_id);
			this.useInputBox(selection);
		} else {
			this.setCookie('');
			document.getElementById('login_input_area').textContent = '';
			if (! onload) {
				document.getElementById('login_selector_form').submit();
			}
		}
    },
    /* Sign-in button click */
    submit: function() {
    	var url = selector.selection_url; 
    	if (url) {
		var eval = document.getElementById('entry').val();
		url = url.replace('{username}', eval);
    		selector.setOpenIdUrl(url);
    	}
	else {
    		selector.setOpenIdUrl("");
	}
    	if (selector.ajaxHandler) {
    		selector.ajaxHandler(selector.selection_id, document.getElementById(selector.input_id).value);
    		return false;
    	}
    	return true;
    },
    setOpenIdUrl: function (url) {
    
	var hidden = document.getElementById(this.input_id);
	if (hidden.length > 0) {
		hidden.value = url;
    	} else {
		var inp = document.createElement('input');
		inp.style.display =  'none';
		inp.id = inp.name = this.input_id;
		inp.value = url;
		document.getElementById('login_selector_form').appendChild(inp);
    	}
    },
    highlight: function (box_id) {
	for (elem of document.getElementsByClassName('login_large_btn')) {
		var div = elem.parentElement;
		if(elem.classList.contains(box_id)) {
			div.classList.add('login_highlight');
		} else {
			div.classList.remove('login_highlight');
		}
	}
    },
    setCookie: function (value) {
    
		var date = new Date();
		date.setTime(date.getTime()+(this.cookie_expires*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		
		document.cookie = this.cookie_name+"="+value+expires+"; path=" + this.cookie_path;
    },
    readCookie: function () {
		var nameEQ = this.cookie_name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
    },
    useInputBox: function (selection) {
   	
		var input_area = document.getElementById('login_input_area');
		
		var html = '';
		var id = selection['name']+'_entry';
		var label = selection['label'];
		
		if (selection['name'] == 'OpenID') {
			id = this.input_id;
		}
		if (label) {
			html = '<label for="'+ id +'" class="block">' + label + '</label>';
		}
		html += '<input id="'+id+'" type="text" name="'+id+'" />' + 
					'<input id="selector_submit" type="submit" value="Login"/>';
		
		input_area.innerHTML = html;

		document.getElementById(id).focus();
    },
    setAjaxHandler: function (ajaxFunction) {
    	this.ajaxHandler = ajaxFunction;
    }
};
