function Inet() {
	var self = this;
	self._init();
};

// -- COMPROBAR SI EXISTE VERSION MOBILE
function checkMobile () {	
	// URL de localización de los datos del usario	
	var urlLocation = configuration.getUrlPwdRecover() + "/user-location-detection";

	var urlAppDownload = "http://www.inditex.net/app/";
	var htmlExtension = ".html";
	
	// IPs para las que no se debe mostrar el mensaje aunque el codigo de pais sea ES
	var ips = ["178.60.200.142", "195.55.66.182", "178.60.198.247"];

	// Nombre de la cookie
	var cookieName = "TrueClientIP";

	$.get(urlLocation, function(data) {
		var obj = data, mostrar = false;	
		if (null != obj.country_code && undefined != obj.country_code && configuration.appCountryList.indexOf(obj.country_code.toUpperCase()) != -1) {
			var true_client_ip = getCookie(cookieName);
			if (true_client_ip != "") {
				if ($.inArray(true_client_ip, ips) == -1) {
					var localeUrl = "";
					if(configuration.appConuntryDownloadList[obj.country_code.toUpperCase()]) {
						localeUrl = configuration.appConuntryDownloadList[obj.country_code.toUpperCase()];
					}
					var urlAppDownloadFinal = urlAppDownload + localeUrl;
					$('#appDownload').html(i18n.msg('index.descargar.app'));
					$('#appDownload').prop('href', urlAppDownloadFinal);
					$('.app').css('display', 'inline-block');
				}
			}
		}
	});
};

function getCookie (cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
};

// -- FIN COMPROBAR SI EXISTE VERSION MOBILE

/**Contexto de la aplicación*/
Inet.context = undefined;

/**Directorio donde van a estar los html*/
Inet.rootPath = undefined;

/**variable global para establecer el host para las peticiones REST*/
Inet.pwdrecoverWSContext = undefined;


Inet.prototype._init = function() {
	
	var self = this;
	
	self.grecaptchaImport = '<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?onload=onLoadCatpcha&render=explicit"></script>';
	
	self.context = self._getContext();
	self.rootPath = configuration.getRootPath();
	self.pwdrecoverWSContext = configuration.getUrlPwdRecover();
	self.siteKey = configuration.getSiteKey();
	self.countryCode = undefined;
	
};



/**
 * Recuperación del contexto
 */
Inet.prototype._getContext = function() {
	
	var self = this;
	
	var pathName = document.location.pathname;
	return pathName.replace(/\/[^\/]+$/,"/");
};


/**
 * Carga el fichero de internacionalización
 */
Inet.prototype.loadI18n = function() {
	
	var self = this;
	var language = navigator.languages ? navigator.languages[0] : navigator.language||navigator.browserLanguage;
	self._loadI18n(language);
	
};

Inet.prototype._loadI18n = function(language) {
	var self = this;
	var urlI18N = self.context+self.rootPath+"/js/i18n/"+language.toLowerCase()+".js";
	
	$.ajax({
		async:false,
		type:'GET',
		url:urlI18N,//"contenido/js/i18n/"+language+".js",
		data:null,
		success:function(data) {},
		dataType:'script',
		cache: true,
		error: function(xhr, textStatus, errorThrown) {
			var lang = language.split('-');
			if(lang.length > 1) {
				self._loadI18n(lang[0]);
			}
		}
	});
}


Inet.prototype.test = function(text) {
	var self = this;
	var url = self.generateUrl('recuperar_final',{});
	
	self.renderUrl({
		"url": url,
		"onSuccess": function(aText) {
			$('#msmFinal').append(aText);
			
		},
		"onFailure": function(aStatus) {
			alert('error');
		}
			});	
	
};

/**
 * Construye la url
 * @action nombre del html a cargar, sin en html
 * @params conjunto de atributo:valor que va a ir en la url
 * @module si se agrupa dentro de directorio rootPath
 */
Inet.prototype.generateUrl = function(action, params,module) {
	var self = this;
	var result;
	var i;
	var tmp;
		
	if (self.context !== undefined) {
		result = self.context;
	} else {
		throw "Inet.generateUrl: Missing attribute 'context'.";
	}
	
	result += self.rootPath;
				
	if (module){
		result += "/"+module;
	}
	
	result += "/"+action+".html";
	

	tmp = null;
	if (params){
		for (i in params) {
			if ((params[i] != null) && (params[i] != undefined)) {
				if (tmp == null) {
					tmp = "?";
				} else {
					tmp += "&";
				}
				
				tmp += encodeURIComponent(i) + "=" + encodeURIComponent(params[i]);
			}
		}
	}
	
	if (tmp) {
		result += tmp;
	}
	
	return result;
};

/**
 * Renderiza las plantillas usando underscore
 */
Inet.prototype.renderTemplate = function(templateUrl, params) {
	
	var self = this;
	var textContent = null;

	$.ajax({
		context: this,
		async : false,
		type: 'GET',
		url : templateUrl,
		success : function(result) {
			textContent = result;
		},
		dataType: 'html'
	});
	
	if (!textContent) {
		throw 'Error loading template: ' + templateUrl;
	}else{
		textContent = self.parserTemplateContent(textContent, params);
	}
	
	return textContent;
	
	
};

/**
 * LLamada a underscore para la sustitución de parámetros
 */
Inet.prototype.parserTemplateContent = function(textContent, params) {
	var template = null;
	if (params){
		// -- si se traen parámetros se renderiza la plantilla con underscore
		template = _.template(textContent);
		template = template(params);
	}else{
		template = textContent;
	}
	
	
	return template;
	
	
};


/**
 * Renderiza la url indicada como parte del atributo options
 * @deprecated
 */
Inet.prototype.renderUrl = function(options) {
	var self = this;
			
	if ((location.protocol == 'http:' && /^https:/.test(options.url)) || (location.protocol == "https:" && /^http:/.test(options.url))) {
		// Cross domain request
			
		optionsArray.push(options);
		
		doMessage();
		
	} 

	// Not cross domain request
	else {
		var tieneDatos = false;
		if (options.data && options.data.length > 0) {
			tieneDatos = true;
		} 
		if (typeof XDomainRequest == 'object' &&  !tieneDatos && !(new RegExp("^(http|https)://" + location.host).test(options.url)) && (new RegExp("^(http|https)://").test(options.url))) {
			
			var xdr = new XDomainRequest();
			xdr.onload = function() {
				if (options.onSuccess) {
					options.onSuccess(xdr.responseText);
				}
			};
			xdr.onerror = function() {
				if (options.onFailure) {
					options.onFailure();
				}
			};
			
			xdr.open("GET", options.url);
			xdr.send();
		}
		else{
			
			var xmlhttp = false;
			
			try {
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e1) {
				try {
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			    } catch(e2) {
			    	xmlhttp = false;
			    }
			}
	
			if(!xmlhttp && typeof XMLHttpRequest != 'undefined') {
				xmlhttp = new XMLHttpRequest();
			}
			   
			if (options.data && options.data.length > 0) {
				xmlhttp.open('POST', options.url, self.iAjaxAsync);
				xmlhttp.setRequestHeader("Content-type", options.contentType ? options.contentType : "application/x-www-form-urlencoded");
			} else {
				xmlhttp.open('GET', options.url, self.iAjaxAsync);
				xmlhttp.setRequestHeader("Content-type", options.contentType ? options.contentType : "application/x-www-form-urlencoded");
			}
			
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 1) {
					if (options.onStart) {
						options.onStart();
					}
				} else if (xmlhttp.readyState == 4) {
					if (xmlhttp.status == 200) {
						if (options.onSuccess) {
							options.onSuccess(xmlhttp.responseText);
						}
					} else {
						if (options.onFailure) {
							options.onFailure(xmlhttp.status);
						}
					}
				}
			};
			    
			xmlhttp.send(options.data);
		}
	}
};

/**
 * Recupera los paises
 */
Inet.prototype.getCountries = function(divClassIframe, className) {

	var countrySelect;
	var selectPicker;
	var clazz;
	
	if(className) {
		clazz = '.'+ className +' .countrySelect';
	} else {
		clazz = '.countrySelect';
	}
	if(divClassIframe) {
		countrySelect = $('.'+divClassIframe).contents().find(clazz);
	} else {
		countrySelect = $(clazz);
	}
	
	userServiceFacade.getCountries(function(data) {
			var html = '<option value=-1>'+i18n.msg('country.select')+'</option>';
			for(i = 0; i < data.length; i++) {
				html = html + '<option value='+data[i].countryId+'>'+data[i].country+'</option>';
			};
			countrySelect.html(html);
			
	}, function(){}, this);
};

/**
 * Inicializa los eventos del index
 */
Inet.prototype.initIndex = function() {

	var self = this;
	
	self.getUserLocation();
	
	document.title = i18n.msg('index.title');
	
	if (!$.support.leadingWhitespace){
		
		$( "<input class='index_passIndex' type='text' name='fake_pass' id='fake_pass' style='display:none'/>" ).insertBefore( $( "#real_pass" ) );
		
		$('#fake_pass').val(i18n.msg('index.password'));
		$('#real_pass').hide();

		$('#fake_pass').show();

		$('#fake_pass').focus(function(){
			$(this).hide(); //  hide the fake password input text
			$('#real_pass').show().focus(); // and show the real password input password
		});

		$('#real_pass').blur(function(){
			if($(this).val() == ""){ // if the value is empty, 
				$(this).hide(); // hide the real password field
				$('#fake_pass').show(); // show the fake password
			}
		});
	}
	else {
		$('#real_pass').attr("onFocus", "if(this.value==defaultValue){this.value=''; setAttribute('type', 'password');} else if(this.value==''){this.value=defaultValue; setAttribute('type', 'text');} ");
		$('#real_pass').attr("onblur", "if(this.value==''){this.value=defaultValue; setAttribute('type', 'text');}"); 
		$('#real_pass').attr("type", "text"); 
		$('#real_pass').attr("value", i18n.msg('index.password')); 
		$('#real_pass').prop("value", i18n.msg('index.password')); 
		
	}
	
	$('.index_acepto span').html(i18n.msg('index.readAndAccept'));
	$('#conditions').html(i18n.msg('index.termsAndConditions'));
	$('#recoveryPassButton .index_boton_recuperar .index_texto_recuperar-pass').html(i18n.msg('recover.password'));
	$('#recoveryUserButton .index_texto_sin-pass').html(i18n.msg('unknown.my.user'));

	self._initHandlers();
	
	// Comprobar si existe version mobile
	checkMobile();
};

Inet.prototype._initHandlers = function() {
	
	var self = this;
	
	// Campo login
	$('#userLogin').val(i18n.msg('index.user'));
	$(document).off('focus', '#userLogin').on('focus', '#userLogin', function(event) {
		if(this.value == i18n.msg('index.user')) {
			this.value = ''; 
		} 
	});
	
	// Input Aceptar
	$('#indexBtnAccept').val(i18n.msg('btn.accept'));
	$(document).off('blur', '#userLogin').on('blur', '#userLogin', function(event){
		if (this.value == '') {
			this.value = i18n.msg('index.user');
		}
	});
	
	// Eventos sobre botones recuperar pass/user
	$(document).off('click', '#recoveryPassButton').on('click', '#recoveryPassButton', function(event){
		self._renderRecoveryPasswordView();
	});
	
	$(document).off('click', '#recoveryUserButton').on('click', '#recoveryUserButton', function(event){
		self._renderRecoveryUserView();
	});
	
	$(document).off('click', '.supportMailLink').on('click', '.supportMailLink', function(event){
		event.preventDefault();
		self._renderSupportView();
	});
	
	// Evento sobre enlace a terminos y condiciones
	$(document).off('click', '#conditions').on('click', '#conditions', function(event){
		self._renderConditionsView();
	});
	
	$(document).off('click', '.boton_cancelar').on('click', '.boton_cancelar', function(event) {
		$('#recoveryView').modal('hide');
	});
	
	$(document).off('show.bs.modal').on('show.bs.modal', '.modal', function(event) {
		  $(this).appendTo($('body'));
		}).off('shown.bs.modal').on('shown.bs.modal', '.modal.in', function(event) {
			self.renderScrollbar();
			if ($(window).height() >= 590){
				  $(window).resize(self._adjustModalMaxHeightAndPosition).trigger("resize");
				}
			self.setModalsAndBackdropsOrder();
			self._setFirstFieldFormFocus();
		}).off('hidden.bs.modal').on('hidden.bs.modal', '.modal', function(event) {
			self.setModalsAndBackdropsOrder();
			$('#' + event.target.id + ' .modal-content').html('');
			$('#' + event.target.id + ' .modal-content .modal-body').css({'max-height' : ''});
			$('#' + event.target.id + ' .modal-content').css({'max-height' : ''});
			captcha.hide();
			$('#' + event.target.id).hide();
		});
};

/**
 * Recupera el siguiente paso y renderiza el html.
 */
Inet.prototype.loadStep = function(action, params, module) {
	
	var self = this;
	captcha.hide();
	var url = self.generateUrl(action, {}, module);
	var template = self.renderTemplate(url, params);
	if (template){
		$('#recoveryView .modal-content').html(template);
		$('#recoveryView').modal({'backdrop' : 'static'});
		
		this.renderScrollbar();
		this.centerModal();
	}
	this._setFirstFieldFormFocus();
//	$('.modal-dialog').loader('hide');
};

Inet.prototype._renderRecoveryPasswordViewFromRecoveryUser = function(login) {
	var self = this;
	
	var options = {
			
	}
	
	new RecoveryPasswordView(options);
	new SupportView(options);
}

Inet.prototype._renderRecoveryPasswordView = function() {
	var self = this;

	var options = {
			i18n: i18n,
			inet : inet,
			userServiceFacade : userServiceFacade,
			messageHandler : messageHandler,
		}
		
		new RecoveryPasswordView(options);
		new SupportView(options);
};

Inet.prototype._renderRecoveryUserView = function() {
	var self = this;

	var options = {
			i18n: i18n,
			inet : inet,
			userServiceFacade : userServiceFacade,
			messageHandler : messageHandler,
		}
		
		new RecoveryUserView(options);
		new SupportView(options);
};

Inet.prototype._renderConditionsView = function() {
	var self = this;
	
	var options = {
			i18n: i18n,
			inet : inet,
			userServiceFacade : userServiceFacade,
			messageHandler : messageHandler,
		}
		
		new ConditionsView(options);	
};

/**
 * Ordena los fondos grises por detrás de las modales para que nunca un fondo gris este delante de su modal.
 */
Inet.prototype.setModalsAndBackdropsOrder = function() {  
	 var modalZIndex = 1040;
	  $('.modal.in').each(function(index) {
	    var $modal = $(this);
	    modalZIndex++;
	    $modal.css('zIndex', modalZIndex);
	    $modal.next('.modal-backdrop.in').addClass('hidden').css('zIndex', modalZIndex - 1);
	});
	  $('.modal.in:visible:last').focus().next('.modal-backdrop.in').removeClass('hidden');
};

Inet.prototype._renderSupportView = function() {
	var self = this;
	
	var url = self.generateUrl('support', {});
	var template = self.renderTemplate(url, {});
	if (template){
		$("#recoveryView-Support .modal-content").html(template);
		$("#recoveryView-Support").modal({'backdrop': 'static'});
		this.centerModal();
	}
	self.getCountries(null, 'supportView');
	
	$('#supportCountrySelect').selectpicker({
		width: '300px',
		height: '35px',
		dropupAuto: false,
		size: 7
  });
};

/**
 * Obtiene la localizacion del usuario que accede a la web
 */
Inet.prototype.getUserLocation = function() {
	var self = this;
	userServiceFacade.getUserLocation(self._onSuccessGetUserLocation, self._onErrorGetUserLocation, self);
};

Inet.prototype._onSuccessGetUserLocation = function(data) {
	var self = this;
	self.countryCode = data.country_code;
	
	if(self.countryCode && self.countryCode.toUpperCase() != 'CN') {
		$(document.getElementsByTagName("head")[0]).append(self.grecaptchaImport);
	}
	captcha.onLoadCaptcha();
};

Inet.prototype._onErrorGetUserLocation = function(response, textStatus, errorThrown) {
	var self = this;
	self.countryCode = '';
	captcha.onLoadCaptcha();
};

/**
 * Actualiza el scrollbar para ajustarlo al contenido
 */
Inet.prototype.updateScrollbar = function() {
//	if($('.scrollbar').parent().data('tsb')) {
//		$('.scrollbar').parent().data('tsb').update();
//	}
	
};

/**
 * Renderiza el scrollbar
 */
Inet.prototype.renderScrollbar = function(divClass) {
    $(".bodyformscroll").mCustomScrollbar({
        theme : "dark",
        advanced : {
            autoScrollOnFocus : false,
            updateOnContentResize : true
        }
    });
};

/**
 * Centra la modal tanto vertical como horizontalmente
 */
Inet.prototype.centerModal = function() {
	this._adjustModalMaxHeightAndPosition();
	this.setModalsAndBackdropsOrder();
};

Inet.prototype._adjustModalMaxHeightAndPosition = function(){
	var self = this;
	$('.modal').each(function(index, value){
		if($(this).hasClass('in') === false){
			$(this).show();
	    }
		var contentHeight = '580px';
		$('.modal-dialog').each(function(element){
			if($(element).height && $(element).height > 0) {
				contentHeight = $(element).height() + 'px';
			}
		})

	    var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
	    var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;

	    $(this).find('.modal-content').css({
	    	'max-height': contentHeight

	    });

	    $(this).find('.modal-body').css({
	    	'max-height': contentHeight
	    });

	    $(this).find('.modal-dialog').addClass('modal-dialog-center').css({
	    	'margin-top': function () {
	    		return -($(this).outerHeight() / 2);
	    	},
	    	'margin-left': function () {
	    		return -($(this).outerWidth() / 2);
	    	}
	    });
	    if($(this).find('.modal-content').html() == false){
	    	$(this).hide();
	    }
	    inet.updateScrollbar();
	});
};

/**
 * Transforma un string en un objeto jquery
 */
Inet.prototype.parseStringToObject = function(str) {
	
	strCleaned = '';
	for (var i = 0, len = str.length; i < len; i++) {
		 if(str[i] != ';' && str[i] != ':' &&  str[i] != ',') {
			 strCleaned = strCleaned + str[i];
		 }
	}
	strArray = strCleaned.split(' ');
	var strObject = {};
	for (var i = 0, len = strArray.length; i < len; i++) {
		if(i%2 != 0) {
			strObject[strArray[i-1]] = strArray[i];
		} 
	}
	
	return strObject;
};

Inet.prototype._setFirstFieldFormFocus = function() {
	$('.firstFormField').focus();
}

//--- Singleton instance ---
var inet = new Inet();

inet.loadI18n();

$(document).ready(function() {		
		inet.initIndex();
});

var onLoadCatpcha = function() {
	captcha.onLoadGRecaptcha();
}

function disable_enable(){
	if (document.all || document.getElementById){
		if (document.frmLogin.btnSubmit.disabled==true)
			document.frmLogin.btnSubmit.disabled=false
		else
			document.frmLogin.btnSubmit.disabled=true
	}
}