// Jimdo Friends

var friend = {

	addresponse: function(t)
	{
		response = t.responseText.evalJSON();
		if (response.status != 'FATAL_ERROR') {
			document.location = response.go;
		}
		else {
			new Insertion.Before('becomefriendsiframe', '<div class="gutter"><p class="message-error">' + frienddata.errorMessage + '</p></div>');
		}
	},

	add: function(friendid){
		$('becomefriends-button').disable();

		new Ajax.Request('/app/social/friend/becomefriends/with/' + escape(friendid) + '/',
			{method: 'post', parameters: 'token=' + $F('becomefriends-token'), onSuccess: this.addresponse});
	},

	showpopup: function(elt, friendid){
		
		friendid = friendid.toString().split('index.html')[2];

		while (elt = elt.nextSibling) {
			if (elt.nodeName == 'DIV')
			  break;
		}
		elt = elt.firstChild;

		if ($('friendpopup')) {
			friend.hidepopup();
		}
		else {

			new Insertion.After(elt,"<div class=\"popup\" id=\"friendpopup\" style=\"display:none;\"></div>");
			
			

			new Ajax.Request('/app/social/friend/getprofile/of/' + escape(friendid) + '/', {
				method: 'get',
				onSuccess: function(t){

					var response = t.responseText.evalJSON();
					this.frienddata = response;

					$('friendpopup').update('' +
					'<div class="top">' +
					'<div class="friend">' +
					'<img src="' + response.avatarUrl + '" alt="" />' +
					'<a id="super" href="javascript:void(1)" onclick="friend.hidepopup()" class="close">close</a>' +
					'<div class="details">' +
					'<h4>' + response.title + '</h4>' +
					'<p>' + response.address + '</p>' +
					'<p>' + response.resume + '</p>' +
					'</div>' +
					'</div>' +

					'<div id="friendcontent"></div>' +
					'</div>' +
					'<div class="bottom"> </div>');

					new Effect.Parallel([new Effect.Appear('friendpopup'), new Effect.Morph('friendpopup', {
						style: 'margin-top:10px;'
					})], {
						duration: 1.0,
						afterFinish: function(){
							($('friendcontent').update('<iframe id="becomefriendsiframe" src="' + window.webserver + 'app/social/friend/becomefriends/with/' + escape(friendid) + '/" frameborder="0" scrolling="no" width="380" height="60"></iframe>'));
						}
					});		

				}
			})
		}
	},

	hidepopup: function() {

		// iframe entfernen
		if ($('becomefriendsiframe') != null) {
			$('becomefriendsiframe').hide();
		}

		new Effect.Parallel(
			[
				new Effect.Fade('friendpopup'),
				new Effect.Morph('friendpopup', {style: 'margin-top:-30px;'})
			],
			{
				duration: 1.0,
				afterFinish: function() { $('friendpopup').remove(); }
			}
		);	
	},

	message: function(msg) {

		// iframe entfernen
		if ($('becomefriendsiframe') != null) {
			$('becomefriendsiframe').hide();
		}	
		
		new Insertion.Before('becomefriendsiframe', "<div class=\"friendgutter\"><p class=\"message-ok\">" + frienddata.successMessage + "</p></div>");

		window.setTimeout('friend.hidepopup()', 2500);
	}
}

// Modal Window -- to become successor/core of JimdoSigninWindow
var ModalWindow = {

    rmiClose: function(theWindow, returnObject)
    {    
        var callback = ModalWindow.callback;
        delete ModalWindow.callback;

        ModalWindow.returnValue = {};
        for (prop in returnObject) {
            ModalWindow.returnValue[prop] = returnObject[prop];
        }

        theWindow.close();
        callback();
        delete ModalWindow.returnValue;
    },
    check: function()
    {
        if (ModalWindow.popup) {

            var closed = false;
            try {
                var closed = ModalWindow.popup.closed;
            } catch (e) { }

            if (closed) {
                delete ModalWindow.popup;
                if (ModalWindow.callback) {
                    ModalWindow.callback();
                    delete ModalWindow.callback;
				}
            } else {
                setTimeout(ModalWindow.check, 800);
            }
        }
    },
    hide: function()
    {
        if (null != ModalWindow.popup) {
            ModalWindow.popup.close();
            ModalWindow.popup = null;
        }
    },
    show: function(url, options, callback) {

    	if (ModalWindow.popup) {
           ModalWindow.popup.focus();
           return;
        }
        delete ModalWindow.returnValue;
        ModalWindow.callback = callback;

        var defaultOptions = {
            height: 80,
            width: 80,

            directories: 'no',
    		location: 'yes',
    		menu: 'no',
            resizable: 'yes',
            scroll: 'yes',
            status: 'yes',
            title: 'yes',
            tools: 'no'
        }
        for (key in options) {
            defaultOptions[key] = options[key];
        }

        var hasEventListener = ('undefined' == typeof window.attachEvent);
        var hasModalDialog   = ('undefined' != typeof window.showModalDialog);

        if (hasEventListener && hasModalDialog) {
            optionString  = 'dialogHeight:'+defaultOptions.height+'px;';
            optionString += 'dialogWidth:'+defaultOptions.width+'px;';
            optionString += 'resizable:'+defaultOptions.resizable+';';
            optionString += 'scroll:'+defaultOptions.scroll+';';
            optionString += 'status:'+defaultOptions.status;
            // alert(optionString);

            showModalDialog(url, null, optionString);
            if (ModalWindow.callback) {
                ModalWindow.callback();
            }
        } else {
            optionString  = 'height='+defaultOptions.height+',';
            optionString += 'width='+defaultOptions.width+',';
            optionString += 'directories='+defaultOptions.directories+',';
            optionString += 'location='+defaultOptions.location+',';
            optionString += 'menubar='+defaultOptions.menu+',';
            optionString += 'resizable='+defaultOptions.resizable+',';
            optionString += 'scrollbars='+defaultOptions.scroll+',';
            optionString += 'status='+defaultOptions.status+',';
            optionString += 'titlebar='+defaultOptions.status+',';
            optionString += 'toolbar='+defaultOptions.tools;
            // alert(optionString);

            ModalWindow.popup = window.open(url, 'ModalWindow', optionString);

            if (window.addEventListener) {
                window.addEventListener('unload', ModalWindow.hide, true);
            } else if (window.attachEvent) {
                window.attachEvent('unload', ModalWindow.hide);
            }
            setTimeout(ModalWindow.check, 800); 
        }
    }
}

function JimdoSigninWindow(callback, url)
{
    if (JimdoSigninWindow._instance) {
        return JimdoSigninWindow._instance;
    }

    if (window.webserver) {
        this.popupLocation = window.webserver+'app/auth/signin/';
    } else {
        this.popupLocation = 'app/auth/signin/index.html';
    }

    if (url) {
        this.popupLocation += '?claimed_identifier=' + url;
    }

    this.callback = callback;

    this.show = function() {
        var options = {
            width: 544,
            height: 330
        };

        ModalWindow.show(
            this.popupLocation,
            options, this.callback
        );
    }

    JimdoSigninWindow._instance = this;
    return JimdoSigninWindow._instance;
}

// Signin Window
function OldJimdoSigninWindow(callback, url)
{
    if (JimdoSigninWindow._instance) {
        return JimdoSigninWindow._instance;
    }

    if (window.webserver) {
        this.popupLocation = window.webserver+'app/auth/signin/';
    } else {
        this.popupLocation = 'app/auth/signin/index.html';
    }
    
    if (url) {
    	this.popupLocation += '?claimed_identifier=' + url;
    }

    this.callback = callback;
    // this.popup = null;

    this.hide = function() {

        if ('undefined' != typeof(this.popup)) {
            this.popup.close();
            delete this.popup;
        }
    }

    this.checkClosed = function() {

        var recheck = true;
        try {
           recheck = !this.popup.closed;
        } catch (e) {
           //
        }

        if (recheck) {
            setTimeout('JimdoSigninWindow().checkClosed();', 800);
            return;
        }

		delete this.popup;
		this.callback();
    }

    this.show = function() {
        if ('undefined' != typeof(this.popup)) {
            this.popup.focus();
            return true;
        }

        this.popup = window.open(this.popupLocation,'JimdoSigninWindow','width=550,height=330,titlebar=yes,menubar=no,location=yes,scrollbars=yes,status=yes,resizable=yes');

		setTimeout('JimdoSigninWindow().checkClosed();', 600);

		// IE suxx

		if (window.addEventListener){
			window.addEventListener(
				'unload', function() {JimdoSigninWindow().hide();}, true); 
		}
		else if (window.attachEvent){
			window.attachEvent(
				'unload', function() {JimdoSigninWindow().hide();});
		}

    }

    JimdoSigninWindow._instance = this;
    return JimdoSigninWindow._instance;
}

// XSS XHR
function JimdoXAjaxRequest()
{
    JimdoXAjaxRequest._instances.push(this);
    for (i=0; i<JimdoXAjaxRequest._instances.length; i++) {
        if (this == JimdoXAjaxRequest._instances[i]) {
            this._instanceId = i;
            break;
        }
    }
}
JimdoXAjaxRequest._instances = [];
JimdoXAjaxRequest.response = function(res) {
    if (('undefined' != typeof(res._id)) && ('' != res._id.toString())) {
        if (('undefined' != typeof(JimdoXAjaxRequest._instances[res._id])) &&
            (null != JimdoXAjaxRequest._instances[res._id])) {

            JimdoXAjaxRequest._instances[res._id]._response = res;

            // work around for broken safari versions
            var uas = navigator.userAgent;
            var uav = parseInt(uas.substr(uas.indexOf('WebKit')+7, 7));
            if (Prototype.Browser.WebKit && (uav < 523)) {

                document.getElementsByTagName('head')[0].removeChild(
                    JimdoXAjaxRequest._instances[res._id]._scriptNode
                );
                JimdoXAjaxRequest._instances[res._id].onreadystatechange(res)
                JimdoXAjaxRequest._instances[res._id] = null;
            }
        }
        else {
            alert('request assignment error');
        }
    }
}
JimdoXAjaxRequest._dispatch = function(req) {
    document.getElementsByTagName('head')[0].removeChild(req._scriptNode);
    if ('undefined' != typeof(req.onreadystatechange)) {
        req.onreadystatechange(req._response);
    }
    else {
        alert('no callback error');
    }
    JimdoXAjaxRequest._instances[req._instanceId] = null;
}
JimdoXAjaxRequest.prototype._instanceId = null;
JimdoXAjaxRequest.prototype._scriptNode = null;
JimdoXAjaxRequest.prototype._response   = null;
JimdoXAjaxRequest.prototype.open = function(serviceUrl)
{
    serviceUrl += (serviceUrl.indexOf('?') > 0 ? '&' : '?') + '_requestId=' + this._instanceId;

    this._scriptNode = document.createElement('script');

    this._scriptNode.request = this;
    this._scriptNode.type    = 'text/javascript';
    this._scriptNode.onload  = function() {JimdoXAjaxRequest._dispatch(this.request);}

    this._scriptNode.onreadystatechange = function() {
        if ((this.readyState == 'complete') || (this.readyState == 'loaded')) {
            JimdoXAjaxRequest._dispatch(this.request);
        }
    }
    this._scriptNode.src  = serviceUrl;

    document.getElementsByTagName('head')[0].appendChild(this._scriptNode);
}

var XSAjax = {
    Request: function(url, options) {

		if ('undefined', typeof(options.requestHeaders)) {
		    options.requestHeaders = {};
        }
        options.requestHeaders['X-Requested-With'] = 'Jimdo XS XMLHttpRequest';
        options.method = 'post';

        var callback = options.onSuccess;
        options.onSuccess = function(t) {
            var res = t.responseText.evalJSON();

            var req = new JimdoXAjaxRequest();
            req.onreadystatechange = callback;            
            req.open(res.pullUrl);
        }
        return new Ajax.Request(url, options);
    }
}

// Captcha
function changeCaptcha(captchaId) {
    var time = new Date();
    
    $('captchaImage' + captchaId).src = window.webserver + 'app/default/captcha/index/captchaId/' + captchaId + '/t/' + time.getTime();
}