/*
 * Several forms here
 */

/*
 * Helper methods
 */

function FormUtils(){
	
}


FormUtils.prototype.addTips = function(){

	$("#layersOS_dock form :input[required][helptip]").each(function(){
		if( $(this).val() == '' || $(this).val() == null ){
			$(this).val( $(this).attr('helptip') );
		}
	});

	this.hideFakeFields();
}

FormUtils.prototype.addMessage = function(myForm, message){
	myForm.find(".layersOS_form_log").remove();
	myForm.append('<ul class="layersOS_form_log" style="display: block;"><li>' + message + '</li></ul>');
		
}


FormUtils.prototype.hideFakeFields = function(){
	// hide real password fields

    $(":input[fake_password]").hide();

    // process helptips

    $(':input[helptip]').each(function(){

        if ($(this).val() == '') {
            $(this).val($(this).attr('helptip'));
        }

    }).focus(function(){

        // if it's a fake password field
        if ($(this).attr('real_password') != undefined) {
            // hide fake password field
            $(this).hide();

            // show real password field
            $('#' + $(this).attr('real_password')).show().focus();
        }
        else 
            if ($(this).val() == $(this).attr('helptip')) {
                $(this).val('');
            }

    }).blur(function(){

        if ($(this).val() == '') {
            // if it's a real password field

            if ($(this).attr('fake_password') != undefined) {
                // hide real password field
                $(this).hide();

                // show fake password field
                $('#' + $(this).attr('fake_password')).show();
            }
            else {
                $(this).val($(this).attr('helptip'));
            }
        }
    });
}


/**
 * checkCamposObligatorios
 *
 * check form inputs that have required attribute are empty
 *
 * Created on 23/04/2009
 * @author "Rodrigo PŽrez"
 * @version <1.0>
 * 
 * @param {Object} formulario Objeto formulario
 *
 * @return {Boolean}
 */
FormUtils.prototype.checkRequiredFields = function(formulario){
			
	var resultado = true;
		
	// todos los inputs con name acabado en _required

	$("#" + formulario.id + " :input").each(function(){								
		// check required fields
		if( $(this).is("[id$='_required']") || $(this).hasClass('layersOS_required') ){
			
			if( ( $(this).attr('type') == 'text' ||  $(this).attr('type') == 'password' ) &&
			 	( $(this).val() == '' || $(this).val() == $(this).attr('helptip') ) ){

				FormUtils.prototype.addMessage( $("#" + formulario.id), STRING_form_required_fields);
			
				// ponemos el foco en el campo
				$(this).focus();
				required_field_id = $(this).attr('id');
				
				// constatamos de que hay un campo vacio
				resultado = false;
			}else if( $(this).attr('type') == 'checkbox' && !$(this).attr("checked")){
				
				FormUtils.prototype.addMessage( $("#" + formulario.id ), STRING_accept_terms_required);
				$(this).focus();
				required_field_id = $(this).attr('id');
				resultado = false;
			}else{
				resultado = true;
			}
		}else if( $(this).val() == $(this).attr('helptip') ){
			// campos no obligatorios pero con helptip
			$(this).focus();
		}
		
		//return resultado;
		
	});
	
	return resultado;
}

/*******************************************************************************************/



/*
 * LayersOSJoinForm
 */
function LayersOSJoinForm(referal, displayable){
	
	this._referal = referal;
	this._displayable = displayable;
	
	this._displayable.html('<div class="layersOS_dock_left_window_content" style="display:none;"/>').fadeIn();

	var html = this._referal._templates.joinFormHTML();
	this._referal._displayable.find('.layersOS_dock_left_window_content').html(html).show();
	
	FormUtils.prototype.addTips();
	FormUtils.prototype.hideFakeFields();
	this.enableSubmit();
}

LayersOSJoinForm.prototype._referal;
LayersOSJoinForm.prototype._displayable;

LayersOSJoinForm.prototype.enableSubmit = function(){
	var me = this;
	
	this._displayable.find('#layersOS_join_form').submit(
		function(){
			try{
				//me._displayable.find('.layersOS_form_log').hide().find('li').remove();
				$(this).find(".layersOS_form_log").remove();
				
				if( FormUtils.prototype.checkRequiredFields(this) ){
					
					if ( !Utils.prototype.checkEmail( $('#layersOS_join_email').val() ) ){
						FormUtils.prototype.addMessage( $('#layersOS_join_form'), STRING_email_wrong);
						$('#layersOS_join_email').focus();
						return false;
					}else{
						os.register( $('#layersOS_join_displayname').val(), $('#layersOS_join_password').val(), $('#layersOS_join_email').val() );
					}
					
				}else{
					FormUtils.prototype.addMessage( $('#layersOS_join_form'), STRING_form_required_fields);				
				}
				return false;
			}catch(e){
				return false;
			}
		}
	);
}

/*******************************************************************************************/

/*
 * LayersOSLoginForm
 */
function LayersOSLoginForm(referal, displayable){
	
	this._referal = referal;
	this._displayable = displayable;
	
	this._displayable.html('<div class="layersOS_dock_left_window_content" style="display:none;"/>').fadeIn();

	var html = this._referal._templates.loginFormHTML();
	this._referal._displayable.find('.layersOS_dock_left_window_content').html(html).show();
	
	FormUtils.prototype.addTips();
	FormUtils.prototype.hideFakeFields();
	this.enableSubmit();
}

LayersOSLoginForm.prototype._referal;
LayersOSLoginForm.prototype._displayable;

LayersOSLoginForm.prototype.enableSubmit = function(){
	var me = this;
	
	this._displayable.find('#layersOS_login_form').submit(
		function(){
				
			me._displayable.find('.layersOS_form_log').hide().find('li').remove();
			if( FormUtils.prototype.checkRequiredFields(this)  ){
				os.login( $('#layersOS_login_user').val(), $('#layersOS_login_password').val() );
			}else{
				FormUtils.prototype.addMessage($('#layersOS_login_form'), STRING_form_required_fields);				
			}
			
			me._displayable.hide();			
			me._referal._loginButton.enable();
			return false;
		}
	);
}



/*******************************************************************************************/


/*
 * LayersOSEditTitleForm
 */
function LayersOSEditTitleForm(referal, displayable){
	
	this._referal = referal;
	this._displayable = displayable;			
	try{
		var html = this._referal._templates.editTitleFormHTML(os.currentLayer._title);	
		this._referal._displayable.find('#layersOS_mylayer_title').html(html).show();		
	}catch(e){
		console.info(e);
	}
	
	// set focus on title field
	$('#layersOS_mylayer_title_form [name=title]').select();	
	
	FormUtils.prototype.addTips();
	FormUtils.prototype.hideFakeFields();	
	this.enableSubmit();
}

LayersOSEditTitleForm.prototype._referal;
LayersOSEditTitleForm.prototype._displayable;

LayersOSEditTitleForm.prototype.checkRequiredFields = function(){
	alert("checkRequiredFields");
}


LayersOSEditTitleForm.prototype.enableSubmit = function(){
	
	var me = this;
		
	me._displayable.find('#layersOS_mylayer_title_form').submit(
		
		function(){	
			var title = $('#layersOS_mylayer_title_form [name=title]').val();
			
			me._referal.setTitleText(title);			
				
			$('#layersOS_mylayer_title').hide();
	
			me._referal._layerTitleButton._displayable.removeClass('layersOS_dock_item_selected');			
												
			return false;				
		}				
		
	);
}


/*******************************************************************************************/


/*
 * LayersOSSendEmailForm
 */
function LayersOSSendEmailForm(referal, displayable){
	
	this._referal = referal;
	this._displayable = displayable;			

	var html = this._referal._templates.sendEmailFormHTML();	
	this._displayable.append(html).show();
	
	var me = this;
		
	// set click event on cancel button
	$('#layersOS_email_cancel').click(
		function(){			
			me.cancelButtonClick();	
		}	
	);
	
	// set focus on title field
	//$('#layersOS_email_form [name=email]').select();	
	
	FormUtils.prototype.addTips();
	FormUtils.prototype.hideFakeFields();	
	this.enableSubmit();
}

LayersOSSendEmailForm.prototype._referal;
LayersOSSendEmailForm.prototype._displayable;

LayersOSSendEmailForm.prototype.enableSubmit = function(){
	
	var me = this;
		
	me._displayable.find('#layersOS_email_form').submit(
				
		function(){
			
			if ( FormUtils.prototype.checkRequiredFields(this) ){
				// hide and empty form log
	            me._displayable.find('.layersOS_form_log').hide().find('li').remove();				
									
				var emailOK = true;
				var myEmails = $("#layersOS_email_form [name='email']").val().split(',');
				for (var email in myEmails){					
					if ( !Utils.prototype.checkEmail(myEmails[email])) emailOK = false;
				};
			
	            if( !emailOK )
	            {
					FormUtils.prototype.addMessage($('#layersOS_email_form'), STRING_email_wrong);			                
					return false;
	            }
				else{
				
					try{
						me.disableSubmitButton();															
						os.sendMail('',
									myEmails,  
									$("#layersOS_email_form [name='subject']").val(), 
									$("#layersOS_email_form [name='message']").val());
					}catch(e){
						console.error(e);
						// Do nothing
					}
					
				}	
			}
			else {
				FormUtils.prototype.addMessage($('#layersOS_email_form'), STRING_form_required_fields);
			}
			            						
			return false;						
		}				
		
	);
}


LayersOSSendEmailForm.prototype.disableSubmitButton = function(){		
	this._displayable.find('#layersOS_email_submit')
									.addClass('layersOS_dock_item_disabled')
									.attr('disabled', 'true');
}

LayersOSSendEmailForm.prototype.enableSubmitButton = function(){
	this._displayable.find('#layersOS_email_submit')
									.removeClass('layersOS_dock_item_disabled')
									.removeAttr('disabled');
}

LayersOSSendEmailForm.prototype.cancelButtonClick = function(){
	$('#layersOS_send_email').hide();
	this._referal._emailButton._displayable.removeClass('layersOS_dock_item_selected');
	return false;
}


/*******************************************************************************************/




