/*
 * This is a modification of the original vzConnect javascript library loaded
 * from http://static.pe.studivz.net/Js/id/v2/library.js . The modification
 * makes it possible to specify the image of the sVZ login image, by using
 * the "buttonImage" property.
 */

vz.id.widget.login.prototype['render'] = function (c) {
        var b = document.createElement("a");
        if (this.id) {
            b.id = this.id
        }
        var a = this.buildLink();
        b.href = "javascript:;";
        b.onclick = function () {
            window.open(a, "_blank", "width=570,height=700,scrollbars=yes")
        };
        var d = document.createElement("img");

        d.src = this.icon;
        d.alt = this.iconAlt;
        d.style.border = "0";

		var fullParameters = vz.id.util.parseOptions(c.innerHTML);
		if(fullParameters.buttonImage !== undefined) {
			d.src = fullParameters.buttonImage;
		}

		b.appendChild(d);

		if(fullParameters.container !== undefined) {
			document.getElementById(fullParameters.container).appendChild(b);
		} else {
        	c.parentNode.insertBefore(b, c);
		}

        return c
    }


vz.gosign = {

	/*
	 * The consumer key and the cookie key are set from within VzPlatform.class.php,
	 * because only PHP knows about them.
	 */
	consumerKey: null,
	cookieKey: null,

	setKeys: function(consumerKey, cookieKey) {
		this.consumerKey = consumerKey;
		this.cookieKey = cookieKey;
	},

	updateStatus: function() {
		jQuery('div#vzRegister img').attr('src', 'typo3conf/ext/go_social/res/buttonSchuelervzConnected.png');
	},

	loginCallback: function(c) {
		this.processRequest(c, true);
	},

	registerCallback: function(c) {
		this.processRequest(c, false);
	},

	processRequest: function(c, doLogin) {
		if (c.error) {
			console.log(c);
			return;
		}

		// Build data to be placed in the cookie from response.
		// This is mostly taken from
		// http://developer.studivz.net/wiki/index.php/VZ-Login-Tutorial

		var parameters = 'access_token=' + c.access_token;
		parameters += '&user_id=' + c.user_id;
		parameters += '&signature=' + c.signature;
		parameters += '&issued_at=' + c.issued_at;

		if(doLogin === true) {
			parameters += '&loginNow=1';
		}

		// Current time plus one day, as expiry date for the cookie
		var date = new Date();
		date = new Date( date.getTime() + (60 * 60 * 24 * 1000) );

		document.cookie = this.cookieKey + '=' + encodeURIComponent(parameters) + ';expires=' + date.toUTCString();

		if(doLogin === true) {
			window.location.reload();
		}

	}


}


/*
 * Workaround because the sVZ API callbacks have to be global functions.
 */
function vz_gosign_loginCallback(c) {
	vz.gosign.loginCallback(c);
}

function vz_gosign_registerCallback(c) {
	vz.gosign.registerCallback(c);
}

