/**
 * Package: skiinfo_functions
 *
 * File containing common JavaScript objects for the Skiinfo portal
 */

/**
 * Class: Skiinfo
 * 
 * Object containing properties and methods for Skiinfo portal
 *
 * Requiers jQuery defined as $j
 */
var Skiinfo = function() {
	this.user = function () { return Skiinfo.Login.currentUser; };
	this.alarmboxDisp = 'none';
	this.destId = null;
	
	// private variables
	var destinationsById = null;
	var tr = {};
	var language = "en";
	
	this.initTr = function(trMap){tr=trMap;};
	this.getTr = function(trKey) {if(tr[trKey]) return tr[trKey];return trKey;};
	this.setLanguage = function(lang){ language=lang; };
	this.getLanguage = function() { return language; };
	
	this.showDynamicAlert = function() {
		var container = jQuery('#two #spacer');
		var snowingAlert = jQuery('#dynamic_alert_snowing');
		var powderAlert = jQuery('#dynamic_alert_powder');
		var destId = this.destId;
		
		if(container.length>0 && destId && (snowingAlert.length>0 || powderAlert.length>0)) {
			container.show();

			// create a div inside alarmbox for each text, hide tooltips
			jQuery("<div id='alarmbox-main'></div>").appendTo("#alarmbox");
			var test = Skiinfo.getTr('product.skiinfo.AlarmTooltip.PowderAlarm');
			jQuery("<div id='alarmbox-powder-tooltip'>"+Skiinfo.getTr('product.skiinfo.AlarmTooltip.PowderAlarm')+"</div>").hide().appendTo("#alarmbox");
			jQuery("<div id='alarmbox-snowing-tooltip'>"+Skiinfo.getTr('product.skiinfo.AlarmTooltip.SnowingHereNow')+"</div>").hide().appendTo("#alarmbox");
			
			jQuery("<div id='closeme'><img src='/gifs/1px.gif'></div>").click(function(){
				new Effect.Fade('alarmbox', {duration: 1});
				jQuery('#alarmbox-main').hide();
			}).appendTo("#alarmbox-main");
			
			if(powderAlert.length>0) {
				// append powder info inside main alarmbox div
				var snowreportHref = jQuery("#dynamic_alert_powder").attr("href") || "#";
				jQuery("<div id='alarm_text_powder'><a href='"+snowreportHref+"'>" + Skiinfo.getTr('product.swc.powder_alarm') + "</a></div>").appendTo("#alarmbox-main");
				
				// add tooltip
				jQuery('#dynamic_alert_powder').mouseover(function(){
					Skiinfo.alarmboxDisp = jQuery('#alarmbox').css('display');
					jQuery('#alarmbox-main').hide();
					jQuery('#alarmbox-snowing-tooltip').hide();
					jQuery('#alarmbox-powder-tooltip').show();
					if(Skiinfo.alarmboxDisp=='none') { jQuery('#alarmbox').show(); }
				});
				jQuery('#dynamic_alert_powder').mouseout(function(){
					jQuery('#alarmbox-powder-tooltip').hide();
					jQuery('#alarmbox-main').show();
					jQuery('#alarmbox').css('display', Skiinfo.alarmboxDisp);
				});
			}
			if(snowingAlert.length>0) {
				// append snowing info inside main alarmbox div
				var snowreportHref2 = jQuery("#dynamic_alert_snowing").attr("href") || "#";
				jQuery("<div id='alarm_text_snowing'><a href='"+snowreportHref2+"'>" + Skiinfo.getTr('product.skiinfo.SnowingHereNow') + "</a></div>").appendTo("#alarmbox-main");
				
				// add tooltip
				jQuery('#dynamic_alert_snowing').mouseover(function(){
					Skiinfo.alarmboxDisp = jQuery('#alarmbox').css('display');
					jQuery('#alarmbox-main').hide();
					jQuery('#alarmbox-powder-tooltip').hide();
					jQuery('#alarmbox-snowing-tooltip').show();
					if(Skiinfo.alarmboxDisp=='none') { jQuery('#alarmbox').show(); }
				});
				jQuery('#dynamic_alert_snowing').mouseout(function(){
					jQuery('#alarmbox-snowing-tooltip').hide();
					jQuery('#alarmbox-main').show();
					jQuery('#alarmbox').css('display', Skiinfo.alarmboxDisp);
				});
			}
			
			// only pulsate once every 8 hours (cookie based)
			var alreadyShown = (destId && jQuery.cookie('shown_powder_alarm_'+destId));
			if(!alreadyShown) {
				new Effect.Appear('alarmbox', {to: 0.8});
				new Effect.Pulsate('alarmbox', {from: 0.3, to: 0.8, pulses: 2, duration: 3, queue: 'end'});
				new Effect.Fade('alarmbox', {to: 0.8, duration: 0.5, queue: 'end'});
				
				// set cookie to avoid displaying again today (8 hours)
				var expireDate = new Date();
				expireDate.setTime( expireDate.getTime() + 1000*60*60*8 ); // 8 hours
				jQuery.cookie('shown_powder_alarm_'+destId, new Date(), {expires: expireDate, path: '/'});
			}
		}		
	};
	
	this.reportsLoaded = false;
	
	this.loadReports = function(callback) {
		if (Skiinfo.Login.currentUser && $j("#login_mysnowreports").size()>0) {
			$j("#login_mysnowreports").load("/portlets/7/skiinfo/myskiinfo/subscribed_snowreports.jsp", callback);
			Skiinfo.reportsLoaded = true;
		}
	};

	
	// Connect a country select with a destination select
	// Use CSS3 syntax for the ID's
	// I.e. '#imageCountryCode', '#imageDestId'
	// Or you can use form name and select name: 'form[name=exampleForm] select[name=countryCode]', 'form[name=exampleForm] select[name=destId]'
	// See jQuery selector documentation for full details: http://docs.jquery.com/Selectors
	this.initDynamicCountryDestSelectors = function(countrySelectId, destSelectId, chooseDestTrKey) {
		// find select elements
		var countrySelect = $j(countrySelectId);
		var destSelect = $j(destSelectId);

		if(countrySelect.size()==0 || destSelect.size()==0) { return; }
		
		// add onchange for country select
		countrySelect.change(function(event) {
			var countryCode = countrySelect.val();
			var oldDestId = destSelect.val();
			
			destSelect.removeOption(/.*/); // clear destId list
			
			if(countryCode == '') {
				destSelect.addOption({'': Skiinfo.getTr('product.skiinfo.SelectCountryFirst')});
				return;
			} else {
				destSelect.addOption({'': Skiinfo.getTr('product.lounge.LoadingData')+'...'});
			}
			
			// load destination hash
			Skiinfo.getDestinationsById(countryCode, function (dests) {
			
				// add result
				destSelect.removeOption(/.*/); // clear dest list
				destSelect.addOption(dests, false).sortOptions(); // add destinations and sort
				
				// check if no dests for country
				if(destSelect.get(0).options.length == 0) {
					destSelect.removeOption(/.*/);
					if(countryCode == '') {
						destSelect.addOption({'': Skiinfo.getTr('product.skiinfo.SelectCountryFirst')});
					} else {
						destSelect.addOption({'': Skiinfo.getTr('product.skiinfo.NoDestsForCountry')});
					}
				} else { // insert 'Choose destination' at top of select
					var elSel = destSelect.get(0);
					var elOptNew = document.createElement('option');
					elOptNew.value = '';
                                        if (!chooseDestTrKey) {
                                           chooseDestTrKey = 'global.chooseDestination';
                                        }
					elOptNew.text = Skiinfo.getTr(chooseDestTrKey);
					elOptNew.selected = true;
					
					try {
						elSel.add(elOptNew, elSel.options[0]); // standards compliant; doesn't work in IE
					}
					catch(ex) {
						elSel.add(elOptNew, 0); // IE only
					}
				}
				
				// if a destination was selected before, make it selected again
				if(oldDestId && oldDestId.length>0 && destSelect.containsOption(oldDestId)) {
					destSelect.selectOptions(oldDestId);
				}
			});
		});
		
		
		// if a country is selected already, fire onchange to
		// load destinations in the selected country
		if(countrySelect.selectedValues().length == 1 && countrySelect.selectedValues()[0].length==2) {
			countrySelect.trigger('change');
		}
	};
	
	this.initQuickSubscribe = function() {
		$j('form#quicksubscribe').ajaxForm({success: function(data) { alert(data); }});
	};
	
	// get a hashmap of destination names with destId as key
	this.getDestinationsById = function(countryCode, callback) {
		if(!countryCode || countryCode.length==0) { return {}; }
		$j.getJSON('/lounge/ajax', {'USERLANG':Skiinfo.getLanguage(),'action':'getDestinationsForCountry', 'countryCode': countryCode}, callback);
	};
	
	this.showMessage = function(id, clazz, msg) {
		$j('#'+id).html('<ul id="loungeMessages" class="'+clazz+'"><li>'+msg+'</li></ul>');
	};
	
	this.showInfo = function(id, msg) {
		showMessage(id,'info',msg);
	}
	
	this.showError = function(id, msg) {
		showMessage(id,'errors',msg);
	}
	
	this.debug = function(msg) {
	    if (window.console && window.console.log) {
	        console.log(msg);
	    }
	};
	
	this.error = function(msg) {
	    if (window.console && window.console.error) {
	        console.error(msg);
	    }
	};
	
	this.selectTopMenuItem = function(item, targetName) {
		clearTimeout(menuTimer);
		
		// Find current selected topmenu
		var currentSelected = $j("#menuTopLevels").attr("class");
		
		if(currentSelected==targetName) return;
		
		// hide the submenu
		if(currentSelected) {
			$j(".menuSubLevels."+currentSelected).hide();
		}
		// remove the selected class from current top menu item
		$j("#menuTopLevels li a.selected").removeClass("selected");
		
		if(item && targetName && targetName!="Frontpage") {
			// Set new class for top menu
			$j("#menuTopLevels").attr("class", targetName);
			// add selected class to the new top menu item
			$j(item).find("a").addClass("selected");
			// Show submenu for new selected top menu item
			$j(".menuSubLevels."+targetName).show();
		} else {
			$j("#menuTopLevels").attr("class", "");
		}
	};
	
	this.menuMouseOut = function() {
		clearTimeout(menuTimer);
		menuTimer = setTimeout(resetTopMenu, 200);
	};
	
	this.resetTopMenu = function() {
		this.selectTopMenuItem($j("#menuTopLevels li:has(a.originalSelected)").get(0), originalTarget);
	};
	
	return this;
}();

/**
 * Class: Skiinfo.Login
 *
 * Singelton object for maintaining a users login state
 * 
 */
Skiinfo.Login = function() {

	//  defaults, may be overridden by implementation
	
	this.reloadOnLogin = false;
	this.defaultPrefix = "login";
	
	/**
	 * Property: currentUser
	 * {<SkiinfoUser>} The current logged in user, or null if not logged in
	 */
	this.currentUser = null;
	
	/**
	 * Property: currentUser
	 * {Number} The current logged in user's userId, or -1 if not logged in
	 */
	this.currentUserId = -1;
	
	this.requireNick = false;
	this.requireNickForm = null;
	this.requireNickOnSubmit = null;
	
	this.requireUser = false;
	this.requireUserForm = null;
	this.requireUserOnSubmit = null;
	
	// internal form cache
	this.forms = {};
	
	function getPrefix(prefix) {
		return (prefix ? prefix : this.defaultPrefix);
	}
	
	/** 
	 * Function load
	 * Loads login_signup_2008.jsp with ajax. It is used for the popup-logins
	 * for comments.
	 *
	 * Params:
	 * idPrefix - the prefix used for html element id's in login_signup_2008 (must be unique for a page)
	 * form - the form we want to hijack submit, so we can popup the login/signup
	 * onSubmit - the old onsubmit if any. will be executed after the user logs in
	 */
	this.load = function(idPrefix, form, onSubmit) {
		Skiinfo.Login.requireNickOnSubmit = onSubmit;
		Skiinfo.Login.requireNickForm = form;
		if(form) {
			Skiinfo.Login.requireNick = true;
		}
		$j.get('/portlets/7/skiinfo/myskiinfo/login_signup_2008.jsp', {'idPrefix':idPrefix}, function(data, textStatus) {
			$j('#loginFormsContainer').remove();
			
			$j('body').append("<div id='loginFormsContainer' class='jqmWindow' style='width:300px'>"+data+"</div>");
			
			Skiinfo.Login.init(idPrefix);
			$j('#loginFormsContainer').jqm({trigger: false});
			$j('#loginFormsContainer').jqmShow();
		});
		return false;
	}
	
	this.loadU = function(idPrefix, form, onSubmit) {
		Skiinfo.Login.requireUserOnSubmit = onSubmit;
		Skiinfo.Login.requireUserForm = form;
		if(form) {
			Skiinfo.Login.requireUser = true;
		}
		$j.get('/portlets/7/skiinfo/myskiinfo/login_signup_2008.jsp', {'idPrefix':idPrefix}, function(data, textStatus) {
			$j('#loginFormsContainer').remove();
			
			$j('body').append("<div id='loginFormsContainer' class='jqmWindow' style='width:300px'>"+data+"</div>");
			
			Skiinfo.Login.init(idPrefix);
			$j('#loginFormsContainer').jqm({trigger: false});
			$j('#loginFormsContainer').jqmShow();
		});
		return false;
	}
	
	/**
	 * Function init
	 * Initializes the login_signup_2008.jsp forms for a given prefix
	 *
	 * Params:
	 * prefix - the prefix used for html element id's in login_signup_2008 (must be unique for a page)
	 */
	this.init = function(prefix) {
		var idPrefix = getPrefix(prefix);

		var login = $j('#'+idPrefix+'_login_box');
		var signup = $j('#'+idPrefix+'_newuser_box');
		var forgotpw = $j('#'+idPrefix+'_forgotpw_box');
		var missingNick = $j('#'+idPrefix+'_edit_profile_box');

		// INIT LOGIN
		// Remove old onsubmit for the login form if any, and add this instead
		login.find('form').unbind('submit').submit(function() {
			Skiinfo.Login.clearLoginMessage();
			pw2md5($j('input[name=p]', login).get(0),$j('input[name=p_md5]', login).get(0)); // calculate MD5 from password field
			$j('input[name=p]', login).val('');
			$j('.wait_animation', login).show();
			
			// ajax request to ski_ajax, Skiinfo.Login.loginResult is the callback function
			$j.getJSON('/community/ski_ajax.jsp', {	
				'action':'login',
				'username':$j('input[name=l]', login).val(),
				'md5':$j('input[name=p_md5]', login).val()
				}, Skiinfo.Login.loginResult);
			return false;
		});
		
		// Initialize validataion for the forms
		// Validation is done with jQuery.validate
		// http://docs.jquery.com/Plugins/Validation/validate#options
		
		
		// INIT SIGNUP
		$j('form', signup).validate({
			submitHandler: function() { // Callback for handling the actual submit when the form is valid
				$j('.wait_animation', signup).fadeIn("fast");
				
				// ADV-158 START
				var r=Math.floor(Math.random()*999999);
				$j.getScript('http://ads.karbon.no/www/delivery/tjs.php?trackerid=1&r=' + r);
				// ADV-158 STOP
				
				// use jQuery Form plugin to serialize the form and submit with ajax
				// http://www.malsup.com/jquery/form/#api
				$j("form", signup).ajaxSubmit({
					dataType: 'json',
					success: Skiinfo.Login.loginResult
				});
				return false;
			},
			/* validation rules */
			rules: { // Key/value pairs defining custom rules
				'email': {
					required: true,
					email: true,
					usernameFree: true
				},
				'password': {
					required: true,
					minlength: 5,
					maxlength: 64
				},
				'nickname': ((idPrefix=='nick_required') ?
					{
						required: true,
						nicknameFree: true,
						minlength: 3,
						maxlength: 63
					} :
					{
						nicknameFree: true,
						minlength: 3,
						maxlength: 63
					}
				)
			},
			/* validation messages */
			messages: { // Key/value pairs defining custom messages
				'email': {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.EmailRequired'),
					email: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.EnterValidEmail'),
					usernameFree: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.EmailTaken')
				},
				'nickname': {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickRequired'),
					nicknameFree: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickTaken'),
					minlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMinLength'),
					maxlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMaxLength')
				},
				'password': {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.PasswordRequired'),
					minlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.PasswordMinLength'),
					maxlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.PasswordMaxLength')
				}
			}
		});
		
		// MISSING NICK
		$j('form', missingNick).validate({
			submitHandler: function() { // Callback for handling the actual submit when the form is valid
				$j('.wait_animation', missingNick).fadeIn("fast");
				
				// use jQuery Form plugin to serialize the form and submit with ajax
				// http://www.malsup.com/jquery/form/#api
				$j("form", missingNick).ajaxSubmit({
					dataType: 'json',
					success: Skiinfo.Login.updateNickResult // success callback function
				});
				return false;
			},
			/* validation rules */
			rules: { // Key/value pairs defining custom rules
				'nickName': {
					required: true,
					nicknameFree: true,
					minlength: 3,
					maxlength: 63
				}
			},
			/* validation messages */
			messages: { // Key/value pairs defining custom messages
				'nickName': {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickRequired'),
					nicknameFree: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickTaken'),
					minlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMinLength'),
					maxlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMaxLength')
				}
			}
		});
		
	};
	
	
	/**
	 * Function initRequiredNickForms
	 * Find all forms with the class 'nick_required' and hijack the
	 * onsubmit to display the login / signup box when not logged
	 * in, or missing nickname.
	 */
	this.initRequiredNickForms = function() {
		$j('form.nick_required').each(function (i) {
			var form = $j(this);
			var onSubmit = form[0].onsubmit; // save original submit for later
			
			// Add onsubmit function for the form
			form.submit(function() {
				// We only have to load the form the first time a user press the submit button.
				// So we unbind the function we are creating here, and replacing it with a
				// function that only shows the popup again. It should contain the same content
				// as when the user clicked outside the popup.
				form.unbind('submit');
				form.submit(function(){ $j('.jqmWindow').jqmShow(); return false;/* stop submit */ });
				Skiinfo.Login.load('nick_required', form);
				return false; // stop submit
			});
		});
	};
	
	/**
	 * Function submitNickRequiredForm
	 * Executed when the user is successfully logged in with
	 * a nickname after login / signup / adding nickname
	 */
	this.submitNickRequiredForm = function() {
		if(Skiinfo.Login.requireNickForm) {
			// we have a form that we want to submit after login and nick
			
			// remove our onsubmit hijack
			Skiinfo.Login.requireNickForm.unbind('submit');
						
			if(Skiinfo.Login.requireNickOnSubmit) {
				// add old onsubmit function
				Skiinfo.Login.requireNickForm.submit(Skiinfo.Login.requireNickOnSubmit);
			}
			
			// submit the form
			Skiinfo.Login.requireNickForm[0].submit();
		}
		
		// reset
		Skiinfo.Login.requireNick = false;
		Skiinfo.Login.requireNickOnSubmit = null;
		Skiinfo.Login.requireNickForm = null;
	};
	
	/**
	 * Function initRequiredUserForms
	 * Find all forms with the class 'user_required' and hijack the
	 * onsubmit to display the login / signup box when not logged
	 * in.
	 */
	this.initRequiredUserForms = function() {
		$j('form.user_required').each(function (i) {
			var form = $j(this);
			var onSubmit = form[0].onsubmit; // save original submit for later
			
			// Add onsubmit function for the form
			form.submit(function() {
				// We only have to load the form the first time a user press the submit button.
				// So we unbind the function we are creating here, and replacing it with a
				// function that only shows the popup again. It should contain the same content
				// as when the user clicked outside the popup.
				form.unbind('submit');
				form.submit(function(){ $j('.jqmWindow').jqmShow(); return false;/* stop submit */ });
				Skiinfo.Login.loadU('user_required', form, onSubmit);
				return false; // stop submit
			});
		});
	};
	
	/**
	 * Function submitUserRequiredForm
	 * Executed when the user is successfully logged in.
 	 */
	this.submitUserRequiredForm = function() {
		if(Skiinfo.Login.requireUserForm) {
			// we have a form that we want to submit after login and nick
			
			// remove our onsubmit hijack
			Skiinfo.Login.requireUserForm.unbind('submit');
						
			var doSubmit = true;
			if(Skiinfo.Login.requireUserOnSubmit) {
				// add old onsubmit function
				doSubmit = (true == Skiinfo.Login.requireUserForm.submit(Skiinfo.Login.requireUserOnSubmit));
			}
			
			// submit the form
			if(doSubmit) {
				Skiinfo.Login.requireUserForm[0].submit();
			}
		}
		
		// reset
		Skiinfo.Login.requireUser = false;
		Skiinfo.Login.requireUserOnSubmit = null;
		Skiinfo.Login.requireUserForm = null;
	};
	
	/**
	 * Function: showWelcome
	 * 
	 * Fade in the welcome div
	 */
	this.showWelcome = function() {
		if (Skiinfo.Login.currentUser   &&   $j('#login_signup_box').size() > 0) {
			if(Skiinfo.Login.currentUser.nickName) {
				$j('#login_signup_box .userName').text(Skiinfo.Login.currentUser.nickName);
			} else {
				$j('#login_signup_box .userName').text(Skiinfo.Login.currentUser.userName);
			}
			
			if($j('#login_signup_box').css("display") == "none") {
				$j('#login_signup_box').slideDown(100);
			}
		}
	};
	
	/**
	 * Function: loginMessage
	 * 
	 * Display a message in the login box
	 *
	 * Parameters:
	 * msg - {String} The text (html) to display
	 */
	this.loginMessage = function(msg) {
		$j('.login_message').html(msg).show('slow');
	};
	
	/**
	 * Function: clearLoginMessage
	 * 
	 * Remove the login message
	 */
	this.clearLoginMessage = function() {
		$j('.login_message').hide().html('');
	};
	
	/**
	 * Function: updateNickMessage
	 * 
	 * Display a message in the update nick box
	 *
	 * Parameters:
	 * msg - {String} The text (html) to display
	 */
	this.updateNickMessage = function(msg) {
		$j('.update_nick_message').html(msg).show('slow');
	};
	

	/**
	 * The callback from a login / signup / nick change. The result is
	 * generated by myskiinfo_ajax.jsp, and is a json object of a 
	 * simplified SkiinfoUser (Java Object).
	 */
	this.loginResult = function(skiinfoUser) {
	    Skiinfo.Login.setCurrentUser(skiinfoUser);
	    
	    // Reload page if successful login and reloadOnLogin is true
	    if (Skiinfo.Login.currentUserId > -1 && Skiinfo.Login.reloadOnLogin) {
	    	window.location.reload();
	    	return;
	    }
		
		// Stop the wait animation
		$j('.wait_animation').hide();
		
		
		// If a user is logged in
		if (Skiinfo.Login.currentUser) {
			$j(".afterLogin").show(); // show all elements with class afterLogin
			$j(".preLogin").hide(); // show all elements with class preLogin
			
			if(!Skiinfo.Login.currentUser.nickName && Skiinfo.Login.requireNick) {
				// nickName required and user has no nick
				$j('.missing_nick_box').show();
			} else {
				// successful login and user has nickname
				$j('.jqmWindow').jqmHide();
				Skiinfo.Login.submitUserRequiredForm();
				Skiinfo.Login.submitNickRequiredForm();
			}
		} else {
			Skiinfo.Login.loginMessage(Skiinfo.getTr('product.skiinfo.WrongUserOrPass'));
		}
	};
	
	this.updateNickResult = function(json) {
		if(json && json.status) {
			if(json.status=='OK') {
				$j('.jqmWindow').jqmHide();
				$j('.missing_nick_box').slideUp();
				Skiinfo.Login.whoAmI();
				Skiinfo.Login.submitNickRequiredForm();
			} else {
				Skiinfo.Login.updateNickMessage(json.message);
			}
		} else {
			Skiinfo.Login.updateNickMessage(Skiinfo.getTr('product.lounge.ErrorUpdatingNick'));
		}
		$j('.wait_animation').hide();
	};
	
	/**
	 * Function: setCurrentUser
	 * 
	 * Set the current user
	 *
	 * Parameters:
	 * json - {<SkiinfoUser>}
	 */
	this.setCurrentUser = function(json) {
		Skiinfo.Login.currentUser = json;
    	if(Skiinfo.Login.currentUser) {
    		Skiinfo.Login.currentUserId = Skiinfo.Login.currentUser.userId;
    		//Skiinfo.showWelcome();
    		//Skiinfo.loadReports();
    		
    		if(!Skiinfo.Login.currentUser.nickName) {
    			Skiinfo.Login.initRequiredNickForms();
    		}
    	} else {
    		Skiinfo.Login.currentUserId = -1;
    		Skiinfo.Login.initRequiredNickForms();
    		Skiinfo.Login.initRequiredUserForms();
    	}
	};
	
	/**
	 * Function: userIsLoggedIn
	 * 
	 * Check if a user is logged in
	 *
	 * Returns:
	 * {boolean}
	 */
	this.userIsLoggedIn = function() {
		return this.currentUserId > 0;
	};
	
	/**
	 * Function: userHasNickName
	 * 
	 * Check if a user is logged in and has a nickname
	 *
	 * Returns:
	 * {boolean}
	 */
	this.userHasNickName = function() {
		return this.currentUser && this.currentUser.nickName && jQuery.trim(this.currentUser.nickName).length > 0 ;
	};
	
	/**
	 * Function: userProfileEnabled
	 * 
	 * Check if a user has enabled profile
	 *
	 * Returns:
	 * {boolean}
	 */
	this.userProfileEnabled = function() {
		return this.currentUser && this.currentUser.profileEnabled == true;
	};

	/**
	 * Property: hosts
	 * {Array<String>} List of skiinfo hostnames
	 */
	this.hosts = [ "www.skiinfo.com","www.skiinfo.it","www.skiinfo.no","www.skiinfo.fr" ] ;

	/**
	 * Function: logout
	 * 
	 * Logout the current user on all skiinfo hostnames
	 */
	this.logout = function() {
	        var img = document.createElement("img");
		img.src="/community/ski_ajax.jsp?logout=true&action=logout&/t.gif";
 		img.id="logon_logout";

		for (var i = 0; i<this.hosts.length; i++) {
		 var img = document.createElement("img");
		 img.src="http://"+this.hosts[i]+"/community/ski_ajax.jsp?logout=true&action=logout&a=/t.gif";
 		 img.id="logon_"+ this.hosts[i];
		}
	};

	/**
	 * Function: updateCookies
	 * 
	 * Update login cookies or logout if Skiinfo.Login.doLogout is true
	 */
	this.updateCookies = function() {
		if (this.doLogout) {
			this.logout();
			return;
		}	
		if ($j.cookie("skiinfo_multi")) return;

		var cauth = $j.cookie("skiinfo_auth");

		if (cauth && cauth.length>0 && cauth.split("-").length==2) {
			cauth = cauth.replace('"','');
			cauth = cauth.replace('\+','%2b');
			for (var i = 0; i<this.hosts.length; i++) {
			 var img = document.createElement("img");
			 img.src="http://"+this.hosts[i]+"/community/ski_ajax.jsp?skiinfo_auth="+cauth+"&/t.gif";
 			 img.id="logon_"+ this.hosts[i];
			}
			
		}
	};
	
	/**
	 * Function: whoAmI
	 * 
	 * Do an ajax request to get the current user
	 *
	 * Parameters:
	 * callback	- Callback to run after we get the response. The skiinfo user
	 *			  is sent as the only parameter to the callback function.
	 */
	this.whoAmI = function(callback) {
		$j.getJSON('/community/ski_ajax.jsp', {'action':'whoami'}, function(json) {
			Skiinfo.Login.setCurrentUser(json);
			if(callback) { callback(Skiinfo.Login.currentUser);	}
		});
	};
	
	/**
	 * Function: usernameIsFree
	 * 
	 * Do an ajax request to see if a username is taken
	 * 
	 * Parameters:
	 * username - {String}
	 */
	this.usernameIsFree = function (username) {
		var responseText = $j.ajax({
			url: '/community/ski_ajax.jsp',
			async: false,
			dataType: 'json',
			data: {
				'action': 'usernameIsFree',
				'username':  username
			}
		}).responseText;
		var result = eval("(" + responseText + ")");
		return result.usernameFree;
	};
	
	/**
	 * Function: nickIsFree
	 * 
	 * Do an ajax request to see if a nickname is taken
	 *
	 * Parameters:
	 * nickName - {String}
	 */
	this.nickIsFree = function (nickName) {
		var responseText = $j.ajax({
			url: '/community/ski_ajax.jsp',
			async: false,
			dataType: 'json',
			data: {
				'action': 'nickIsFree',
				'nick':  nickName
			}
		}).responseText;
		var result = eval("(" + responseText + ")");
		return result.nickIsFree;
	};
	
	return this;
}();





/**
 * Class: Skiinfo.LoginForm
 *
 * Initialize and display login form. If the form with the specified prefix
 * already is in the document tree, it will be re-used. If not, it will be
 * loaded by ajax.
 * 
 */
Skiinfo.LoginForm = function() {
	// Default options
	this.options = {
			prefix: 'login',
			reloadOnLogin: false,
			requireProfileEnabled: false,
			requireNick: false,
			popup: false
	};
	this.containerId;
	
	/**
	 * Constructor: Skiinfo.LoginForm
	 * Create a javascript login form object
	 *
	 * Parameters:
	 * options - {<Skiinfo.LoginFormOptions>}	Options object
	 */
	function Constructor(options) {
		// custom options overrides defaults
		this.options = $j.extend(this.options, options);
		this.containerId = this.options.prefix + "_loginFormsContainer";
		
		if( this.options.popup ) {
			loadLoginForms.call(this);
		} else {
			initLoginForms.call(this);
		}
	}
	// Run the constructor now!
	Constructor.apply(this, arguments);
	
	/**
	 * loadLoginForms (Private)
	 * Load the html for the login/signup/nick by ajax and popup
	 */
	function loadLoginForms() {
		var loginObj = this;
		var inDOMalready = $j('#'+loginObj.containerId).size() > 0;
		
		if( inDOMalready ) {
			$j('#'+loginObj.containerId).unbind().remove();
		}
			
		$j.ajax({
			url: '/portlets/7/skiinfo/myskiinfo/login_signup_2008.jsp',
			data: {'idPrefix':this.options.prefix, 'requireNick':this.options.requireNick, 'requireProfileEnabled':this.options.requireProfileEnabled, 'popup': this.options.popup},
			success: function(data, textStatus) {
				$j('body').append("<div id='"+loginObj.containerId+"' class='jqmWindow' style='width:300px'>"+data+"</div>");
								
				$j('#'+loginObj.containerId).jqm({trigger: false});
				$j('#'+loginObj.containerId).jqmShow();
				initLoginForms.call(loginObj);
			}
		});
	}

	/**
	 * initLoginForms (Private)
	 * Add validation and submit handlers for the forms
	 */	
	function initLoginForms() {
		var idPrefix = this.options.prefix;
		var loginSel = '#'+idPrefix+'_login_box';
		var signupSel = '#'+idPrefix+'_newuser_box';
		var forgotpwSel = '#'+idPrefix+'_forgotpw_box';
		var editProfileSel = '#'+idPrefix+'_edit_profile_box';
		var loginForm = this;

		// INIT LOGIN
		// Remove old onsubmit for the login form if any, and add this instead
		$j(loginSel+' form').unbind('submit').submit(function() {
			//Skiinfo.Login.clearLoginMessage();
			pw2md5($j(loginSel+' input[name=p]').get(0),$j(loginSel+' input[name=p_md5]').get(0)); // calculate MD5 from password field
			$j(loginSel+' input[name=p]').val('');
			$j(loginSel+' .wait_animation').show();
			
			// ajax request to ski_ajax, Skiinfo.Login.loginResult is the callback function
			$j.getJSON('/community/ski_ajax.jsp', {	
				'action':'login',
				'username':$j(loginSel+' input[name=l]').val(),
				'md5':$j(loginSel+' input[name=p_md5]').val()
				}, function() {
					loginForm.loginResult.apply(loginForm, arguments);
				});
			return false;
		});
		
		
		// Initialize validataion for the forms
		// Validation is done with jQuery.validate
		// http://docs.jquery.com/Plugins/Validation/validate#options		
		
		// INIT SIGNUP
		$j(signupSel+' form').validate({
			submitHandler: function() { // Callback for handling the actual submit when the form is valid
				$j(signupSel+' .wait_animation').fadeIn("fast");
				
				// use jQuery Form plugin to serialize the form and submit with ajax
				// http://www.malsup.com/jquery/form/#api
				$j(signupSel+" form").ajaxSubmit({
					dataType: 'json',
					success: function() {
						loginForm.loginResult.apply(loginForm, arguments);
					}
				});
				return false;
			},
			/* validation rules */
			rules: { // Key/value pairs defining custom rules
				email: {
					required: true,
					email: true,
					usernameFree: true
				},
				nickname: {
						nicknameFree: true,
						minlength: 3,
						maxlength: 63,
						required: this.options.requireNick
				},
				password: {
					required: true,
					minlength: 5,
					maxlength: 64
				}
				
			},
			/* validation messages */
			messages: { // Key/value pairs defining custom messages
				email: {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.EmailRequired'),
					email: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.EnterValidEmail'),
					usernameFree: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.EmailTaken')
				},
				nickname: {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickRequired'),
					nicknameFree: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickTaken'),
					minlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMinLength'),
					maxlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMaxLength')
				},
				password: {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.PasswordRequired'),
					minlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.PasswordMinLength'),
					maxlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.PasswordMaxLength')
				}
			}
		});
		
		// MISSING NICK OR PROFILE DISABLED
		$j(editProfileSel+' form').validate({
			submitHandler: function() { // Callback for handling the actual submit when the form is valid
				$j(editProfileSel+' .wait_animation').fadeIn("fast");
				
				// use jQuery Form plugin to serialize the form and submit with ajax
				// http://www.malsup.com/jquery/form/#api
				$j(editProfileSel+' form').ajaxSubmit({
					dataType: 'json',
					success: function() {
						loginForm.updateNickResult.apply(loginForm, arguments);
					} // success callback function
				});
				return false;
			},
			/* validation rules */
			rules: { // Key/value pairs defining custom rules
				'nickName': {
					required: this.options.requireNick,
					nicknameFree: true,
					minlength: 3,
					maxlength: 63
				}
			},
			/* validation messages */
			messages: { // Key/value pairs defining custom messages
				'nickName': {
					required: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickRequired'),
					nicknameFree: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickTaken'),
					minlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMinLength'),
					maxlength: Skiinfo.getTr('product.skiinfo.MySkiinfo.Login.NickMaxLength')
				}
			}
		});
	}
	
	/**
	 * The callback from a login / signup / nick change. The result is
	 * generated by myskiinfo_ajax.jsp
	 *
	 * Parameters:
	 * skiinfoUser - json object of a  simplified SkiinfoUser (Java Object)
	 */
	this.loginResult = function(skiinfoUser) {
	    Skiinfo.Login.setCurrentUser(skiinfoUser);
		
		// Stop the wait animation
		$j('.wait_animation').hide();
		
		
		// If a user is logged in
		if (Skiinfo.Login.currentUser) {
			// Reload page if successful login and reloadOnLogin is true
			if(this.options.reloadOnLogin) {
				window.location.reload();
				return;
			}
		
			$j(".afterLogin").show(); // show all elements with class afterLogin
			$j(".preLogin").hide(); // show all elements with class preLogin
			
			if(!Skiinfo.Login.currentUser.nickName && this.options.requireNick) {
				// nickName required and user has no nick
				$j('.missing_nick_box').show();
			} else {
				// successful login and user has nickname, or nick not required
				$j('.jqmWindow').jqmHide();

				// Run callback
				if(this.options.success) {
					this.options.success.call(this, Skiinfo.Login.currentUser);
				}
			}
		} else {
			Skiinfo.Login.loginMessage(Skiinfo.getTr('product.skiinfo.WrongUserOrPass'));
		}
	};
	
	/**
	 * The callback from a nick update. The result is
	 * generated by LoungeServlet, and is a 
	 *
	 * Parameters:
	 * json - object with two properties: status and message.
	 *		  status will be 'OK' if the update was successful.
	 */
	this.updateNickResult = function(json) {
		if(json && json.status) {
			if(json.status=='OK') {
				$j('.jqmWindow').jqmHide();
				$j('.missing_nick_box').slideUp();
				Skiinfo.Login.whoAmI(this.options.success);
			} else {
				Skiinfo.Login.updateNickMessage(json.message);
			}
		} else {
			Skiinfo.Login.updateNickMessage(Skiinfo.getTr('product.lounge.ErrorUpdatingNick'));
		}
		$j('.wait_animation').hide();
	};
};

/**
 * Class: Skiinfo.LoginFormOptions
 *
 * This class represents optional arguments to the Skiinfo.LoginForm
 * constructor. It has no constructor, but is instantiated as an object
 * literal (JSON).
 * 
 * Properties:
 * prefix			- ID prefix for the html elements in the login form, an
 *					  only be one form pr prefix pr page. Default: 'login'
 * success			- Callback function after login process complete
 * reloadOnLogin	- Reload the page when successful login
 * requireNick		- Require that the user has a nickname before success
 * popup			- Popup the login form in a javascript window
 */

 // Yes, you're absolutely right, Skiinfo.LoginFormOptions doesn't exist!
 // It's just a fake comment to document the parameter object for
 // the constructor of Skiinfo.LoginForm in NaturalDocs.


// add validator rules for unique username and nickname
if(jQuery.validator) {
	jQuery.validator.addMethod("usernameFree", function(value, element, param) {
	 	if(param) {	return Skiinfo.Login.usernameIsFree(value);	}
	});
	
	jQuery.validator.addMethod("nicknameFree", function(value, element, param) {
	 	if(param) {	return Skiinfo.Login.nickIsFree(value);	}
	});
	
	/* use jquery.skiinfo plugin instead
	jQuery.validator.addMethod("userLoggedIn", function(value, element, param) {
		if( !Skiinfo.Login.userIsLoggedIn() ) {
			var currentForm = this.currentForm;
			var validateLogin = new Skiinfo.LoginForm({
				prefix: 'validate',
				success: function(skiinfoUser) {
					//$j(element).val(skiinfoUser.userId);
					$j(currentForm).trigger("submit");
				},
				popup: true
			});
			return false;
		}
		return true;
	},'');
	
	
	jQuery.validator.addMethod("userHasNick", function(value, element, param) {
		if( !Skiinfo.Login.userHasNickName() ) {
			var currentForm = this.currentForm;
			var validateLogin = new Skiinfo.LoginForm({
				prefix: 'validate',
				success: function(skiinfoUser) {
					//$j(element).val(skiinfoUser.userId);
					alert(skiinfoUser.nickName);
					$j(currentForm).trigger("submit");
				},
				popup: true,
				requireNick: true
			});
			return false;
		}
		return true;		
	},'');
	*/
}

// document onload (ready is fired when DOM tree is ready instead of all elements loaded)
$j(document).ready(function(){
	Skiinfo.Login.whoAmI();
	Skiinfo.showDynamicAlert();
	Skiinfo.Login.updateCookies();
	
	//To stop someone/something from clearing the site
	document.write = function() {};
});

// generic handler for jQuery ajax errors
$j(document).ajaxError(function(){
    Skiinfo.error(arguments);
});
