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'};
		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 == 2 || pagenr == 3) {
					myFx.addEvent('complete', prizeselector.updateSelectedPrize.bind(prizeselector));
				}
			}
			$(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.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.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() {
		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: [193, 5],
			2: [322, 5],
			3: [512, 5]
		};
		
		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.Signup = new Class({
	initialize: function() {
		this.currentstep = 1;
		this.email = "";
		this.name = "";
		this.adress = "";
		this.city = "";
		this.zip = "";
		this.userid = 0;
		this.loadinglocked = false;
		this.citydisabled = true;
		this.init();
		this.getPreviousData();
		this.cba = new Mobajl.Checkbox('cba', 'cbabox', 'cbalabel');
		this.firstsignup = true;
	},
	
	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) {
				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 gender = (result.user.gender == 'male' ? 1 : 2);
					genderselector.select(gender);
					$('iname').value = result.user.name;
					$('iyear').value = result.user.year;
					$('imonth').value = result.user.month;
					$('iday').value = result.user.day;
					$('izipcode').value = result.user.postcode;
					$('icellphone').value = result.user.cellphone;
					gotopage = 3;
					this.cba.toggleCheckbox();
					this.fixInterests();
				}
				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();
	},
	
	init: function() {
		$('step1button').addEvent('click', this.step1.bind(this));
		$('emailform').addEvent('submit', this.step1.bind(this));
		$('step2button').addEvent('click', this.step2.bind(this));
		$('signupform').addEvent('submit', this.step2.bind(this));


		$('step3button').addEvent('click', this.step3.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);

        $('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);
			}
		});
	},
	
	step1: function(e) {
		if (this.loadinglocked) {
			return;
		}
		var prize = prizeselector.getSelection();
		$('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 />";
		}
		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;

					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) {
		$('igender').value = genderselector.getSelection();
		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');
					signup.fixInterests();
					slider.gotoPage(3);
				} else {
					signup.bad(2);
					signup.flagErrors(result.errors);
				}
			},

			onFailure: function() {
				signup.bad(2);
			}
		});
		this.citydisabled = false;
		form.send();		
	},
	
	step3: function(e) {
		var form = $('interestsform');
		var inputs = form.getElements('input');
		var interestcount = 0;
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].id.indexOf('interest') == 0 && inputs[i].value == 1) {
				interestcount++;
			}
		}
		if (interestcount == 0) {
			signup.flagErrors({'interests': alerts.interests});
			return false;
		}
		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) {
						$('exitofferlink').fireEvent('click');
					} else {
						window.location = baseurl + "invite/" + result.user.code + "?first=1";
					}
				} 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');
			}
			
		}
	},

	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 ($('iyear').value == 9999) {
			dateerrors.year = alerts.year+'<br />\n';
			dateerrors.fail = true;
		}
	
		if ($('imonth').value == 99) {
			dateerrors.month = alerts.month+'<br />\n';
			dateerrors.fail = true;
		}
	
		if ($('iday').value == 99) {
			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 ($('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 ($('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').value != '1') {
			iMsg += alerts.agree+"<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.InvitePage = new Class({
	initialize: function(usercode, first) {
		if (typeof(first) == 'undefined') {
			this.first = false;
		} else {
			this.first = true;
		}
		this.bindElements();
		this.initTerms();
//		this.cba = new Mobajl.Checkbox('cba', 'cbabox', 'cbalabel');
//		this.sendinviteok = new Mobajl.Checkbox('inviteok', 'inviteokbox', 'inviteoklabel');
		this.inviteContacts = {};
		this.selectedCount = 0;
		this.contactCount = 0;
		this.allSelected = false;
		this.usercode = usercode;
		setGoal(2, 'step1');
	},
	
	bindElements: function() {
		$('copylinkbutton').addEvent('click', this.copyLinkToClipboard.bind(this));
		$('step1button').addEvent('click', this.step1.bind(this));
		$('step2button').addEvent('click', this.step2.bind(this));
		$('step3button').addEvent('click', this.step3.bind(this));
		$('inviteform').addEvent('submit', this.step2.bind(this));
		$('invitelink').addEvent('keypress', this.checkLinkInput.bind(this));
		$('toggleallbox').addEvent('click', this.toggleAll.bind(this));
		$('toggleall').addEvent('click', this.toggleAll.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.addEvent('click', function() {
					window.location = pagelink;
				});
//				element.set('html', alerts.skip);
			} else {
				element.addEvent('click', slider.previous.bind(slider));
//				element.set('html', alerts.goback);
			}
		}, this);
	},
	
	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);
	},

	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.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() {
		var invite = [];
		var errors = {};
		var formchecked = true;
		for (var i in this.inviteContacts) {
			if (this.inviteContacts[i] == true) {
				invite.push(i);
			}
		}
		if (invite.length == 0) {
			errors.invite = alerts.selectatleastone;
			formchecked = false;
		}

/*		if (!this.sendinviteok.checked()) {
			errors.agree = alerts.agree;
			formchecked = false;
		}*/
		
		var status = new Mobajl.StatusIndicator(3);
		
		if (formchecked) {
			var jsonRequest = new Request.JSON({
				url: baseurl+"ajax/invite",
	 			onRequest: function(){
					this.statusindicator.loading();
				},

				onComplete: function(result){
					if (result.success) {
						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);
		} else {
			status.flagErrors(errors);
		}
	},
	
	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() {
		var list = $('contactslist');
		list.empty();
		this.contactCount = 0;
		this.inviteContacts = {};
		if (typeof(this.contacts.length) != 'undefined') {
			this.contactCount = this.contacts.length;
			for (var i = 0; i < this.contacts.length; i++) {
				var li = new Element('li');
				li.appendChild(new Element('div').addClass('checkbox').addClass('checked'));
				li.appendChild(new Element('div').addClass('contacticon'));
				li.appendChild(new Element('label').appendText(this.contacts[i].name+" - "+this.contacts[i].email));
				li.contactnr = i;
				li.handler = this;
				list.appendChild(li);
				li.addEvent('click', this.toggleContact)
			}
			this.toggleAll();
			if (!this.allSelected) {
				this.toggleAll();
			}
		}
	},
	
	toggleContact: function(e) {
		if ((typeof(this.handler.inviteContacts[this.contactnr]) != 'undefined') && this.handler.inviteContacts[this.contactnr] == true) {
			this.handler.inviteContacts[this.contactnr] = false;
			this.getElement('div.checkbox').removeClass('checked');
			this.handler.selectedCount--;
		} else {
			this.handler.inviteContacts[this.contactnr] = true;
			this.getElement('div.checkbox').addClass('checked');
			this.handler.selectedCount++;
		}
		if (this.handler.selectedCount < this.handler.contactCount) {
			this.handler.allSelected = false;
			$('toggleallbox').removeClass('checked');
		} else {
			this.handler.allSelected = true;
			$('toggleallbox').addClass('checked');
		}
	},
	
	toggleAll: function(e) {
		if (this.allSelected) {
			this.allSelected = false;
			$('toggleallbox').removeClass('checked');
			this.selectedCount = 0;
			$('contactslist').getElements('li').each(function(li, index) {
				li.handler.inviteContacts[index] = false;
				li.getElement('div.checkbox').removeClass('checked');
			});
		} else {
			this.allSelected = true;
			this.selectedCount = this.contactCount;
			$('toggleallbox').addClass('checked');
			$('contactslist').getElements('li').each(function(li, index) {
				li.handler.inviteContacts[index] = true;
				li.getElement('div.checkbox').addClass('checked');
			});
		}
	}

})

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) {
			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 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); 
}
