//namespacing
Account={};

Account.Prices = {
	/**
     * where to send the data via ajax
     *
     * @param string
     */
    requestUrl:  '/account/priceupdate',

    lastRequestSuccessful: false,

    lastRequestUrl: null,

    /**
     * html id of the feedback div
     */
    statusId: 'cbPricesFB',

    sendData: function()
    {
        var ekCB = document.getElementById('ek');
        var val  = (ekCB.checked) ? 1 : 0;
        var doSubmit   = false;
        var statusText = '';
        this.sendFormData(val);
    },

    sendFormData: function(ek)
    {
        Account.Prices.setStatus(Account.Prices.Status.SENDING_DATA, 'success');
        //building up ajax url
        var requestUrl = this.requestUrl + '?ek=' + ek + '&ekSent=true';

        //last request is identic to current - and last request was successful.
        //so why send it again? no mailspam for CustomerSupport
        if(this.lastRequestSuccessful && this.lastRequestUrl == requestUrl)
        {
            this.setStatusInterval(Account.Prices.Status.ALREADY_SENT, 'error');
        }
        //nothing sended until now - send it
        else
        {
            Account.Prices.lastRequestSuccessful = false;
            this.lastRequestUrl = requestUrl;
            var request = YAHOO.util.Connect.asyncRequest('GET', requestUrl, Account.Prices.UpdateCallback );
        }
    },

    /**
     * setting Status message for defined time of 5 seconds
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
    setStatusInterval: function(msg, type)
    {
        this.setStatus(msg, type);
        this.statusInterval = setInterval("Account.Prices.clearStatus()", 5000);
    },

    /**
     * setting status forever - if interval is set - clear this
     * setting css classes for error and success
     * @todo - this has to be moved to another generic structure (no form crap)
     *
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
    setStatus: function(msg, type)
    {
        if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
        if(type == 'error')
        {
            Emv.Effects.removeClassName(this.statusId, 'success');
            Emv.Effects.addClassName(this.statusId, 'error');
        }
        else
        {
            Emv.Effects.removeClassName(this.statusId, 'error');
            Emv.Effects.addClassName(this.statusId, 'success');
        }
        var st = document.getElementById(this.statusId);
        st.style.visibility = 'visible';
        st.style.display    = 'block';
        st.innerHTML = msg;
    },

    /**
     * clear current Status message
     * if an interval is set, also clear this
     *
     */
    clearStatus: function()
    {
        var st = document.getElementById(this.statusId);
        st.innerHTML = '';
        st.style.visibility = 'hidden';
        st.style.display    = 'none';
        if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
    }
};

/**
 * callback object for priceupdate action
 * writing status messages, and setting lastRequestSuccessful flag to account.addresses
 */
Account.Prices.UpdateCallback = {

    /**
     * Yui connection success.
     *
     * @param object o
     */
    success: function(o) {
        var respText = o.responseText.substring(o.responseText.indexOf('{'), o.responseText.lastIndexOf('}') + 1);
        var resp = eval('(' + respText+ ')');
        if(resp.success)
        {
            Account.Prices.setStatusInterval(Account.Prices.Status.SUCCESS, 'success');
            Account.Prices.lastRequestSuccessful = true;
        }
        else
        {
            if('undefined' != typeof(resp.statusMsg))
            {
                err = resp.statusMsg;
            }
            else
            {
                err = Account.Prices.Status.FORM_ERROR;
            }
            Account.Prices.setStatusInterval(err, 'error');
            Account.Prices.lastRequestSuccessful = false;
        }
    },

    /**
     * Yui connection failed.
     */
    failure: function() {
        Account.Prices.setStatusInterval(Account.Prices.Status.CONNECTION_FAILED, 'error');
    },

    argument: [ this ]
};

Account.Prices.Status = {
	SENDING_DATA:   'sende Daten',
	FORM_ERROR:     'Fehler im Formular',
    SUCCESS:        'Ihre Daten wurden erfolgreich gespeichert',
    CONNECTION_FAILED: 'Übertragungfehler',
    ALREADY_SENT: 'Ihre &Auml;nderung wurde bereits gespeichert.'
};

Account.Email = {
    formVisible: false,

    /**
     * html id of the feedback div
     */
    statusId: 'FeedbackBox',
    /**
     * storage of the interval object  -is used for fading it out (if info is not that important)
     */
    statusInterval: null,

    /**
     * where to send the data via ajax
     *
     * @param string
     */
    requestUrl:  '/account/emailupdate',

    lastRequestSuccessful: false,

    sendData: function()
    {
        var oldMail    = document.getElementById('oldMail');
        var newMail    = document.getElementById('newMail');

        var doSubmit  = false;
        var statusText = '';

        if(oldMail.value.trim() == '')
        {
            statusText = 'Bitten geben Sie Ihre altes E-Mail-Adresse an.';
        }
        else if(!this.validateEmail(oldMail.value.trim()))
        {
            statusText = 'Ihre alte E-Mail-Adresse ungültig';
        }
        else if(newMail.value.trim() == '')
        {
            statusText = 'Bitte geben Sie Ihre neue E-Mail-Adresse an.';
        }
        else if(!this.validateEmail(newMail.value.trim()))
        {
            statusText = 'Ihre neue E-Mail-Adresse ungültig.';
        }
        else
        {
            doSubmit=true;
        }
        if(doSubmit)
        {
            this.sendFormData(oldMail.value.trim(), newMail.value.trim());
        }
        else
        {
            this.setStatusInterval(statusText, 'error');
        }
    },

    sendFormData: function(oldmail, newmail)
    {
        Account.Email.setStatus(Account.Email.Status.SENDING_DATA, 'success');
        //building up ajax url
        var requestUrl = this.requestUrl + '?oldEmail=' + oldmail +'&newEmail=' + newmail + '&emailSent=true';
        //collect elements

        //last request is identic to current - and last request was successful.
        //so why send it again? no mailspam for CustomerSupport
        if(this.lastRequestSuccessful && this.lastRequestUrl == requestUrl)
        {
            this.setStatus(Account.Email.Status.ALREADY_SENT, 'error');
        }
        //nothing sended until now - send it
        else
        {
            Account.Email.lastRequestSuccessful = false;
            this.lastRequestUrl = requestUrl;
            var request = YAHOO.util.Connect.asyncRequest('GET', requestUrl, Account.Email.UpdateCallback );
        }
    },

    /**
     * validates given string to e-mail-format
     * @param string - email?
     *
     * @return boolean - is email
     *
     */
    validateEmail: function(elementValue)
    {
       var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/;
       return emailPattern.test(elementValue);
    },

    /**
     * called after successful email update
     * assigning new email to form
     */
    assignNewMail: function()
    {
        var newM = document.getElementById('newMail');
        var oldM = document.getElementById('oldMail');
        oldM.value = newM.value;
        newM.value = '';
    },

    /**
     * setting Status message for defined time of 5 seconds
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
    setStatusInterval: function(msg, type)
    {
        this.setStatus(msg, type);
        this.statusInterval = setInterval("Account.Email.clearStatus()", 5000);
    },

    /**
     * setting status forever - if interval is set - clear this
     * setting css classes for error and success
     * @todo - this has to be moved to another generic structure (no form crap)
     *
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
    setStatus: function(msg, type)
    {
        if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
        if(type == 'error')
        {
            Emv.Effects.removeClassName(this.statusId, 'green');
            Emv.Effects.addClassName(this.statusId, 'red');
        }
        else
        {
            Emv.Effects.removeClassName(this.statusId, 'red');
            Emv.Effects.addClassName(this.statusId, 'green');
        }
        var st = document.getElementById(this.statusId);
        st.style.visibility = 'visible';
        st.style.display    = 'block';
        st.innerHTML = msg;
    },

    /**
     * clear current Status message
     * if an interval is set, also clear this
     *
     */
    clearStatus: function()
    {
        var st = document.getElementById(this.statusId);
        st.innerHTML = '';
        st.style.visibility = 'hidden';
        st.style.display    = 'none';
        if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
    }
};

/**
 * callback object for Addressupdate action
 * writing status messages, and setting lastRequestSuccessful flag to account.addresses
 */
Account.Email.UpdateCallback = {

    /**
     * Yui connection success.
     *
     * @param object o
     */
    success: function(o) {
        var respText = o.responseText.substring(o.responseText.indexOf('{'), o.responseText.lastIndexOf('}') + 1);
        var resp = eval('(' + respText+ ')');
        if(resp.success)
        {
            Account.Email.setStatusInterval(Account.Email.Status.SUCCESS, 'success');
            Account.Email.lastRequestSuccessful = true;
            Account.Email.assignNewMail();
        }
        else
        {
            if('undefined' != typeof(resp.statusMsg))
            {
                err = resp.statusMsg;
            }
            else
            {
                err = Account.Password.Status.FORM_ERROR;
            }
            Account.Email.setStatusInterval(err, 'error');
            Account.Email.lastRequestSuccessful = false;
        }
    },

    /**
     * Yui connection failed.
     */
    failure: function() {
        Account.Email.setStatusInterval(Account.Email.Status.CONNECTION_FAILED, 'error');
    },

    argument: [ this ]
};

/**
 * status texts for all possible feedback messages
 */
Account.Email.Status = {
    CONNECTION_FAILED: 'Fehler bei der Übertragung.<br />Bitte versuchen Sie es erneut.',
    FORM_ERROR_FIELDS: 'Fehler in folgenden Feldern: ', //followed by  a list of not correct filled fields
    FORM_ERROR:        'Fehler im Formular',
    SENDING_DATA:      'sende Daten',
    SUCCESS:           'Ihre Daten wurden erfolgreich gespeichert.',
    ALREADY_SENT:      'Das Formular wurde bereits erfolgreich übertragen.'
};

Account.Password = {
	formVisible: false,

    /**
     * html id of the feedback div
     */
    statusId: 'FeedbackBoxPanel',
    /**
     * storage of the interval object  -is used for fading it out (if info is not that important)
     */
    statusInterval: null,

    /**
     * where to send the data via ajax
     *
     * @param string
     */
    requestUrl:  '/account/passwordupdate',

    lastRequestSuccessful: false,


	toggleForm: function()
	{
		var stars = document.getElementById('password_stars');
		var form  = document.getElementById('password_form');
		if(this.formVisible)
		{
			stars.style.display = 'block';
            stars.style.visibility = 'visible';

            form.style.display = 'none';
            form.style.visibility = 'hidden';
		}
		else
		{

            //hide stars
            stars.style.display = 'none';
            stars.style.visibility = 'hidden';

            //show form
            form.style.display = 'block';
            form.style.visibility = 'visible';
		}
		this.formVisible = !this.formVisible;
	},

	hideForm: function()
	{
        if(this.formVisible)
        {
			var stars = document.getElementById('password_stars');
	        var form  = document.getElementById('password_form');
            stars.style.display = 'block';
            stars.style.visibility = 'visible';

            form.style.display = 'none';
            form.style.visibility = 'hidden';
            this.formVisible = false;
        }
	},

	sendData: function()
	{
		var oldPw     = document.getElementById('oldPassword');
		var newPw1    = document.getElementById('newPassword1');
		var newPw2    = document.getElementById('newPassword2');
		var doSubmit  = false;
		var statusText = '';

		if(oldPw.value.trim() == '')
		{
			statusText = 'Bitten geben Sie Ihr altes Passwort an.';
		}
		else if(newPw1.value.trim() == '' || newPw1.value.trim() != newPw2.value.trim())
		{
			statusText = 'Die neuen Passworte müssen ausgefüllt sein und übereinstimmen';
		}
		else if(newPw1.value.trim().length < 4 || newPw1.value.trim().length > 8)
        {
            statusText = 'Ihr Passwort muss von 4 bis 8 Zeichen lang sein.';
        }
		else
		{
			doSubmit=true;
		}
		if(doSubmit)
		{
			this.sendFormData(oldPw.value.trim(), newPw1.value.trim(), newPw2.value.trim());
		}
		else
		{
			this.setStatusInterval(statusText, 'error');
		}
	},

	sendFormData: function(old, new1, new2)
    {
        Account.Password.setStatus(Account.Addresses.Status.SENDING_DATA, 'success');
        //building up ajax url
        var requestUrl = this.requestUrl + '?oldPassword=' + old +'&newPassword1=' + new1 +'&newPassword2=' + new2  + '&pwUpSent=true';
        //collect elements

        //last request is identic to current - and last request was successful.
        //so why send it again? no mailspam for CustomerSupport
        if(this.lastRequestSuccessful && this.lastRequestUrl == requestUrl)
        {
            this.setStatus(Account.Password.Status.ALREADY_SENT, 'error');
        }
        //nothing sended until now - send it
        else
        {
            Account.Password.lastRequestSuccessful = false;
            this.lastRequestUrl = requestUrl;
            var request = YAHOO.util.Connect.asyncRequest('GET', requestUrl, Account.Password.UpdateCallback );
        }
    },

	/**
     * setting Status message for defined time of 5 seconds
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
    setStatusInterval: function(msg, type)
    {
        this.setStatus(msg, type);
        this.statusInterval = setInterval("Account.Password.clearStatus()", 5000);
    },

    /**
     * setting status forever - if interval is set - clear this
     * setting css classes for error and success
     * @todo - this has to be moved to another generic structure (no form crap)
     *
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
    setStatus: function(msg, type)
    {
        if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
        if(type == 'error')
        {
            Emv.Effects.removeClassName(this.statusId, 'green');
            Emv.Effects.addClassName(this.statusId, 'red');
        }
        else
        {
            Emv.Effects.removeClassName(this.statusId, 'red');
            Emv.Effects.addClassName(this.statusId, 'green');
        }
        var st = document.getElementById(this.statusId);
        st.style.visibility = 'visible';
        st.style.display    = 'block';
        st.innerHTML = msg;
    },

    /**
     * clear current Status message
     * if an interval is set, also clear this
     *
     */
    clearStatus: function()
    {
        var st = document.getElementById(this.statusId);
        st.innerHTML = '';
        st.style.visibility = 'hidden';
        st.style.display    = 'none';
        if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
    }
};

/**
 * callback object for Addressupdate action
 * writing status messages, and setting lastRequestSuccessful flag to account.addresses
 */
Account.Password.UpdateCallback = {

    /**
     * Yui connection success.
     *
     * @param object o
     */
    success: function(o) {
        var respText = o.responseText.substring(o.responseText.indexOf('{'), o.responseText.lastIndexOf('}') + 1);
        var resp = eval('(' + respText+ ')');
        if(resp.success)
        {
            Account.Password.setStatusInterval(Account.Password.Status.SUCCESS, 'success');
            Account.Password.lastRequestSuccessful = true;
            Account.Password.hideForm();
            var oldPw     = document.getElementById('oldPassword');
	        var newPw1    = document.getElementById('newPassword1');
	        var newPw2    = document.getElementById('newPassword2');
	        oldPw.value = '';
	        newPw1.value = '';
	        newPw2.value = '';
        }
        else
        {
        	if('undefined' != typeof(resp.statusMsg))
        	{
        		err = resp.statusMsg;
        	}
        	else
        	{
        		err = Account.Password.Status.FORM_ERROR;
        	}
            Account.Password.setStatusInterval(err, 'error');
            Account.Password.lastRequestSuccessful = false;
        }
    },

    /**
     * Yui connection failed.
     */
    failure: function() {
        Account.Password.setStatusInterval(Account.Password.Status.CONNECTION_FAILED, 'error');
    },

    argument: [ this ]
};

/**
 * status texts for all possible feedback messages
 */
Account.Password.Status = {
    CONNECTION_FAILED: 'Fehler bei der Übertragung.<br />Bitte versuchen Sie es erneut.',
    FORM_ERROR_FIELDS: 'Fehler in folgenden Feldern: ', //followed by  a list of not correct filled fields
    FORM_ERROR:        'Fehler im Formular',
    SENDING_DATA:      'sende Daten',
    SUCCESS:           'Ihre Daten wurden erfolgreich gespeichert.',
    ALREADY_SENT:      'Das Formular wurde bereits erfolgreich übertragen.'
};

Account.Services = {
	/**
	 * 4 inputs for 1 email
	 * to avoid too much trouble - this function is called onBlur and sets all inputs
	 * to last value
	 * @param int nr - currently updated field - to select value from
	 */
	updateFormfields: function(nr)
	{
	    var idprefix = 'mobileNr';
	    var cElem = document.getElementById(idprefix + nr);
	    var num = cElem.value;
	    for (var i = 1; i<=4; i++)
	    {
	        if(i != nr)
	        {
	            var elem = document.getElementById(idprefix + i);
	            if(elem)
	            {
	                elem.value = num;
	            }
	        }
	    }
	    //update hiddenfield -
	    var elem = document.getElementById(idprefix);
	    if(elem)
	    {
	        elem.value = num;
	    }
	}
};

/**
 * @todo - move to account.js namespace emv.mediabiz f.e.
 */
Account.Upselling = {
    blockId: 'upsellingBox',
    
    resize: function() {
	
	    // Calculate the new paper height on upselling box top style, height and content Y position.
	    // Set upsellingBox css style to top and substract 200 here, to avoid invalid position if moving via JS failes.
	    var contentBoxY   = YAHOO.util.Dom.getY('content');
	    var upsellingBox  = YAHOO.util.Dom.get('upsellingBox');
	    var upsellingBoxY = (contentBoxY + parseInt(YAHOO.util.Dom.getStyle('upsellingBox', 'top').substr(0, 3)) - 200);
	    var paperHeight   = upsellingBox.offsetHeight + upsellingBoxY - YAHOO.util.Dom.get('container_fs').offsetHeight;

	    YAHOO.util.Dom.setStyle(upsellingBox, 'top', upsellingBoxY + 'px');
	    YAHOO.util.Dom.setStyle('paper', 'height', paperHeight + 'px');
	},

    show: function() {
		
        var elem = document.getElementById(this.blockId);
        elem.style.display    = 'block';
        elem.style.visibility = 'visible';

        Account.Upselling.resize();
    },

    hide: function() {
    	
        var elem = document.getElementById(this.blockId);
        elem.style.display    = 'none';
        elem.style.visibility = 'hidden';
        
        YAHOO.util.Dom.setStyle('paper', 'height', 'auto');
    }
};

/**
 * handling of the address form for customer abos
 * @todo - move formhandling to a new Emv.Form class Structure
 * @todo - use Objects instead of ids (for email, numeric, text validation ...)
 * @todo - complex structures for (at least one - or maybe one field has to be set | see objects in mandatoryIDs)
 */
Account.Addresses = {
	/**
	 * two different types of objects could be stored in hered
	 * {id: '', title:} simple object (html id and title-value for error msgs)
	 * {title: '', prefix: '', values: array) for multiple checkboxes x_1, x_2, x_3 (x_ is prefix, values are{1, 2, 3}
	 *
	 * @todo move to a class structure - do not keep those crappy object thing
	 *
	 * @param array
	 */
	mandatoryIDs: new Array({id: 'email', title: 'E-Mail-Adresse'}, {id: 'strasse', title: 'Stra&szlig;e'}, {id: 'plz', title: 'Postleitzahl'}, {id: 'ort', title: 'Ort'}, {id: 'land', titel: 'Land'}, {id: 'telefonnummer', title: 'Telefonnummer'}, {title: 'Anschrift', prefix: 'anschrift_', values: new Array('lieferung', 'rechnung')}, {title: 'Abonnement', prefix: 'abo_', values: new Array(1, 105, 110, 120, 130, 205, 210, 220, 230, 310, 320, 330, 410, 420, 430)}),

	/**
	 * html-ids for all optional fields
	 */
	optionalIDs: new Array('firma', 'anrede', 'vorname', 'name', 'faxnummer'),

	/**
	 * html id of the feedback div
	 */
    statusId: 'FeedbackBoxPanel',
    /**
     * storage of the interval object  -is used for fading it out (if info is not that important)
     */
    statusInterval: null,

    /**
     * where to send the data via ajax
     *
     * @param string
     */
    requestUrl:  '/account/addressupdate',

    /**
     * keeping last request full url
     * to avoid duplicate form sends
     *
     * @param string
     */
    lastRequestUrl: null,

    /**
     * checking, if last request was a success.
     * also used to avoid double form submits
     *
     * @param boolean
     */
    lastRequestSuccessful: false,

    /**
     * entry point - is called onsubmit from html template
     * walking mandatory array an call validation for those fields
     */
	sendData: function()
	{
		var formValid = true;
		var invalidFields = new Array();
		for(var i=0; i<this.mandatoryIDs.length; i++)
		{
			var curr = this.mandatoryIDs[i];
			var elValid = true;

			//not just html -ids handling objects
			if(typeof(curr) == 'object')
			{
				//simple title/id object
				if('undefined' != typeof(curr.id))
				{
					var cel = document.getElementById(curr.id);
		            if(cel)
		            {
		                elValid = Account.Addresses.validateInput(cel);
		            }
		            if(!elValid)
		            {
		                invalidFields[invalidFields.length] = curr.title;
		                formValid = false;
		            }
				}
				//multiple html-id objects (f.e. Abonnements, Anschriften)
				else
				{
	                var prefix = curr.prefix;
	                var postfixes = curr.values;
	                var oneOfItValid = false;
	                //walking postfixes array and check all forms
	                for (j = 0; j < postfixes.length; j++)
	                {
		                var groupElValid = false;
	                	var postfix = postfixes[j];
	                	var el = prefix + postfix;
	                	var cel = document.getElementById(el);

	                	//cbs  hasn't to be there - just those abos the user has subscribed
	                	if(cel)
	                    {
	                        groupElValid = this.validateInput(cel);
	                    }
	                    if(groupElValid)
	                    {
	                    	oneOfItValid = true;
	                    }
	                }

	                //none of the group checkboxes is set - form isn't valid
	                if(!oneOfItValid)
	                {
	                	invalidFields[invalidFields.length] = curr.title;
	                    formValid = false;
	                }
				}
			}
			//simple html id walk... no longer used for mandatorys but maybe for
			// a planned emv.forms structure
			/*else
			{
				var cel = document.getElementById(curr);
				if(cel)
				{
				    elValid = Account.Addresses.validateInput(cel);
				}
				if(!elValid)
                {
                    invalidFields[invalidFields.length] = curr;
                    formValid = false;
                }
			}*/
		}

		//all mandatory fields are set - do the ajax
		if(formValid)
		{
			this.sendFormData();
		}
		//form invalid - show errors (comma separated)
		else
		{
			var msg = '';
			for(k = 0; k < invalidFields.length; k++)
			{
				if(k > 0 )
				{
					msg += ', ';
				}
				msg += invalidFields[k] ;
			}
			msg = Account.Addresses.Status.FORM_ERROR_FIELDS + msg;
			this.setStatus( msg, 'error');
		}
	},

    /**
     * building up reuqest url an send data
     */
    sendFormData: function()
    {
    	Account.Addresses.setStatus(Account.Addresses.Status.SENDING_DATA, 'success');
    	var mandatory = this.getRequestStringForArray(this.mandatoryIDs);
    	var optional  = this.getRequestStringForArray(this.optionalIDs);
    	//building up ajax url
        var requestUrl = this.requestUrl + '?' + mandatory + "&" + optional + '&billingSent=true';
        //collect elements

        //last request is identic to current - and last request was successful.
        //so why send it again? no mailspam for CustomerSupport
        if(this.lastRequestSuccessful && this.lastRequestUrl == requestUrl)
        {
        	this.setStatus(Account.Addresses.Status.ALREADY_SENT, 'error');
        }
        //nothing sended until now - send it
        else
        {
	        Account.Addresses.lastRequestSuccessful = false;
	        this.lastRequestUrl = requestUrl;
	        var request = YAHOO.util.Connect.asyncRequest('GET', requestUrl, Account.Addresses.UpdateCallback );
        }
    },

    /**
     * preformat a string for request url from given array
     *
     * @param Array with obects as desrciped in this.mandatoryIDs doc block
     *
     * @return String - key=value&k2=v2&....
     */
    getRequestStringForArray: function(arr)
    {
    	var ret = '';
    	for(var i=0; i<arr.length; i++)
        {

        	if(i > 0)
        	{
        		ret += '&';
        	}

            var curr = arr[i];
            if(typeof(curr) == 'object')
            {
            	if('undefined' != typeof(curr.id))
                {
                    var cel = document.getElementById(curr.id);
	                if(cel)
	                {
	                    ret +=  cel.name + "=" + this.getRequestValueForElem(cel);
	                }
                }
                else
                {
	                var prefix = curr.prefix;
	                var postfixes = curr.values;
	                var k=0;
	                for (j = 0; j < postfixes.length; j++)
	                {
	                	var postfix = postfixes[j];
	                    var el = prefix + postfix;
	                    var cel = document.getElementById(el);
	                    if(cel)
	                    {
	                    	if(k > 0)
		                    {
		                        ret += '&';
		                    }
	                        k++;
	                    	ret +=  cel.name + "=" + this.getRequestValueForElem(cel);
	                    }
	                }
                }
            }
            else
            {
                var cel = document.getElementById(curr);
                if(cel)
	            {
	                ret +=  cel.name + "=" + this.getRequestValueForElem(cel);
	            }
            }
        }
        return ret;
    },

    /**
     * get clean values for Request String
     * called from {@see Account.Addresses.getRequestStringForArray}
     * primary format checkbox values
     *
     * @param dom element
     * @return string - value to append to request url
     */
    getRequestValueForElem: function(elem)
    {
    	var ret = '';
    	if(elem.type == 'text')
        {
            ret = elem.value;
        }
        else if(elem.type == 'checkbox')
        {
            if(elem.checked)
            {
            	ret = elem.value;
            }
            else
            {
            	ret = '0';
            }
        }
        else if(elem.tagName == 'select' || elem.tagName == 'SELECT')
        {
            ret = elem.value;
        }
        return ret;
    },

    /**
     * validate user input for given element
     *
     * @todo do this a little bit better for generic version ;) check all possible elements
     *
     * @param dom element
     * @return boolean - element valid
     */
	validateInput: function(elem)
	{
		if(elem.type == 'text')
		{
			if(elem.id == 'email')
			{
				return this.validateEmail(elem.value);
			}
			else if(elem.value.trim() != '')
			{
				return true;
			}
		}
		else if(elem.type == 'checkbox')
		{
			return elem.checked;
		}
		else if(elem.tagName == 'select' || elem.tagName == 'SELECT')
		{
			return true;
		}

		return false;
	},

	/**
	 * validates given string to e-mail-format
	 * @param string - email?
	 *
	 * @return boolean - is email
	 *
	 */
	validateEmail: function(elementValue)
	{
	   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/;
	   return emailPattern.test(elementValue);
	},

	/**
	 * setting Status message for defined time of 5 seconds
	 * @param string msg - statusMessage
	 * @param string type - type of message (only 'error' is handled all other are success)
	 */
	setStatusInterval: function(msg, type)
	{
		this.setStatus(msg, type);
		this.statusInterval = setInterval("Account.Addresses.clearStatus()", 5000);
	},

	/**
	 * setting status forever - if interval is set - clear this
	 * setting css classes for error and success
	 * @todo - this has to be moved to another generic structure (no form crap)
	 *
     * @param string msg - statusMessage
     * @param string type - type of message (only 'error' is handled all other are success)
     */
	setStatus: function(msg, type)
    {
    	if(this.statusInterval)
        {
            clearInterval(this.statusInterval);
        }
        if(type == 'error')
        {
        	Emv.Effects.removeClassName(this.statusId, 'green');
        	Emv.Effects.addClassName(this.statusId, 'red');
        }
        else
        {
        	Emv.Effects.removeClassName(this.statusId, 'red');
            Emv.Effects.addClassName(this.statusId, 'green');
        }
        var st = document.getElementById(this.statusId);
        st.style.visibility = 'visible';
        st.style.display    = 'block';
        st.innerHTML = msg;
    },

	/**
	 * clear current Status message
	 * if an interval is set, also clear this
	 *
	 */
	clearStatus: function()
	{
		var st = document.getElementById(this.statusId);
        st.innerHTML = '';
		st.style.visibility = 'hidden';
        st.style.display    = 'none';
		if(this.statusInterval)
		{
		    clearInterval(this.statusInterval);
		}
	}
};

/**
 * callback object for Addressupdate action
 * writing status messages, and setting lastRequestSuccessful flag to account.addresses
 */
Account.Addresses.UpdateCallback = {

    /**
     * Yui connection success.
     *
     * @param object o
     */
    success: function(o) {
    	var respText = o.responseText.substring(o.responseText.indexOf('{'), o.responseText.lastIndexOf('}') + 1);
        var resp = eval('(' + respText+ ')');
        if(resp.success)
        {
            Account.Addresses.setStatusInterval(Account.Addresses.Status.SUCCESS, 'success');
            Account.Addresses.lastRequestSuccessful = true;
        }
        else
        {
    	   Account.Addresses.setStatusInterval(Account.Addresses.Status.FORM_ERROR, 'error');
    	   Account.Addresses.lastRequestSuccessful = false;
        }
    },

    /**
     * Yui connection failed.
     */
    failure: function() {
        Account.Addresses.setStatusInterval(Account.Addresses.Status.CONNECTION_FAILED, 'error');
    },

    argument: [ this ]
};

/**
 * status texts for all possible feedback messages
 */
Account.Addresses.Status = {
	CONNECTION_FAILED: 'Fehler bei der Übertragung.<br />Bitte versuchen Sie es erneut.',
	FORM_ERROR:        'Fehler im Formular - bitte checken sie Ihre Eingaben.',
	FORM_ERROR_FIELDS: 'Fehler in folgenden Feldern: ', //followed by  a list of not correct filled fields
	SENDING_DATA:      'sende Daten',
	SUCCESS:           'Ihre Daten wurden erfolgreich an den Customer Service &uuml;bermittelt.',
	ALREADY_SENT:      'Das Formular wurde bereits erfolgreich übermittelt.'
};

//newsletter handler
Account.Newsletter = {
	interval: false,
	requestUrl:  '/account/newsletterupdate',

	/**
	 * update all setting for Newsletter Block. Additional Check, if a aboblock with newsletter cb is set
	 * an sync those checkboxes
	 */
	updateNewsletterSettings: function(cbId)
    {
		Account.Newsletter.setLoading();
		var requestUrl = this.requestUrl + '?';
		//collect elements
		requestUrl += 'mailpermiss=' + ((document.getElementById('acceptStuff').checked) ? 1 : 0);
		requestUrl += '&fiDaily='   + ((document.getElementById('fiDaily').checked) ? 1 : 0);
		requestUrl += '&eDaily='    + ((document.getElementById('eDaily').checked) ? 1 : 0);
		requestUrl += '&viDaily='   + ((document.getElementById('viDaily').checked) ? 1 : 0);
		requestUrl += '&gaDaily='   + ((document.getElementById('gaDaily').checked) ? 1 : 0);
		requestUrl += '&muDaily='   + ((document.getElementById('muDaily').checked) ? 1 : 0);
		requestUrl += '&liDaily='   + ((document.getElementById('liDaily').checked) ? 1 : 0);
		//check/uncheck possible remote Box from aboteaser
		var remoteId = cbId + '_remote';
		var remoteElem = document.getElementById(remoteId);
		if(remoteElem)
		{
			remoteElem.checked = document.getElementById(cbId).checked;
		}

        var request = YAHOO.util.Connect.asyncRequest('GET', requestUrl, Account.Newsletter.UpdateCallback );

    },

    setIcon: function(ico)
    {
    	var elem = document.getElementById('newsletterIcon');
    	if(elem)
		{
    		elem.src = ico;
		}
    },

    restoreIcon: function()
    {
    	Account.Newsletter.setIcon('/account/pics/abo/news.gif');
    	clearInterval(Account.Newsletter.interval);
    },

    setLoading: function()
    {
    	Account.Newsletter.setIcon('/_assets/pics/icons/nlupdate_loader.gif');
    },
    setSuccessful: function()
    {
    	Account.Newsletter.setIcon('/_assets/pics/icons/checked.png');
    	if(Account.Newsletter.interval)
    	{
    		clearInterval(Account.Newsletter.interval);
    	}
    	Account.Newsletter.interval = setInterval(Account.Newsletter.restoreIcon, 2000);
    },
    /**
     * this function handles remote checkboxes to check the newsletterblock checkboxes
     * and update settings
     *
     * @param checked element,
     * @param id of the element from Newsletter Box (has to be checked/unchecked too)
     */
    remoteSwitch: function(remoteElem, nlCbId)
    {
    	 var nlElem = document.getElementById(nlCbId);
    	 if(nlElem)
    	 {
    		 nlElem.checked = remoteElem.checked;
    		 Account.Newsletter.updateNewsletterSettings();
    	 }
    }
};

Account.Newsletter.UpdateCallback = {
	/**
	 * Yui connection success.
	 *
	 * @param object o
	 */
    success: function(o) {
		var resp = eval('(' + o.responseText+ ')');
		if('undefined' != typeof(resp))
		{
		  Account.Newsletter.setSuccessful();
		}
    },

    /**
     * Yui connection failed.
     */
    failure: function() {

    },

    argument: [ this ]
};