String.implement({
    /**
     * String.truncate(max, atChar, trail)
     *
     * ++All parameters are optional.
     * @param max = (integer) maximum length of truncated string. Defaults to 100 chars.
     * @param atChar = (string) truncate at the last index of this string. If not found, just truncates to max length.
     *                 If null, does not search and truncates to max length. Defaults to split at space.
     * @param trail = (string) what you want appended to the end of the returned string. Defaults to '...'
     *
     * @author Michael Fuery, Fuery Solutions, Inc. http://www.fuerysolutions.com/
     *
     * +Requires MooTools Core
     */
    truncate:function(max, atChar, trail){
        var s = this.trim();
        if(s.length<1) return '';
        if(!$defined(max)) var max = 100;
          else max = max.toInt();
        if(!$defined(atChar)) var atChar=' '; // break at space
          else if(atChar == null) var atChar=false;
        if(!$defined(trail)) var trail = '...';

        if(s.length > max) {
            s=s.slice(0,max);
            var i=0;
            if(atChar){
                if((i = s.lastIndexOf(atChar)) != -1){
                    s = s.substring(0, i);
                } else{
                    s = s.substring(0, max);
                }
            }

            s += trail;
        }

        return s;
    }
});

var Mobajl = Object();

Mobajl.Slider = new Class({
	initialize: function(action, currentpage) {
		if (typeof(action) == 'undefined') {
			action = 'home';
		}
		if (typeof(currentpage) == 'undefined') {
			currentpage = 1;
		}
		this.parts = {1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth'};
		this.action = action;
		this.currentpage = currentpage;
		this.container = $('contentinner');
		this.animating = false;
		this.pagewidth = parseInt($('content').getStyle('width'));
		this.margin = 20;
		this.sloganshown = false;
		this.sloganheight = 106;
		this.oncomplete = null;
		this.termsInit = false;
		this.currentslogan = 1;
		this.firstuntouched = true;
		this.swapcount = 0;
		this.toggleInputs();
		this.toggleVisible();
	},
    
	gotoPage: function(pagenr, oncomplete) {
		if (pagenr == this.currentpage) {
			
		} else {
			this.firstuntouched = false;
			if (typeof(oncomplete) == 'undefined' && typeof(this.oncomplete) != 'undefined') {
				oncomplete = this.oncomplete;
				this.oncomplete = null;
			}

			if (this.action == 'home' && this.pagenr != 1) {
				//$('selectedprizeoverlay').setStyle('display', 'none');
				if (this.sloganshown) {
					this.hideSlogan();
					if (!Browser.Engine.trident4) {
						this.oncomplete = oncomplete;
						this.gotoPage.delay(300, this, pagenr);
						return;
					}
				}
			}
			if (this.animating) {
				//this.oncomplete = oncomplete;
				//this.gotoPage.delay(100, this, pagenr, oncomplete);
				return;
			}
			this.lockAnimation();

			var from = 0-(this.currentpage-1)*(this.pagewidth+this.margin);
			var to = 0-(pagenr-1)*(this.pagewidth+this.margin);
			
			var myFx = new Fx.Tween(this.container, {
				property: 'left',
				duration: 1000,
				link: 'chain'
			});
			
			myFx.addEvent('complete', this.toggleVisible.bind(this));
			myFx.addEvent('complete', this.toggleInputs.bind(this));
			if (typeof(oncomplete) == 'function') {
				myFx.addEvent('complete', oncomplete);
			}
			
			if ((this.action == 'home') && !(pagenr == 1 && !this.sloganshown) || this.action != 'home') {
				myFx.addEvent('complete', this.unlockAnimation.bind(this));
			}
			if (this.action == 'home') {
				if (pagenr == 1 && !this.sloganshown) {
					myFx.addEvent('complete', this.showSlogan.bind(this));
					myFx.addEvent('complete', function(){
						$('selectedprizeoverlay').setStyle('display', 'block');
					});
				} else if (pagenr == 2) {
					if (!this.termsInit) {
						myFx.addEvent('complete', this.initTerms.bind(this));
					}
				}
				if (pagenr > 1) {
                    $('selectedprizeoverlay').setStyle('display', 'none');
				}
			}
			$(this.parts[pagenr]).setStyle('visibility', 'visible');
			if (Math.abs(this.currentpage-pagenr) == 2) {
				$(this.parts[2]).setStyle('visibility', 'visible');
			}
			myFx.start(from, to);
			this.currentpage = pagenr;
		}
	},
	
	next: function(oncomplete) {
		this.gotoPage(this.currentpage+1, oncomplete);
	},
	
	previous: function(oncomplete) {
		if (this.currentpage > 1) {
			this.gotoPage(this.currentpage - 1, oncomplete);
		}
	},

	toggleInputs: function() {
		for (var i in this.parts) {
			if (! $(this.parts[i])) continue; // Skip missing parts
			if (this.currentpage != i) {
				$(this.parts[i]).getElements('input').each(function(element){
					element.disabled = true;
				});
				$(this.parts[i]).getElements('select').each(function(element){
					element.disabled = true;
				});
			} else {
				$(this.parts[i]).getElements('input').each(function(element){
					element.disabled = false;
				});
				$(this.parts[i]).getElements('select').each(function(element){
					element.disabled = false;
				});
			}					
		}		
	},
	
	toggleVisible: function() {
		var parts = {1: 'first', 2: 'second', 3: 'third'};
		for (var i in this.parts) {
			if (! $(this.parts[i])) continue; // Skip missing parts
			if (this.currentpage != i) {
				$(this.parts[i]).setStyle('visibility', 'hidden');
			} else {
				$(this.parts[i]).setStyle('visibility', 'visible');
			}
		}		
	},

	lockAnimation: function() {
		this.animating = true;	
	},
	
	unlockAnimation: function() {
		this.animating = false;	
	},
	
	sloganOff: function() {
		this.sloganshown = false;	
	},
	
	sloganOn: function() {
		this.sloganshown = true;
	},

	showSlogan: function() {
	    return; // Disabled
		if (this.sloganshown || this.currentpage != 1) {
			return;
		}
		this.sloganOn();
		if (Browser.Engine.trident4) {
			var slogan = $('sloganoverlay'+this.currentslogan);
			if (slogan.getStyle('filter').length == 0) {
				var filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+slogan.getStyle('background-image').replace('url("', '').replace('")', '')+"', sizingMethod='image');";
				slogan.setStyle('background-image', 'none');
				slogan.setStyle('display', 'block');
				slogan.setStyle('filter', filter);
			} else {
				$('sloganoverlay'+this.currentslogan).setStyle('display', 'block');
			}
			this.unlockAnimation();
			if (this.firstuntouched) {
				this.hideSlogan.delay(5000, this);
				this.showSlogan.delay(5000, this);
			}
		} else {
			this.lockAnimation();
			var from = $('sloganoverlay'+this.currentslogan).getStyle('height');
			var to = this.sloganheight;
			var myFx = new Fx.Tween($('sloganoverlay'+this.currentslogan), {
				property: 'height',
				duration: 500,
				link: 'ignore'
			});
			myFx.addEvent('complete', this.unlockAnimation.bind(this));

			if (this.swapcount <2 && this.firstuntouched && this.currentpage == 1) {
				myFx.addEvent('complete', function(){
					slider.hideSlogan.delay(5000, slider);
				});
			}

			myFx.start(from, to);
		}
	}, 
	
	hideSlogan: function() {
		if (!this.sloganshown) {
			return;
		}
		this.sloganOff();
		if (Browser.Engine.trident4) {
			$('sloganoverlay1').setStyle('display', 'none');
			$('sloganoverlay2').setStyle('display', 'none');
		} else {
			var from = $('sloganoverlay'+this.currentslogan).getStyle('height');
			var to = 0;
			var myFx = new Fx.Tween($('sloganoverlay'+this.currentslogan), {
				property: 'height',
				duration: 500,
				link: 'ignore'
			});
			if (this.firstuntouched && this.swapcount < 2) {
				myFx.addEvent('complete', function(){
					slider.showSlogan.delay(1000, slider);
				});
				this.swapcount++;
			}

			myFx.start(from, to);
		}
		if (this.currentslogan == 1) {
			this.currentslogan = 2;
		} else {
			this.currentslogan = 1;
		}
		
	},
	
	initTerms: function() {
		this.termsInit = true;
	}
});

Mobajl.Selector = new Class({
	initialize: function() {
		this.selected = false;
		this.active = 0;
		this.activeimages = new Object();
		this.inactiveimages = new Object();
		this.activefilters = new Object();
		this.inactivefilters = new Object();
		this.marked = new Object();
		this.firsthover = false;
		this.bindElements();
	}, 
	
	bindElements: function() {
		for (var i = 1; i <= this.count; i++) {
			this.activeimages[i] = $(this.objectname+i+'marked');
			this.inactiveimages[i] = $(this.objectname+i+'unmarked');
			this.marked[i] = false;
			
			if (Browser.Engine.trident4) {
			} else {
				this.activeimages[i].fade('hide');
				this.activeimages[i].setStyle('visibility', 'visible');
			}			
			this.inactiveimages[i].selectionnr = i;
			this.inactiveimages[i].handler = this;
	
			this.inactiveimages[i].addEvent('mouseenter', function() {
				this.handler.hover(this.selectionnr);
			});
			this.inactiveimages[i].addEvent('mouseleave', function() {
				this.handler.leave(this.selectionnr);
			});
			this.inactiveimages[i].addEvent('click', function() {
				this.handler.select(this.selectionnr);
			});
		}
	},
	
	fadeIn: function(selectnr) {
		if (this.activeimages[selectnr]) {
			if (Browser.Engine.trident4) {
				if (typeof(this.inactivefilters[selectnr]) == 'undefined') {
					this.inactivefilters[selectnr] = this.inactiveimages[selectnr].getStyle('filter');
				}
				this.inactiveimages[selectnr].setStyle('filter', '');
				if (typeof(this.activefilters[selectnr]) == 'undefined') {
					this.activefilters[selectnr] = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.activeimages[selectnr].getStyle('background-image').replace('url("', '').replace('")', '')+"', sizingMethod='image');";
					this.activeimages[selectnr].setStyle('background-image', 'none');
				}
				this.activeimages[selectnr].setStyle('visibility', 'visible');
				this.activeimages[selectnr].setStyle('filter', this.activefilters[selectnr]);
			} else if (Browser.Engine.trident5) {
				this.activeimages[selectnr].fade('show');
			} else {
				this.activeimages[selectnr].fade('in');
			}
			this.marked[selectnr] = true;

			if (this.fadeInExtra) {
				this.fadeInExtra(selectnr);
			}
			
		}
	},

	fadeOut: function(selectnr) {
		if (this.activeimages[selectnr] && this.marked[selectnr]) {
			this.marked[selectnr] = false;
			if (Browser.Engine.trident4) {
				this.activefilters[selectnr] = this.activeimages[selectnr].getStyle('filter');
				this.activeimages[selectnr].setStyle('filter', '');
				if (typeof(this.inactivefilters[selectnr]) == 'undefined') {
					this.inactivefilters[selectnr] = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.inactiveimages[selectnr].getStyle('background-image').replace('url("', '').replace('")', '') + "', sizingMethod='image');";
				}
				this.inactiveimages[selectnr].setStyle('visibility', 'visible');
				this.inactiveimages[selectnr].setStyle('filter', this.inactivefilters[selectnr]);
			} else if (Browser.Engine.trident5) {
				this.activeimages[selectnr].fade('hide');
			} else {
				this.activeimages[selectnr].fade('out');
			}
			if (this.fadeOutExtra) {
				this.fadeOutExtra(selectnr);
			}
		}
	},
	
	hover: function(selectnr) {
		if (!this.firsthover) {
			this.firsthover = true;
		}
		for (var i = 1; i <= this.count; i++) {
			if (i == selectnr) {
				this.fadeIn(i);
			} else if (this.marked[i] && i != this.selected) {
				this.fadeOut(i);
			}
		}		
	},
	
	leave: function(selectnr) {
		if (this.marked[selectnr] && selectnr != this.selected) {
			this.fadeOut(selectnr);
		}
	},
	
	select: function(selectnr) {
		this.selected = selectnr;
		this.hover(selectnr);
		if (this.selectExtra) {
			this.selectExtra(selectnr);
		}
	},
	
	getSelection: function() {
		return this.selected;
	}
});

Mobajl.PrizeSelector = new Class({
	Extends: Mobajl.Selector,
	initialize: function() {
		this.objectname = "prize";
		this.count = 3;
		this.parent();
		this.loopprize = 0;
		this.loopcount = 0;
		this.prizeLoop();
		this.prizeNames = {
			1: alerts.prize1,
			2: alerts.prize2,
			3: alerts.prize3
		}
		this.overlayPositions = {
			1: [165, 163],
			2: [377, 40],
			3: [567, 40]
		};
		
		for (var i = 2; i <= 3; i++) {
			var container = $('selectedprizecontainer' + i);
			if (container) {
				container.getElement('a').addEvent('click', function(e) {
					slider.gotoPage(1);
					e.preventDefault();
				});
			}
		}		
	},
	
	prizeLoop: function() {
		if (!this.firsthover && this.loopcount < 21) {
			this.loopprize++;
			this.loopcount++;
			if (this.loopprize > this.count) {
				this.loopprize = 1;
			}
			for (var i = 1; i <= this.count; i++) {
				if (i == this.loopprize) {
					this.fadeIn(i);
				} else {
					this.fadeOut(i);
				}
			}
			this.prizeLoop.delay(2000, this);
		} else if (!this.firsthover) {
			this.fadeOut(this.loopprize);
		}
	},
	
	selectExtra: function(selectnr) {
		var position = this.overlayPositions[selectnr];
		var overlay = $('selectedprizeoverlay');
		overlay.setStyle('top', position[1]);
		overlay.setStyle('left', position[0]);
		var filter = false;
		if (Browser.Engine.trident4) {
			if (overlay.getStyle('background-image') != 'none') {
				filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+overlay.getStyle('background-image').replace('url("', '').replace('")', '')+"', sizingMethod='image');";
				overlay.setStyle('background-image', 'none');
			}
		}
		overlay.setStyle('display', 'block');
		if (filter) {
			overlay.setStyle('filter', filter);
		}
	},
	
	updateSelectedPrize: function() {
		for (var i = 2; i <= 3; i++) {
			var container = $('selectedprizecontainer'+i);
			if (container) {
				container.getElement('.prizename').set('html', this.prizeNames[this.selected]);
				var prizecontainer = container.getElement('.selectedprize');
				if (Browser.Engine.trident4) {
					prizecontainer.setStyle('background-image', 'none');
					prizecontainer.setStyle('filter', this.activefilters[this.selected].replace("marked", "mini"));
				} else {
					prizecontainer.setStyle('background-image', this.activeimages[this.selected].getStyle('background-image').replace("marked", "mini"));
				}
				if (this.selected == 2) {
					prizecontainer.setStyle('left', "-35px");
				} else {
					prizecontainer.setStyle('left', "-22px");
					
				}
			}
		}
	}
});

Mobajl.GenderSelector = new Class({
	Extends: Mobajl.Selector,
	initialize: function() {
		this.objectname = "gender";
		this.count = 2;
		this.parent();
		this.fadeOutExtra(1);
		this.fadeOutExtra(2);

		for (var i = 1; i <= 2; i++) {
			var desc = this.inactiveimages[i].getParent().getElement('p.description');
			desc.handler = this;
			desc.selectionnr = i;
			desc.addEvent('mouseenter', function(){
				this.handler.hover(this.selectionnr);
			});
			desc.addEvent('mouseleave', function(){
				this.handler.leave(this.selectionnr);
			});
			desc.addEvent('click', function(){
				this.handler.select(this.selectionnr);
			});
		}
	},
	
	fadeInExtra: function(selectnr) {
		if (Browser.Engine.trident4) {
			this.inactiveimages[selectnr].getParent().getElement('p.description').fade('show');
		} else {
			this.inactiveimages[selectnr].getParent().getElement('p.description').fade(1);
		}
	},
	
	fadeOutExtra: function(selectnr) {
		if (Browser.Engine.trident4) {
			this.inactiveimages[selectnr].getParent().getElement('p.description').get('tween', {property: 'opacity', duration: 0}).start(0.5);
		} else {
			this.inactiveimages[selectnr].getParent().getElement('p.description').fade(0.5);
		}	
	}

});

Mobajl.Splashes = new Class({
    enableBubbles: function() {
        $('splash').addEvent('mouseover', function(e) {
                if (Browser.Engine.trident) {
				$('splashinfo').show();
                } else {
				$('splashinfo').get('tween', {property: 'opacity', duration: 'long'}).start(1);
                }
            });
		$('splash').addEvent('mouseout', function() {
                if (Browser.Engine.trident) {
				$('splashinfo').hide();
                } else {
				$('splashinfo').get('tween', {property: 'opacity', duration: 'long'}).start(0);
                }
            });
        if ((lang == 'sv') || (lang == 'fi')) {
            $('cellinfo').addEvent('mouseover', function() {
                if (Browser.Engine.trident) {
                    $('cellinfomsg').show();
                } else {
                    $('cellinfomsg').get('tween', {property: 'opacity', duration: 'long'}).start(1);
                }
            });
            $('cellinfo').addEvent('mouseout', function() {
                if (Browser.Engine.trident) {
                    $('cellinfomsg').hide();
                } else {
                    $('cellinfomsg').get('tween', {property: 'opacity', duration: 'long'}).start(0);
                }
            });
            $('splash2').addEvent('mouseover', function(e) {
                if (Browser.Engine.trident) {
                    $('splashinfo2').show();
                } else {
                    $('splashinfo2').get('tween', {property: 'opacity', duration: 'long'}).start(1);
            }
            });
            $('splash2').addEvent('mouseout', function() {
                if (Browser.Engine.trident) {
                    $('splashinfo2').hide();
                } else {
                    $('splashinfo2').get('tween', {property: 'opacity', duration: 'long'}).start(0);
                }
            });
        }
    }
});

Mobajl.InvitePage = new Class({
	initialize: function(usercode, first) {
		if (typeof(first) == 'undefined') {
			this.first = false;
		} else {
			this.first = true;
		}
		this.styledElements = (typeof Custom == 'undefined') ? false : true;
		this.bindElements();
		this.initTerms();
		this.inviteContacts = {
            "online": {},
            "offline": {}
        };
        this.selectedCount = {
            'online': 0,
            'offline': 0
        }
        this.contactCount = {
            'online': 0,
            'offline': 0
        };
        this.allSelected = {
            'online': false,
            'offline': false
        };

		this.usercode = usercode;
		setGoal(2, 'step1');
	},
	
	bindElements: function() {
		try { /* Step 1 */
            $('invite1button').addEvent('click', this.step1.bind(this));
            $('invitelink').addEvent('focus', function(e) { this.select(); });
        } catch(e) {}
        
        /* Step 2 */
        $('invite2button').addEvent('click', this.step2.bind(this));
		$('inviteform').addEvent('submit', this.step2.bind(this));
		
		$('iusername').addEvent('keypress', this.listenToEnter.bind(this));
		$('ipassword').addEvent('keypress', this.listenToEnter.bind(this));
		$('contentinner').getElements('a.goback').each(function(element) {
			if (this.first && element.id != 'gobackthird' && element.id != 'gobackthird2') {
				element.addEvent('click', function() {
					window.location = pagelink;
				});
			} else {
                if (element.id == 'gobackthird2') {
                    element.addEvent('click', function() {
                        $('onlinecontacts').setStyle('display', 'block');
                        $('offlinecontacts').setStyle('display', 'none');
                        $$('#onlinecontacts > a.goback')[0].fireEvent('click');
                    });
                } else {
                    element.addEvent('click', slider.previous.bind(slider, function() {
                        if (slider.currentpage == 1) {
                            $('ad').show();
                        }
                    }));
                }
			}
		}, this);
        
        try { /* Step 3 */
            $('invite3button').addEvent('click', this.step3.bind(this));
            $('invite3button2').addEvent('click', this.step3.bind(this));
            
            if (Browser.Engine.trident) {
                $('copylinkbutton').addEvent('click', this.copyLinkToClipboard.bind(this));
            }
            $('toggleall').addEvent('click', this.toggleAll.bind(this));
            $('toggleall2').addEvent('click', this.toggleAll.bind(this));
        } catch(e) {}
	},
	
	listenToEnter: function(e) {
		if (e.key == 'enter') {
			this.step2();
			e.preventDefault();
		}
	},

	copyLinkToClipboard: function(e) {
		Clipboard.copy($('invitelink').value);

		$('invitelink').get('tween', {property: 'opacity', duration: 'long'}).start(0);
		$('copylinkbutton').set('html', alerts.copied);
		var afterlink = function(){
			$('invitelink').get('tween', {
				property: 'opacity',
				duration: 'long'
			}).start(1);

		};
		afterlink.delay(1000);

		var aftertext = function(){
			$('copylinkbutton').set('html', alerts.copy);
		};
		aftertext.delay(3000);

		if (e)
			e.preventDefault();	
	},
	
	step1: function() {
		slider.gotoPage(2, function() {
			if ($('iusername').value.length > 0) {
				$('ipassword').focus();
			} else {
				$('iusername').focus();
			}
			$('ad').hide();
		});
	},

	step2: function() {
		var errors = {};
		var formcheck = true;
/*		if ($('cba').value != 1) {
			errors.agree = alerts.agree;
			formcheck = false;
		}*/
		var focus = false;
		if ($('iusername').value.length == 0) {
			errors.username = alerts.email;
			formcheck = false;
			focus = 'iusername';
		}
		if ($('ipassword').value.length == 0) {
			errors.password = alerts.password;
			formcheck = false;
			if (!focus) {
				focus = 'ipassword';
			}
		}

		var status = new Mobajl.StatusIndicator(2);
		if (!formcheck) {
			status.flagErrors(errors, focus);
			if (typeof(e) != 'undefined')
				e.preventDefault();	
			return;
		}
		var form = $('inviteform');
		form.statusindicator = status;
		form.handler = this;
		form.set('send', {url: baseurl+'ajax/contacts', method: 'post',
 			onRequest: function(){
				$('inviteform').statusindicator.loading();
			},
			
			onSuccess: function() {
				var response = $('inviteform').get('send');
				var result = JSON.decode(response.response.text);
				if (result.success) {
					$('inviteform').statusindicator.good();
					$('inviteform').handler.contacts = result.contacts;
					$('inviteform').handler.onlineContacts = result.onlineContacts;
					if (result.onlineContacts.length == 0) {
                        if (result.contacts.length > 0) {
                            $('onlinecontacts').hide();
                            $('offlinecontacts').show();
                        }
                    }
					$('inviteform').handler.allSelected = {
                        'online': false,
                        'offline': false
                    };
					$('inviteform').handler.populateContacts();
					setGoal(2, 'step2');
                    slider.gotoPage(3);
					
				} else {
					$('inviteform').statusindicator.bad();
					$('inviteform').statusindicator.flagErrors(result.errors);
				}
			},

			onFailure: function() {
				$('inviteform').statusindicator.bad();
			}
		});
		form.send();
		if (typeof(e) != 'undefined')
			e.preventDefault();	
	},
	
	step3: function(e) {
		var invite = [];
		// This function is bound on two different forms
        var contactType = (e.target.id == 'invite3button') ? 'online' : 'offline';

		for (var i in this.inviteContacts[contactType]) {
            if (this.inviteContacts[contactType][i] == true) {
                invite.push(i);
            }
        }
		
		var status = new Mobajl.StatusIndicator(3);
		
        var jsonRequest = new Request.JSON({
            url: baseurl+"ajax/invite",
            onRequest: function(){
                this.statusindicator.loading();
            },

            onComplete: function(result){
                if (result.success) {
                    this.statusindicator.loadingDone();
                    if ((contactType == 'online') && ($$('#contactslist2 li').length > 0)) {
                        $('onlinecontacts').setStyle('display', 'none');
                        $('offlinecontacts').setStyle('display', 'block');
                    } else {
                        this.statusindicator.good();
                        setGoal(2, 'submit');
                        window.location = baseurl+"invite/"+this.handler.usercode;
                    }
                } else {
                    this.statusindicator.bad();
                    this.statusindicator.flagErrors(result.errors);
                }
            },

            onFailure: function() {
                this.statusindicator.bad();
            }

        });
        jsonRequest.statusindicator = status;
        jsonRequest.handler = this;
        jsonRequest.send("invite=" + invite + "&contactType=" + contactType);
	},
	
	checkLinkInput: function(e) {
		if (e.event.charCode == 0) {
			if (e.event.keyCode != 9 && !(e.event.keyCode >= 33 && e.event.keyCode <= 39)) {
				e.preventDefault();
				
			}
		} else {
			e.preventDefault();
		}
	},

	initTerms: function() {
		this.termsInit = true;
	},
	
	populateContacts: function() {
		this.contactCount = {
            'offline': 0,
            'online': 0
        };
		this.inviteContacts = {
            "offline": {},
            "online": {}
        };
        for (var listnr=1; listnr <= 2; listnr++) {
            var contacts, list, contactType;
            if (listnr == 1) {
                contactType = 'offline';
                contacts = this.contacts;
                list = $('contactslist2');
            } else {
                contactType = 'online';
                contacts = this.onlineContacts;
                list = $('contactslist');
            }
            if (contacts != undefined) {
                this.contactCount[contactType] = contacts.length;
                list.empty();
                for (var i=0; i < contacts.length; i++) {
                    var li = new Element('li');
                    li.appendChild(new Element('input').set({'type': 'checkbox'}));
                    //li.appendChild(new Element('div').addClass('contacticon'));
                    li.appendChild(new Element('label').addClass('contacticon').appendText((contacts[i].name+" - "+contacts[i].email).truncate(50)));
                    li.contactnr = i;
                    li.contactType = contactType;
                    li.handler = this;
                    list.appendChild(li);
                    li.addEvent('click', this.toggleContact);
                }
            }
        }
        this.toggleAll();
	},
	
    toggleContact: function(e) {
		var checkbox = this.getElement('input[type=checkbox]');

		if ((typeof(this.handler.inviteContacts[this.contactType][this.contactnr]) != 'undefined') && this.handler.inviteContacts[this.contactType][this.contactnr] == true) {
			this.handler.inviteContacts[this.contactType][this.contactnr] = false;
			if (checkbox.checked) {
				checkbox.checked = false;
			}
			this.handler.selectedCount[this.contactType]--;
		} else {
			this.handler.inviteContacts[this.contactType][this.contactnr] = true;
			if (! checkbox.checked) {
				checkbox.checked = true;
			}
			this.handler.selectedCount[this.contactType]++;
		}
        var toggleall = (this.contactType == 'online') ? 'toggleall' : 'toggleall2';
		if (this.handler.selectedCount[this.contactType] < this.handler.contactCount[this.contactType]) {
			this.handler.allSelected[this.contactType] = false;
			if ($(toggleall).checked) {
				$(toggleall).checked = false;
			}
		} else {
			this.handler.allSelected[this.contactType] = true;
			if (! $(toggleall).checked) {
				$(toggleall).checked = true;
			}
		}
	},
	
    toggleAll: function(e) {
        var contacts;
        var listname = false;
        if (e == undefined) { // Clicked specific list or both
            contacts = $$('#contactslist li, #contactslist2 li');
            listname = 'both';
        } else if (e.target.id == 'toggleall') {
            listname = 'online';
            contacts = $$('#contactslist li');
        } else if (e.target.id == 'toggleall2') {
            listname = 'offline';
            contacts = $$('#contactslist2 li');
        }

        var checked;
        if ((listname == 'both') || (listname == 'online')) {
            if (this.allSelected['online']) {
                checked = false;
                this.selectedCount['online'] = 0;
                this.allSelected['online'] = false;
                if ($('toggleall').checked) {
                    $('toggleall').checked = false;
                }
            } else {
                checked = true;
                this.selectedCount['online'] = $$('#contactslist li').length;
                this.allSelected['online'] = true
                if (! $('toggleall').checked) {
                    $('toggleall').checked = true;
                }
            }
        }
        if ((listname == 'both') || (listname == 'offline')) {
            if (this.allSelected['offline']) {
                checked = false;
                this.selectedCount['offline'] = 0;
                this.allSelected['offline'] = false;
                if ($('toggleall2').checked) {
                    $('toggleall2').checked = false;
                }
            } else {
                checked = true;
                this.selectedCount['offline'] = $$('#contactslist2 li').length;
                this.allSelected['offline'] = true;
                if (! $('toggleall2').checked) {
                    $('toggleall2').checked = true;
                }
            }
        }

        contacts.each(function(li, index) {
            li.handler.inviteContacts[li.contactType][li.contactnr] = checked;
            var checkbox = li.getElement('input[type=checkbox]');
            checkbox.checked = checked;
        });
	}
});

Mobajl.Signup = new Class({
	initialize: function() {
        /*  Invite page */
        this.styledElements = (typeof Custom == 'undefined') ? false : true;
        this.inviteContacts = {
            "online": {},
            "offline": {}
        };
        this.selectedCount = {
            'online': 0,
            'offline': 0
        }
        this.contactCount = {
            'online': 0,
            'offline': 0
        };
        this.allSelected = {
            'online': false,
            'offline': false
        };
        
        $$('a.skip').addEvent('click', function(e) { slider.next(); });
        $('fifth').getElement('#onlinecontacts > a.goback').addEvent('click', function(e) {
            $('fifth').getElement('.first').setStyle('display', 'block');
            $('fifth').getElement('.second').setStyle('visibility', 'hidden');
        });
        $('fifth').getElement('#offlinecontacts > a.goback').addEvent('click', function(e) {
            $('offlinecontacts').hide();
            $('onlinecontacts').show();
            $('fifth').getElement('#onlinecontacts > a.goback').fireEvent('click');
        });
        
        $('toggleall').addEvent('click', this.toggleAll.bind(this));
        $('toggleall2').addEvent('click', this.toggleAll.bind(this));
        
        /* Invite end */
        
		this.currentstep = 1;
		this.email = "";
		this.name = "";
		this.adress = "";
		this.city = "";
		this.zip = "";
		this.userid = 0;
		this.loadinglocked = false;
		this.citydisabled = false;
		this.init();
		this.getPreviousData();
		this.cba = new Mobajl.Checkbox('cba', 'cbabox', 'cbalabel');
		this.firstsignup = true;
	},
	
	init: function() {
        // Exitoffer
        $('exitoffer_yes').addEvent('click', this.exitOffer);
        $('exitoffer_no').addEvent('click', this.exitOffer);
        if (lang != 'dk')
            $('lastfour').addEvent('keydown', this.checkLastfourInput);
        
        // Invite page
        $('invite2button').addEvent('click', this.inviteStep.bind(this));
        $('invite3button').addEvent('click', this.inviteStep2.bind(this));  // Online contacts
        $('invite3button2').addEvent('click', this.inviteStep2.bind(this)); // Offline contacts
        $('iusername').addEvent('keypress', this.listenToEnter.bind(this));
        $('ipassword').addEvent('keypress', this.listenToEnter.bind(this));

        // Signup
		$('step1button').addEvent('click', this.step1.bind(this));
		$('emailform').addEvent('submit', this.step1.bind(this));
		$('step2button').addEvent('click', this.step2.bind(this));
        $('step3button').addEvent('click', this.step3.bind(this));
		$('signupform').addEvent('submit', this.step2.bind(this));
		$('izipcode').addEvent('keypress', this.checkZipInput.bind(this));
		$('izipcode').addEvent('keyup', this.checkZipLength.bind(this));
		$('icity').addEvent('keypress', this.checkCityInput.bind(this));
		$('icellphone').addEvent('keypress', this.checkPhoneInput.bind(this));

		$$('a').each(function(el) {
			if (el.get('rel') == 'termslink') {
				el.addEvent('click', this.termsLink.bind(this));
			}
		}, this);
		if ((this.currentstep == 1) && (! Cookie.read('flashShown'))) {
            makeFlashModal(571,286);
            $$('a[rel=flashmsg]').fireEvent('click');
        }
        
		(new Mobajl.Splashes()).enableBubbles();
	},
    listenToEnter: function(e) {
		if (e.key == 'enter') {
			this.inviteStep();
			e.preventDefault();
		}
	},
    exitOffer: function() {
        var status = new Mobajl.StatusIndicator(5);
        var success = true;
        var focus = false;
        var iMsg = "";
        if (this.id == 'exitoffer_yes') {
            if (! $('conditionsagreement').checked) {
                $('conditionsagreementalerts').getElement('.bad').setStyle('display', 'block');
                iMsg += alerts.agree + "<br/>";
                success = false;
            } else {
                $('conditionsagreementalerts').getElement('.bad').setStyle('display', 'none');
            }
            if (lang != 'dk') {
                if (! $('lastfour').value.trim().match(/^\d{4}$/)) {
                    $('birthdatealerts').getElement('.bad').setStyle('display', 'block');
                    iMsg += alerts.birthdatelast2 + "<br/>";
                    focus = 'lastfour';
                    success = false;
                } else {
                    $('birthdatealerts').getElement('.bad').setStyle('display', 'none');
                }
            }
        }
        if (success) {
            var jsonRequest = new Request.JSON({
                url: baseurl+"ajax/exitoffer",
                onRequest: function() {
                    this.statusindicator.loading();
                },
                onComplete: function(result){
                    if (result.success || this.button_id == 'exitoffer_no') {
                        this.statusindicator.good();
                        slider.next(function() {
                        if ($('iusername').value.length > 0) {
                            $('ipassword').focus();
                        } else {
                            $('iusername').focus();
                        }
                    });
                    } else {
                        this.statusindicator.bad();
                        signup.flagErrors(result.errors);
                    }
                },
                onFailure: function() {
                    this.statusindicator.bad();
                }
            });
            jsonRequest.statusindicator = status;
            jsonRequest.button_id = this.id;
            if (this.id == 'exitoffer_yes') {
                var birthdate = (lang != 'dk') ? $('lastfour').value : '';
                jsonRequest.send("accept=yes&lastfour=" + birthdate + "&newsletter=" + $('inewsletter').checked);
            } else {
                jsonRequest.send("accept=no");
            }
        } else {
            status.bad();
            makeAlert(alerts.errors, iMsg, focus);
        }
    },
	getPreviousData: function() {
		this.loading(1);
		var jsonRequest = new Request.JSON({encoding: "iso-8859-1", url: baseurl+"ajax/previous", onComplete: function(result) {
			this.loadingDone(1);

			if ((result && result.user) && (result.user.stage < 3)) {
				var gotopage = 0;	
				if (result.user.stage >= 1) {
					prizeselector.select(result.user.prize);
                    $('splash').addClass('step2');
					this.email = result.user.email;
					$('iemail').value = this.email;
					gotopage = 2;
					this.firstsignup = false;
				}
				if (result.user.stage >= 2) {
                    var lastskip = $('fifth').getElement('a.skip')
                    lastskip.removeEvents('click');
                    lastskip.addEvent('click', function() { window.location = baseurl + 'invite/' + result.user.code; });
                    
					var gender = (result.user.gender == 'male') ? 1 : 2;
					$("igender").selectedIndex = gender;
					if ($("igender").hasClass('styled')) {
						// Update the text for styled lists
						try { $("selectgender").innerHTML = $("igender").options[$("igender").selectedIndex].innerHTML; } catch(e) {}
					}
					
					//genderselector.select(gender);
					$('iname').value = result.user.name;
					$('iyear').value = result.user.year;
					$('imonth').value = result.user.month;
					$('iday').value = result.user.day;
					$('icellphone').value = result.user.cellphone;
                    
                    var birthdate = result.user.birthdate.split('-');
                    for (var i=1; i <= 2; i++) {
                        if (birthdate[i].length == 1) birthdate[i] = '0' + birthdate[i];
                    }
                    $('birthdate').set('text', birthdate.join('-'));
                    
                    $('cba').checked=true;
                    if (! Browser.Engine.trident4) Custom.init();
					gotopage = 3;
				}
				if (gotopage > 0) {
					slider.gotoPage.delay(1000, slider, gotopage);
				} else {
					slider.showSlogan();
				}
			} else {
				slider.showSlogan();
			}
		}.bind(this), 
		onFailure: function(result) {
			slider.showSlogan();
		}.bind(this)
		}).get();
	},
    /* Invite start */
    inviteStep: function(e) {
        var errors = {};
		var formcheck = true;
		var focus = false;
		if ($('iusername').value.length == 0) {
			errors.username = alerts.email;
			formcheck = false;
			focus = 'iusername';
		}
		if ($('ipassword').value.length == 0) {
			errors.password = alerts.password;
			formcheck = false;
			if (!focus) {
				focus = 'ipassword';
			}
		}

		var status = new Mobajl.StatusIndicator(31);
		if (!formcheck) {
			status.flagErrors(errors, focus);
			if (typeof(e) != 'undefined')
				e.preventDefault();	
			return;
		}
		var form = $('inviteform');
		form.statusindicator = status;
		form.handler = this;
		form.set('send', {url: baseurl+'ajax/contacts', method: 'post',
 			onRequest: function(){
				$('inviteform').statusindicator.loading();
			},
			
			onSuccess: function() {
				var response = $('inviteform').get('send');
				var result = JSON.decode(response.response.text);
				if (result.success) {
					$('inviteform').statusindicator.good();
					$('inviteform').handler.contacts = result.contacts;
                    $('inviteform').handler.onlineContacts = result.onlineContacts;
					if (result.onlineContacts.length == 0) {
                        if (result.contacts.length > 0) {
                            $('onlinecontacts').hide();
                            $('offlinecontacts').show();
                        }
                    }
					$('inviteform').handler.allSelected = {
                        'online': false,
                        'offline': false
                    };
                    
					$('inviteform').handler.populateContacts();
                    
                    $('fifth').getElement('.first').setStyle('display', 'none');
                    $('fifth').getElement('.second').setStyle('visibility', 'visible');
					setGoal(3, 'step3');
				} else {
					$('inviteform').statusindicator.bad();
					$('inviteform').statusindicator.flagErrors(result.errors);
				}
			},

			onFailure: function() {
				$('inviteform').statusindicator.bad();
			}
		});
		form.send();
		if (typeof(e) != 'undefined')
			e.preventDefault();	
    },
    inviteStep2: function(e) {
        var invite = [];
        // This function is bound on two different forms
        var contactType = (e.target.id == 'invite3button') ? 'online' : 'offline';

		for (var i in this.inviteContacts[contactType]) {
            if (this.inviteContacts[contactType][i] == true) {
                invite.push(i);
            }
        }
        
        var status = new Mobajl.StatusIndicator(32);
        var jsonRequest = new Request.JSON({
            url: baseurl+"ajax/invite",
            onRequest: function(){
                this.statusindicator.loading();
            },
            
            onComplete: function(result){
                if (result.success) {
                    this.statusindicator.loadingDone();
                    if ((contactType == 'online') && ($$('#contactslist2 li').length > 0)) {
                        $('onlinecontacts').hide();
                        $('offlinecontacts').show();
                    } else {
                        this.statusindicator.good();
                        setGoal(3, 'submit');
                        window.location = baseurl + "invite/" + result.user.code;
                    }
                } else {
                    this.statusindicator.bad();
                    this.statusindicator.flagErrors(result.errors);
                }
            },

            onFailure: function() {
                this.statusindicator.bad();
            }

        });
        jsonRequest.statusindicator = status;
        jsonRequest.handler = this;
        jsonRequest.send("invite=" + invite + "&contactType=" + contactType);
	},
    populateContacts: function() {
		this.contactCount = {
            'offline': 0,
            'online': 0
        };
		this.inviteContacts = {
            "offline": {},
            "online": {}
        };
        for (var listnr=1; listnr <= 2; listnr++) {
            var contacts, list, contactType;
            if (listnr == 1) {
                contactType = 'offline';
                contacts = this.contacts;
                list = $('contactslist2');
            } else {
                contactType = 'online';
                contacts = this.onlineContacts;
                list = $('contactslist');
            }
            if (contacts != undefined) {
                this.contactCount[contactType] = contacts.length;
                list.empty();
                for (var i=0; i < contacts.length; i++) {
                    var li = new Element('li');
                    li.appendChild(new Element('input').set({'type': 'checkbox'}));
                    //li.appendChild(new Element('div').addClass('contacticon'));
                    li.appendChild(new Element('label').addClass('contacticon').appendText((contacts[i].name+" - "+contacts[i].email).truncate(50)));
                    li.contactnr = i;
                    li.contactType = contactType;
                    li.handler = this;
                    list.appendChild(li);
                    li.addEvent('click', this.toggleContact);
                }
            }
        }
        this.toggleAll();
	},
    toggleContact: function(e) {
		var checkbox = this.getElement('input[type=checkbox]');
		
		if ((typeof(this.handler.inviteContacts[this.contactType][this.contactnr]) != 'undefined') && this.handler.inviteContacts[this.contactType][this.contactnr] == true) {
			this.handler.inviteContacts[this.contactType][this.contactnr] = false;
			if (checkbox.checked) {
				checkbox.checked = false;
			}
			this.handler.selectedCount[this.contactType]--;
		} else {
			this.handler.inviteContacts[this.contactType][this.contactnr] = true;
			if (! checkbox.checked) {
				checkbox.checked = true;
			}
			this.handler.selectedCount[this.contactType]++;
		}
        var toggleall = (this.contactType == 'online') ? 'toggleall' : 'toggleall2';
		if (this.handler.selectedCount[this.contactType] < this.handler.contactCount[this.contactType]) {
			this.handler.allSelected[this.contactType] = false;
			if ($(toggleall).checked) {
				$(toggleall).checked = false;
			}
		} else {
			this.handler.allSelected[this.contactType] = true;
			if (! $(toggleall).checked) {
				$(toggleall).checked = true;
			}
		}
	},
	
	toggleAll: function(e) {
        var contacts;
        var listname = false;
        if (e == undefined) { // Clicked specific list or both
            contacts = $$('#contactslist li, #contactslist2 li');
            listname = 'both';
        } else if (e.target.id == 'toggleall') {
            listname = 'online';
            contacts = $$('#contactslist li');
        } else if (e.target.id == 'toggleall2') {
            listname = 'offline';
            contacts = $$('#contactslist2 li');
        }

        var checked;
        if ((listname == 'both') || (listname == 'online')) {
            if (this.allSelected['online']) {
                checked = false;
                this.selectedCount['online'] = 0;
                this.allSelected['online'] = false;
                if ($('toggleall').checked) {
                    $('toggleall').checked = false;
                }
            } else {
                checked = true;
                this.selectedCount['online'] = $$('#contactslist li').length;
                this.allSelected['online'] = true
                if (! $('toggleall').checked) {
                    $('toggleall').checked = true;
                }
            }
        }
        if ((listname == 'both') || (listname == 'offline')) {
            if (this.allSelected['offline']) {
                checked = false;
                this.selectedCount['offline'] = 0;
                this.allSelected['offline'] = false;
                if ($('toggleall2').checked) {
                    $('toggleall2').checked = false;
                }
            } else {
                checked = true;
                this.selectedCount['offline'] = $$('#contactslist2 li').length;
                this.allSelected['offline'] = true;
                if (! $('toggleall2').checked) {
                    $('toggleall2').checked = true;
                }
            }
        }
        
        contacts.each(function(li, index) {
            li.handler.inviteContacts[li.contactType][li.contactnr] = checked;
            var checkbox = li.getElement('input[type=checkbox]');
            checkbox.checked = checked;
        });
	},
    /* Invite end */
    
	step1: function(e) {
		if (this.loadinglocked) {
			return;
		}
		$('iemail').value = $('iemail').value.replace(/ /gi,'');
		var iMsg = "";
		if ($('iemail').value.search(/^[-A-Za-z0-9_.]+[@][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)*[.][A-Za-z]{2,8}$/gi) == -1) {
			iMsg += alerts.email+"<br />";
		}

        var prize = prizeselector.getSelection();
        if (prize == 0) {
            iMsg += alerts.prize+"<br />";
        }
		if (iMsg.length > 0) {
			makeAlert(alerts.errors, iMsg);
			return false;
		}
        
        $('iprize').value = prize;
		var form = $('emailform');
		form.handler = this;

		form.set('send', {url: baseurl+'ajax/step1', method: 'post',
 			onRequest: function(arg){
				signup.loading(1);
			},
			
			onSuccess: function(responseText) {
				var result = JSON.decode(responseText);
				if (result.success) {
					signup.good(1);
					form.handler.userid = result.id;
					form.handler.email = result.email;
					if (form.handler.firstsignup) {
						setGoal(1, 'step1');
					}
					form.handler.firstsignup = false;
                    
                    $('iusername').value = $('iemail').value;
                    

                    var lastskip = $('fifth').getElement('a.skip')
                    lastskip.removeEvents('click');
                    lastskip.addEvent('click', function() { window.location = baseurl + 'invite/' + result.user.code; });
                    
                    slider.next(function() {
						$('iname').focus();
						$('splash').addClass('step2');
					});
				} else {
					signup.bad(1);
					signup.flagErrors(result.errors);
				}
			},

			onFailure: function(arg) {
				signup.bad(1);
			}
		});
		form.send();
		if (e)
			e.preventDefault();	
	},
	
	step2: function(e) {
		if (!this.checkForm()) {
			return false;
		}

		var form = $('signupform');
		form.set('send', {url: baseurl+'ajax/step2', method: 'post',
 			onRequest: function(){
				signup.loading(2);
			},
			
			onSuccess: function() {
				var response = $('signupform').get('send');
				var result = JSON.decode(response.response.text);
				if (result.success) {
					signup.good(2);
					setGoal(1, 'step2');
                    if (lang != 'dk') {
                        var birthdate = result.user.birthdate.split('-');
                        for (var i=1; i <= 2; i++) {
                            if (birthdate[i].length == 1) birthdate[i] = '0' + birthdate[i];
                        }
                        $('birthdate').set('text', birthdate.join('-'));
                    }
					slider.next(function() { $('iaddress').focus(); });
				} else {
					signup.bad(2);
					signup.flagErrors(result.errors);
				}
			},

			onFailure: function() {
				signup.bad(2);
			}
		});
		this.citydisabled = false;
		form.send();		
	},
	
    step3: function(e) {
        if (!this.checkForm2()) {
			return false;
		}
        
        form = $('interestsform');
		form.set('send', {url: baseurl+'ajax/step3', method: 'post',
 			onRequest: function(){
				signup.loading(3);
			},
			
			onSuccess: function() {
				var response = $('interestsform').get('send');
				var result = JSON.decode(response.response.text);
				if (result.success) {
					signup.good(3);
					setGoal(1, 'submit');
					if (! result.exitoffer) {
                        slider.gotoPage(5);
					}
                    slider.next();
				} else {
					signup.bad(3);
					signup.flagErrors(result.errors);
				}
			},

			onFailure: function() {
				signup.bad(3);
			}
		});
		form.send();
	},
	
	fixInterests: function() {
		if (lang == 'sv') {
			if (genderselector.getSelection() == 1) {
				$('interest7').getParent('li').setStyle('display', 'none');
				$('interest6').getParent('li').setStyle('display', 'block');
			} else {
				$('interest6').getParent('li').setStyle('display', 'none');
				$('interest7').getParent('li').setStyle('display', 'block');
			}
		} else if (lang == 'no') {
			if (genderselector.getSelection() == 1) {
				$('interest7').getParent('li').setStyle('display', 'none');
				$('interest9').getParent('li').setStyle('display', 'none');
				$('interest6').getParent('li').setStyle('display', 'block');
			} else {
				$('interest6').getParent('li').setStyle('display', 'none');
				$('interest7').getParent('li').setStyle('display', 'block');
				$('interest9').getParent('li').setStyle('display', 'block');
			}
			
		}
	},
    checkLastfourInput: function(e) {
        var input = $('lastfour').value;
        var inputlength = input.length;
        var keycode = (e.event.which) ? e.event.which : e.event.keyCode;

        switch(lang) {
        case 'fi':	// FI can also use a-y
            if ((typeof(e.meta) != 'undefined' && e.meta == true) || keycode == 8 || keycode == 9 || !(keycode == 0 || keycode > 31 && (keycode < 48 || keycode > 57 && (keycode < 65 || keycode > 89)))) {
                if (keycode > 47 && $('lastfour').value.length > 3 && $('lastfour').getSelectedText().length == 0) {
                    new Event(e).stop();
                } else {
                    return;
                }
            }
            break;

        default:	// Default is numbers only
            var key = parseInt(e.key);
            if (isNaN(key) == false && key >= 0 && key <= 9) {
                inputlength++;
                if (inputlength > 4 && $('lastfour').getSelectedText().length == 0) {
                    new Event(e).stop();
                } else {
                    return;
                }
            } else if ((typeof(e.meta) != 'undefined' && e.meta == true) || keycode == 8 || keycode == 9 || !(keycode == 0 || keycode > 31 && (keycode < 48 || keycode > 57))) { return; }
        }
        new Event(e).stop();
    },

	checkForm: function() {
		var errors = false;
		iMsg = "";
		var focus = false;
		if ($('iname').value.length < 2) {
			iMsg += alerts.name+"<br />\n";
			if (!focus) {
				focus = 'iname';
			}
		} else {
			var namesplit = $('iname').value.trim().split(" ");
			if (namesplit.length < 2) {
				iMsg += alerts.lastname+"<br />\n";
				if (!focus) {
					focus = 'iname';
				}
			}
		}

		var dateerrors = {year: false, month: false, day: false, fail: false};
		
		if (! IsNumeric($('iyear').value)) {
			dateerrors.year = alerts.year+'<br />\n';
			dateerrors.fail = true;
		}
	
		if (! IsNumeric($('imonth').value)) {
			dateerrors.month = alerts.month+'<br />\n';
			dateerrors.fail = true;
		}
	
		if (! IsNumeric($('iday').value)) {
			dateerrors.day = alerts.day+'<br />\n';
			dateerrors.fail = true;
		}
	
		if (dateerrors.fail) {
			var focus = false;
			if (lang == 'sv') {
				if (dateerrors.year) {
					iMsg += dateerrors.year;
					focus = 'iyear';
				}
				if (dateerrors.month) {
					iMsg += dateerrors.month;
					if (!focus)
						focus = 'imonth';
				}
				if (dateerrors.day) {
					iMsg += dateerrors.day;
					if (!focus)
						focus = 'iday';
				}
			} else {
				if (dateerrors.day) {
					iMsg += dateerrors.day;
					if (!focus)
						focus = 'iday';
				}
				if (dateerrors.month) {
					iMsg += dateerrors.month;
					if (!focus)
						focus = 'imonth';
				}
				if (dateerrors.year) {
					iMsg += dateerrors.year;
					if (!focus)
						focus = 'iyear';
				}
			}
		}
			
		
	
		if ($('igender').value != 1 && $('igender').value != 2) {
			iMsg += alerts.gender+"<br />\n";
		}
		
		$('icellphone').value = $('icellphone').value.replace(/[^0-9]/gi,'');
		if ($('icellphone').value.length < cellphoneminlength) {
			iMsg += alerts.cellphone+"<br />\n";
			if (!focus) {
				focus = 'icellphone';
			}
		} else if ($('icellphone').value.search(/^000/) >= 0) {
			iMsg += alerts.cellphone+"<br />\n";
			if (!focus) {
				focus = 'icellphone';
			}
		}
		
		if (! $('cba').checked) {
			iMsg += alerts.agree+"<br />\n";
		}

		if (iMsg.length > 0) {
			var alert = makeAlert(alerts.errors, iMsg, focus);

			return false;
		}
		
		return true;
	},
    
    checkForm2: function() {
        var errors = false;
		iMsg = "";
		var focus = false;
        
        if ($('iaddress').value.length < 2) {
			iMsg += alerts.address+"<br />\n";
			if (!focus) {
				focus = 'iaddress';
			}
		}

		if (!IsNumeric($('izipcode').value) || $('izipcode').value.length != zipcodemax) {
			iMsg += alerts.postcode+"<br />\n";
			if (!focus) {
				focus = 'izipcode';
			}
		}

		if ($('icity').value.length < 1) {
			iMsg += alerts.city+"<br />\n";
			if (!focus) {
				focus = 'icity';
			}
		}
        
        if (! IsNumeric($('iinterests').value)) {
			iMsg += alerts.interests + "<br />\n";
		}
		
        if (iMsg.length > 0) {
			var alert = makeAlert(alerts.errors, iMsg, focus);

			return false;
		}
		
		return true;
    },
	checkZipLength: function(e) {
		var zipcode = $('izipcode').value;
		if (zipcode.length == zipcodemax) {
			this.getCity();
		}

	},

	checkZipInput: function(e) {
		var zipcode = $('izipcode').value;
		var inputlength = zipcode.length;

		var keycode = (e.event.which) ? e.event.which : e.event.keyCode;

		var key = parseInt(e.key);
		if (isNaN(key) == false && key >= 0 && key <= 9) {
			inputlength++;
			if (inputlength > zipcodemax && $('izipcode').getSelectedText().length == 0) {
				e.preventDefault();
			}		
		} else if ((typeof(e.meta) != 'undefined' && e.meta == true) || keycode == 8 || keycode == 9 || !(keycode > 31 && (keycode < 48 || keycode > 57))) {
		} else {
			e.preventDefault();
		}
	},
	
	checkPhoneInput: function(e) {
		var phone = $('icellphone').value;
		var inputlength = phone.length;
		var keycode = (e.event.which) ? e.event.which : e.event.keyCode;

		var key = parseInt(e.key);
		if (isNaN(key) == false && key >= 0 && key <= 9) {
			inputlength++;
			if (inputlength > cellphonelength && $('icellphone').getSelectedText().length == 0) {
				e.preventDefault();
			}		
		} else if ((typeof(e.meta) != 'undefined' && e.meta == true) || keycode == 8 || keycode == 9 || !(keycode > 31 && (keycode < 48 || keycode > 57))) {
		} else {
			e.preventDefault();
		}
	},

	checkCityInput: function(e) {
		if (this.citydisabled) {
			if (e.event.charCode == 0) {
				if (e.event.keyCode != 9 && !(e.event.keyCode >= 33 && e.event.keyCode <= 39)) {
					e.preventDefault();
					
				}
			} else {
				e.preventDefault();
			}
		}
	},

	flagErrors: function(errors, focus) {
		iMsg = "";
		for (var i in errors) {
			iMsg += errors[i]+"<br />\n";
		}

		makeAlert(alerts.errors, iMsg, focus);
	},

	termsLink: function(e) {
		slider.gotoPage(4);
		e.preventDefault();
	},

	getCity: function() {
		//this.citydisabled = true;
		var zipcode = $('izipcode').value;
		if (zipcode != this.zip && zipcode.length > 0) {
			this.zip = zipcode;
			$('step2alerts').getElement('span.loader').setStyle('display', 'inline');
			var jsonRequest = new Request.JSON({url: baseurl+"/ajax/city", onComplete: function(result) {
				$('step2alerts').getElement('span.loader').setStyle('display', 'none');			
				if (result.success) {
					this.city = result.city;
					$('icity').value = this.city;
					if (this.city.length == 0) {
						//this.citydisabled = false;
						$('icity').focus();
					}
				} else {
					//this.citydisabled = true;
					$('icity').focus();
				}
			}.bind(this)}).send("zip="+zipcode);
		}
	},
	
	loading: function(step) {
		this.loadinglocked = true;
		if (typeof(step) == 'undefined') {
			step = 1;
		}
		$('step'+step+'alerts').getElement('span.good').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.bad').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.loader').setStyle('display', 'inline');
	},
	
	loadingDone: function(step) {
		this.loadinglocked = false;
		if (typeof(step) == 'undefined') {
			step = 1;
		}
		$('step'+step+'alerts').getElement('span.good').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.bad').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.loader').setStyle('display', 'none');
	},
	
	good: function(step) {
		this.loadinglocked = false;
		if (typeof(step) == 'undefined') {
			step = 1;
		}
		$('step'+step+'alerts').getElement('span.bad').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.loader').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.good').setStyle('display', 'inline');
		if (Browser.Engine.trident4) {
			$('step'+step+'alerts').getElement('span.good').setStyle('background-image', 'none');
			$('step'+step+'alerts').getElement('span.good').setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=image, src='/img/alert_good.png')");
		}
	},

	bad: function(step) {
		this.loadinglocked = false;
		if (typeof(step) == 'undefined') {
			step = 1;
		}
		$('step'+step+'alerts').getElement('span.good').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.loader').setStyle('display', 'none');
		$('step'+step+'alerts').getElement('span.bad').setStyle('display', 'inline');
		if (Browser.Engine.trident4) {
			$('step'+step+'alerts').getElement('span.bad').setStyle('background-image', 'none');
			$('step'+step+'alerts').getElement('span.bad').setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=image, src='/img/alert_bad.png')");
		}
	}
	
});

Mobajl.Checkboxes = new Class({
	initialize: function(listid) {
		if (typeof(listid) == 'undefined') {
			listid = 'interestslist';
		}
		this.listid = listid;
		this.bindElements();
	},
	
	bindElements: function() {
		$(this.listid).getElements('li').each(function(element) {
			element.handler = this;
			element.addEvent('click', this.toggleCheckbox);
			element.getElement('input').value = 0;
		}, this);
	},
	
	toggleCheckbox: function(event) {
		var storage = this.getElement('input');

		if (storage.value == 1) {
			storage.value = 0;
			this.getElement('div').setStyle('background-image', 'url('+baseurl+'img/checkbox.png)');
		} else {
			storage.value = 1;
			this.getElement('div').setStyle('background-image', 'url('+baseurl+'img/checkbox_checked.png)');
		}
	}
});

Mobajl.Checkbox = new Class({
	initialize: function(storage, box, label) {
		this.storage = $(storage);
		if (this.storage) {
			this.storage.value = 0;
		}
		this.box = $(box);
		this.label = $(label);
        
		if (this.box != null) {
			this.box.addEvent('click', this.toggleCheckbox.bind(this));
		} else {
			return false;
		}
		if (this.label) {
			this.label.addEvent('click', this.toggleCheckbox.bind(this));
		}
	},
	
	toggleCheckbox: function() {
		if (this.storage.value == 1) {
			this.storage.value = 0;
			this.box.setStyle('background-image', 'url('+baseurl+'img/checkbox.png)');
		} else {
			this.storage.value = 1;
			this.box.setStyle('background-image', 'url('+baseurl+'img/checkbox_checked.png)');
		}
	},
	
	checked: function () {
		if (this.storage.value == 1) {
			return true;
		} else {
			return false;
		}
	}
})

Mobajl.StatusIndicator = new Class({
	initialize: function(step) {
		if (typeof(step) == 'undefined') {
			step = 1;
		}

		this.step = step;	
	},
	
	loading: function() {
		this.loadinglocked = true;
		$('step'+this.step+'alerts').getElement('span.good').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.bad').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.loader').setStyle('display', 'inline');
	},
	
	loadingDone: function() {
		this.loadinglocked = false;
		$('step'+this.step+'alerts').getElement('span.good').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.bad').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.loader').setStyle('display', 'none');
	},
	
	good: function() {
		this.loadinglocked = false;
		$('step'+this.step+'alerts').getElement('span.bad').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.loader').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.good').setStyle('display', 'inline');
		if (Browser.Engine.trident4) {
			$('step'+this.step+'alerts').getElement('span.good').setStyle('background-image', 'none');
			$('step'+this.step+'alerts').getElement('span.good').setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=image, src='"+baseurl+"img/alert_good.png')");
		}
	},

	bad: function() {
		this.loadinglocked = false;
		$('step'+this.step+'alerts').getElement('span.good').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.loader').setStyle('display', 'none');
		$('step'+this.step+'alerts').getElement('span.bad').setStyle('display', 'inline');
		if (Browser.Engine.trident4) {
			$('step'+this.step+'alerts').getElement('span.bad').setStyle('background-image', 'none');
			$('step'+this.step+'alerts').getElement('span.bad').setStyle('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=image, src='"+baseurl+"img/alert_bad.png')");
		}
	},
	
	flagErrors: function(errors, focus) {
		iMsg = "";

		if (typeof(errors.length) == 'undefined') {
			for (var i in errors) {
				iMsg += errors[i] + "<br />\n";
			}			
		} else {
			for (var i = 0; i < errors.length; i++) {
				iMsg += errors[i] + "<br />\n";
			}			
			
		}
		if (iMsg.length == 0) {
			iMsg = alerts.connectionerror;
		}

		makeAlert(alerts.errors, iMsg, focus);
	}

});

function makeAlert(header, msg, focus) {
	if (Browser.Engine.trident4) {
		var slask = new Object();
		alert(header+"\n\n"+msg.trim().replace(/<br \/>\n?/gi, "\n"));
		if (focus) {
			$(focus).focus();
		}
	} else {
		var slask = Mobajl.Alert(header, msg);

		if (focus) {
			slask.addEvent('close', function(){
				$(focus).focus();
			});
		}
	}

	return slask;
}

Mobajl.Alert = function(msghdr, msg) {
	baseHref = '/img/alert/';
	
	var body = Mobajl.StickywinAlert(msghdr, msg, {width: 250});
	var modaloptions = {
		modalOptions: {
			modalStyle: {
				zIndex: 11000
			}
		},
		zIndex: 110001,
		content: body,
		position: 'center' //center, corner
	};

	return new StickyWinModal(modaloptions);
};


Mobajl.StickywinAlert = function(caption, body) {
	options = {
		css: "",
		width: 250,
		cornerHandle: false,
		cssClass: '',
		baseHref: '/img/alert/',
		buttons: []
	};

	new StyleWriter().createStyle(options.css.substitute({baseHref: options.baseHref}, /\\?\{%([^}]+)%\}/g), 'defaultStickyWinStyle');
	caption = $pick(caption, '%caption%');
	body = $pick(body, '%body%');
	var container = new Element('div').setStyle('width', options.width).addClass('DefaultStickyWin');
	if(options.cssClass) container.addClass(options.cssClass);

	//header
	var h1Caption = new Element('h1').addClass('caption').setStyle('width', (options.width.toInt()-(options.cornerHandle?70:60)));

	if($(caption)) h1Caption.adopt(caption);
	else h1Caption.set('html', caption);
	
	var bodyDiv = new Element('div').addClass('body');
	if($(body)) bodyDiv.adopt(body);
	else bodyDiv.set('html', body);

	//bodyDiv.addClass('clearfix');
	
	container.adopt(
		new Element('div').addClass('top').adopt(
			new Element('div').addClass('closeButton').addClass('closeSticky')
		).adopt(h1Caption)
	);
	//body
	container.adopt(bodyDiv);

	//footer
	container.adopt(
		new Element('div').addClass('bottom')
	);
	return container;
};


function returnAge() {
	ayear = 0;
	if ($('iyear').value==9999 || $('imonth').value==99 || $('iday').value==99) {
		return -1;
	} else {
		var myDate = new Date();
		myDate.setFullYear($('iyear').value, ($('imonth').value-1), $('iday').value);

		var ayear = (today.getFullYear() - myDate.getFullYear())-1;

		if (today.getMonth() > myDate.getMonth()) {
			ayear++;
		} else if (today.getMonth() == myDate.getMonth() && today.getDate() >= myDate.getDate()) {
			ayear++;
		}
	}

	return ayear;
}

function IsNumeric(sText) {
	if (sText.search(/^[0-9]+$/gi) == -1) { return false; }
	return true;
}


function preloadImages(preload) {
	if (typeof(preload) != 'undefined') {
		var myImages = new Asset.images(preload);
	}
 }

function makeModal(assignfilter, width, height, type, autosize) {
	if (typeof(type) == 'undefined') {
		type = 'iframe';
	}
	if (typeof(autosize) == 'undefined') {
		autosize = false;
	}
	var options = {
		size: {
			x: width,
			y: height
		},
		autosize: autosize
	};
		
	if (type == 'iframe') {
		options.handler = 'iframe';
	} else if (type == 'ajax') {
		options.ajaxOptions = {
			method: 'get' // we use GET for requesting plain HTML
		};
	}
		

	SqueezeBox.assign($$(assignfilter), options);
}

function makeExitofferModal() {
	var options = {
		size: {
			x: exitofferx,
			y: exitoffery
		},
		autosize: true,
		handler: 'iframe',
		closable: false,
		closeBtn: false,
/*		onClose: function() {
			alert("hej!");
		},*/
		onOpen: function() {
			setGoal(3, 'view');
			$('sbox-btn-close').addEvent('click', exitOfferNo);
		}
	};
		
	SqueezeBox.assign($$('a[rel=boxedexitoffer]'), options);
}

function makeFlashModal(width, height) {
    var options = {
		size: {
			x: width,
			y: height
		},
        offset: {
            left: 100,
            top: -100
        },
		handler: 'iframe',
        closeBtn: true,
        closable: true,
        marginInner: {x: 0, y: 0},
		onOpen: function() {
            Cookie.write('flashShown', true);
            (function() { SqueezeBox.close() }).delay(6000);
		}
	};

	SqueezeBox.assign($$('a[rel=flashmsg]'), options);
}

function setExternalLinks() {
	$$('a[rel=external]').each(function(element) {
		element.target='_blank';
	});
}

function exitOfferYes(){
	setGoal(3, 'accept');
	var jsonRequest = new Request.JSON({
		url: baseurl+"ajax/exitoffer",
		onComplete: function(result){
			exitOfferProceed();
		}
	});
	jsonRequest.send("accept=yes");
}

function exitOfferNo() {
	exitOfferProceed();
}

function exitOfferProceed() {
	SqueezeBox.setOptions({closable: true});
	SqueezeBox.close();
	window.location = baseurl+"invite/?first=1";
}

function setGoal(goal, name) {
	pageTracker._trackPageview("/funnel_G"+goal+"/"+name); 
}
