/**
 * @author alltouch
 */

function Auth(){
	this . options = new Object();
	this . options . url = piro . options . path + 'auth.php';
	
	this . logged = false;
	
	this . cache = null;
	var LoginBlock = null;
	var countErrors = 0;
	
	this . status = function(){
		
		piro . loading . hidePage('auth');
		
		$.ajax({
			'type' : 'POST',
			'async' : false,
			'url' : piro . auth . options . url,
			'data' : { 
						'data': $.toJSON({'type' : 'status'})
			 },
			'dataType' : 'json',
			'success' : piro . auth . set,
			'error' : function(obj){
				countErrors++;
				if(countErrors < 5){
					setTimeout(piro.auth.status,500);	
				} else {
					piro . alert . loadCustom('noConnectInternet');
				}
				
			}
		});	
		
	}
	
	this . set = function(obj){
		countErrors = 0;
		piro . auth . cache = obj;
		
		piro . auth . showUserBlock(obj);
		
		if(obj.userinfo && obj.userinfo.userType == 4 && obj.userinfo.siteType == 2){
			$('body').addClass('AGENT');
		} else {
			$('body').removeClass('AGENT');
		}
		
		piro . loading . showPage('auth');
		
	}
	
	this . set2 = function(obj){
		
		location.reload();
		return ;
		
		if (location.pathname.indexOf('main.html') > -1) {
		
			piro.chapters.init();
			piro . page . MakePage(location.hash.substr(1));
			
			if(obj.isLogged){
				//$.historyLoad('user');
			} else {
				piro.page.goFirst();	
			}
			
		} else {
			//location . href = 'main.html#user';
		}
		
		piro . auth . set(obj);
		
				
	}
	
	this . showUserBlock = function(obj){
		
		piro . auth . logged = obj . isLogged;
		if( !LoginBlock ){
			LoginBlock = $('#al_login_block');
		}
		
		if(obj.isLogged){
			LoginBlock . children('form') . hide();
			LoginBlock . children('.logged') . show();
			LoginBlock . children('.logged') . find('b') . 
				html( obj . userinfo . name + ' ' + obj . userinfo . surname );
		} else {
			LoginBlock . children('form') . show();
			LoginBlock . children('.logged') . hide();
		}
		
	}
	
	this . login = function(email, password){
		piro . loading . hidePage('auth');
		
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'login',
				'userLogin' : email,
				'userPassword' : password
			},
			piro . auth . set2,
			function(obj){
				piro . loading . showPage('auth');
				
				var obj = eval('[' + obj.responseText + ']')[0];
				
				if(obj.errors[0].text == 'not_confirmed'){
					piro . alert . loadCustom('userNotActivated');
				} else if(obj.errors[0].text == 'not_approved'){
					piro . alert . loadCustom('partnerNotActivated');
				} else {
					piro . alert . loadCustom('wrongPassword');	
				}				
				
			}
		);
		
	}
	
	this . logout = function(){
		piro . loading . hidePage('auth');
		
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'logout'
			},
			piro . auth . set2
		)
	}
	
	this . forgot = function(email){
		
		var _aError = $('#formForgot')[0].aError;
				
		piro . loading . hidePage('auth');
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'forgot',
				'userEmail' : email
			},
			function(answer){
				_aError . AfterSubmitSuccess();
				
				piro . loading . showPage('auth');
				piro . alert . loadCustom ('forgotSuccess');
			},
			function(answer){
				piro . loading . showPage('auth');
				piro . alert . loadCustom ('wrongForgotForm');
			}
		)
		
	}
	
	this . register = function(obj){
		
		var _aError = $('#formRegister')[0].aError;
		
		piro . loading . hidePage('auth');
		
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'register',
				'userData' : obj
			},
			function(answer){
				_aError . AfterSubmitSuccess();
				
				piro . loading . showPage('auth');
				
				if($('#f_userType').val() == 1){
					piro . alert . loadCustom('registerUser');	
				} else {
					piro . alert . loadCustom('registerPartner');
				}
				
				try {
					pageTracker._trackPageview('/'+ piro.page.info.path +'success/');
				}catch(e){}
				
				try {
					yaCounter.hit('/'+ piro.page.info.path +'success/');
				}catch(e){}
				
			},
			function(obj){
				_aError . showBackendErrors(obj);				
				piro . loading . showPage('auth');
			}
		)
		
	}
	
	this . remember = function(obj){
		
		var _aError = $('#formRemember')[0].aError;
		
		piro . loading . hidePage('auth');
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'remember',
				'userData' : obj
			},
			function(answer){
				_aError . AfterSubmitSuccess();
				
				piro . loading . showPage('auth');
				
				piro . page . goFirst();
				//location . reload();
			},
			function(obj){
				_aError . showBackendErrors(obj);				
				piro . loading . showPage('auth');
			}
		)
		
	}
	
	this . changePassword = function(){
		
		var _aError = $('#formChangePassword')[0].aError;
		_aError . clear();
		_aError . check(true);
		if(_aError . error){
			//piro . alert . loadCustom ('incorrectFormValues');
			return false;
		}
		
		var info = {
			'type' : 'changePassword'
		};
		var userData = $('#formChangePassword').serializeArray();
		var len = userData.length;
		for(var i=0; i<len ; i++){
			info[userData[i].name] = userData[i].value; 
		}
		
		piro . loading . hidePage('auth-change-pass');
		piro . ajax(
			piro . auth . options . url,
			info,
			function(answer){
				piro . loading . showPage('auth-change-pass');
				
				piro . alert . loadCustom('changePasswordSuccess');
			},
			function(obj){
				
				_aError . showBackendErrors(obj);
				
				piro . loading . showPage('auth-change-pass');
			}
		);
	}
	
	this . init = function(){
		
		this . status();
		
		$('#al_login_block form').submit(function(){
			
			piro . auth . login($('#f_login').val(), $('#f_password').val());
			
			return false;
		})
		$('#f_login_submit').click(function(){
			
			$(this).parent().submit();
			
			return false;
		})
		
		$('#f_logout_submit').click(function(){
			
			piro . auth . logout();
			
			return false;
		})
	}

	this . initViewSettings = function(display){
		if(piro . auth . logged && piro . auth . cache . userinfo . userType == 2){
			if (display)
			{
				$('.header #settings select[name="productViewType"]').val(piro . auth . cache . userinfo . productViewType);
				$('.header #settings select[name="pricesType"]').val(piro . auth . cache . userinfo . pricesType);
				$('.header #settings').show();
			}
			else
				$('.header #settings').hide();
		}
	}
	
	this . hideProfileFields = function(){
		if(piro . auth . logged && piro . auth . cache . userinfo . userType == 1){
			$('#body form').addClass('hidden1');			
		}
		if(piro . auth . cache . userinfo . userType == 4){
			$('#siteType').show();
		} else{
			$('#siteType').hide();
		}
	}
	
	this . setUserOptions = function(obj){
		
		var form = $('#body form');
		
		for(var i in obj){
			
			var temp = form.find('[name=' + i + ']');
			if(temp.length == 0){
				continue;
			}
			
			if(temp.is('input[type=checkbox]')){
				if(obj[i] > 0){
					temp.attr('checked','checked');
				}
			} else if(temp.is('input')){
				temp.val(obj[i]);
			} else if(temp.is('select')){
				temp.find('option[value=' + obj[i] + ']').attr('selected','selected');
				if(temp.is('#f_sendLetters')){
					temp.trigger('change');
				}				
			}
		}
		
		piro . loading . showPage('auth-user-options');
	}
	
	this . saveUserOptions = function(obj){
		
		var _aError = $('#formSaveOptions')[0].aError;
		piro . loading . hidePage('auth-save-user-options');
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'optionsSave',
				'options' : obj
			},
			function(answer){
				
				_aError . AfterSubmitSuccess();
				piro . auth . cache . userinfo = answer . options;
				if(answer . options.userType == 4 && answer . options.siteType == 2){
					$('body').addClass('AGENT');
				} else {
					$('body').removeClass('AGENT');
				}
				piro . cash . load();
				
				setTimeout(function(){
					piro . loading . showPage('auth-save-user-options');
					
					piro . alert . loadCustom('saveOptionsSuccess');
				},400)
				
				
				//location . reload();
			},
			function(obj){
				_aError . showBackendErrors(obj);				
				piro . loading . showPage('auth-save-user-options');
			}
		)
		
	}

	this . saveViewSettings = function(obj){
		piro . ajax(
			piro . auth . options . url,
			{
				'type' : 'settingsSave',
				'options' : obj
			},
			function(answer){
				piro . auth . cache . userinfo . productViewType = answer . options . productViewType;
				piro . auth . cache . userinfo . pricesType = answer . options . pricesType;
				
				piro . cash . load();

				var p = piro . page . params;
				var url = p.search ? 'search&query=' + p . query : 'pageid=' + p . pageid;
				
				if (p.countItems) url += '&countItems=' + p.countItems;
				if (p.pageNumber) url += '&pageNumber=' + p.pageNumber;
				
				$.historyLoad(url);
			}
		)
	}
	
	this . mode = function(){
		var result = {
			'type' : 0,
			'mode' : 0
		};
		
		if(piro . auth . logged){
			result . type = parseInt(piro . auth . cache . userinfo . userType);
			if(result . type > 1){
				result . mode = parseInt(piro . auth . cache . userinfo . pricesType);
			}
		}
		
		return result;
	}
}

piro . auth = new Auth();

