
/**
 * 
 * @param title							Title which will be displayed on the login/reg box
 * @param module						Module to which the action belongs to (public or agent or cpb or pm or cf_apt)
 * @param returnUrl						Url to which user should be redirected after successful login/registration
 * @param formId						Form which needs to be submitted after successful login/registration
 * @param callbackFunctionsWithParams	Javascript callback functions which need to be called after successful login/registration
 * @param loaderId						Id of the loader div (Loader will be displayed while the request is in processing)
 * @param reloadPageAfterCallbacks		Is current page should be reloaded after calling the call back functions
 * @param containerDivId				Container in which login/register forms need to be displayed
 * @returns {Authorize}
 */
function Authorize(title, module, returnUrl, formId, callbackFunctionsWithParams, loaderId, reloadPageAfterCallbacks, containerDivId){
	
	NEW_LINE = "\n";
	
	BULLET = "* ";
	
	LOGIN_FORM_CONTAINER_ID = 'login_form_container';
	
	REGISTER_FORM_CONTAINER_ID = 'register_form_container';
	
	REGISTERED_USER_FORM_CONTAINER_ID = 'registered_user_form_container';
	
	if(containerDivId)
		AUTHORIZE_FORMS_CONTAINER_DIV_ID = containerDivId;
	 else
		AUTHORIZE_FORMS_CONTAINER_DIV_ID = 'authorize_forms_container';
	title='';
	this.title = title;
	
	if(loaderId)
		this.loaderId = loaderId;
	else
		this.loaderId = 'listing_loader';
	
	this.module = module;
	
	this.returnUrl = returnUrl;
	
	this.formId = formId;
	
	this.type = 1; /* 1: Login, 2: signup */
	
	this.callbackFunctionsWithParams = callbackFunctionsWithParams;
	
	if(reloadPageAfterCallbacks == 'no')
		this.reloadPageAfterCallbacks = false;
	else
		this.reloadPageAfterCallbacks = true;
	
	this.callBackFunctionsWithoutReload = (this.callbackFunctionsWithParams && !this.reloadPageAfterCallbacks);		
}
Authorize.prototype.setType = function(type) {
	if(type==1) {
		this.type = 1;
	} else {
		this.type = 2;
	}
}
/**
 * Shows authorize login and registration forms to the user. 
 */
Authorize.prototype.showAuthorizeForm = function(isNotUserRequest, hideShadow, width, top){
	var loaderId = this.loaderId;
	var me = this;
	
	if($(loaderId))
	$(loaderId).show();
	
	var params = "ml=" + this.module + "&tl=" + this.title;
	
	if (this.returnUrl){ 
		var url_params = (this.returnUrl).toQueryParams();
		if (url_params.apt_id)  
			params += "&apt_id=" + url_params.apt_id;
	}
	
	if(isNotUserRequest)
		params += "&inur=true";
	
	if(hideShadow)
		params += "&hs=true";
	
	if(this.type==2) {
		params += "&signup=true";
	}
	new Ajax.Request(
		"/authorize/show-authorize-form",
		{
			method:'GET',
			parameters: params,
			onSuccess: function(transport){		
				
				$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).innerHTML = transport.responseText;
				evalScript($(AUTHORIZE_FORMS_CONTAINER_DIV_ID));
				if(AUTHORIZE_FORMS_CONTAINER_DIV_ID == 'authorize_forms_container') {
					
					$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).style.position = 'fixed';
					$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).style.zIndex = '9999';
				}
				
				if(width) {
					$('authorize_forms_content').style.width = width + "px";
				} else {
					$('authorize_forms_content').style.width = '500px';
				}
				
				var dimensions = me.getBrowserSize();
				var width = dimensions[0];
				var height = dimensions[1];
				
				var contentWidth = $(AUTHORIZE_FORMS_CONTAINER_DIV_ID).offsetWidth;	
		    	var contentHeight = $(AUTHORIZE_FORMS_CONTAINER_DIV_ID).offsetHeight;
		    	$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).style.left = Math.ceil(((width - contentWidth) / 2)-50) + 'px';
		    	var temp_top = (Math.ceil((height - contentHeight) / 2) - 20);
		    		if(temp_top < 0) {
		    			temp_top = 0;
		    		}
		    	$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).style.top = temp_top + 'px';
		    	
		    	$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).show();
				
				
			},
			onFailure: function(transport){
				alert('Could not connect to CommonFloor Server for this request');
			},
			onComplete: function(transport){
				if($(loaderId))
				$(loaderId).hide();
			}		
		}
	);
}

Authorize.prototype.toggleAuthorizeForms = function(){
	
	$(LOGIN_FORM_CONTAINER_ID).toggle();
	$(REGISTER_FORM_CONTAINER_ID).toggle();
	$(REGISTERED_USER_FORM_CONTAINER_ID).toggle();
}

Authorize.prototype.submitLoginForm = function(isRegistered){

	var me = this;
	var validated = false;
	var formId = '';
	var loaderId = this.loaderId;
	var callBackFunctionsWithoutReload = this.callBackFunctionsWithoutReload;
	validated = this.validateLoginDetails();
	formId = 'auth_login_form';
	if(validated) {
	  if($(loaderId))
		$(loaderId).show();
		var remember_me = $('remember_me').checked;
	
		new Ajax.Request("/authorize/login",
		{
			method:'POST',
			parameters: $(formId).serialize() + ((callBackFunctionsWithoutReload) ? "&rt=a" : "") +"&remember_me="+remember_me ,
			onSuccess: function(transport){		
				var text = transport.responseText;//alert(text);
				var returnValueParts = text.split("|");
			
				if(/0/.test(returnValueParts[0])) {
					$('login_password_div').innerHTML = returnValueParts[1];
					$('login_password_error').className='t-tipshow';	
					//alert(returnValueParts[1]);
				} else {
						
					if(/1/.test(returnValueParts[0])) {
						
//						if(callBackFunctionsWithoutReload && $('user_welcome_div')) {
//							
//							$('user_welcome_div').innerHTML = returnValueParts[1];
//						}
					if (returnValueParts[2])
					{
						me.returnUrl = returnValueParts[2]; 
					}
					$("auth_login_form").hide();
					me.handleSuccessfulAuthorization();
					}
				}
			},
			onFailure: function(transport){
				alert('Could not connect to CommonFloor Server for this request');
			},
			onComplete: function(transport){
				if($(loaderId))
				$(loaderId).hide();
			}		
		});
	}
}

Authorize.prototype.submitRegisterForm = function(formId){
    if(formId == null){
    	formId = 'auth_register_form';
    }
	var me = this;
	
	var loaderId = this.loaderId;
	var callBackFunctionsWithoutReload = this.callBackFunctionsWithoutReload;
	if(this.validateRegisterDetails(formId)) {
		
		if($(loaderId))
		$(loaderId).show();
		new Ajax.Request("/authorize/register",
		{
			method:'POST',
			parameters: $(formId).serialize() + ((callBackFunctionsWithoutReload) ? "&rt=a" : ""),
			onSuccess: function(transport){		
				var text = transport.responseText;//alert(text);
				var returnValueParts = text.split("|");
				if(/0/.test(returnValueParts[0])) {
					$('register_email_div').innerHTML = returnValueParts[1];
					$('register_id_error').className = 't-tipshow';
					//alert(returnValueParts[1]);
				} else {
					
					if(/1/.test(returnValueParts[0])) {
						
//						if(callBackFunctionsWithoutReload && $('user_welcome_div')) {
//							
//							$('user_welcome_div').innerHTML = returnValueParts[1];
//						}
						
						if (returnValueParts[2])
						{
							me.returnUrl = returnValueParts[2]; 
						}

						if($('auth_registered_user_form') !=undefined){

							$('username').innerHTML = $('auth_register_name').value;
							$('useremailid').innerHTML = $('auth_register_email_id').value;
							$("auth_register_form").hide();
							if($('auth_register_name').value=='')
								me.handleSuccessfulAuthorization();
							else 
								$("auth_registered_user_form").show();
						} else {
						
							me.handleSuccessfulAuthorization();
						}
					}
				}
			},
			onFailure: function(transport){
				alert('Could not connect to CommonFloor Server for this request');
			},
			onComplete: function(transport){
				if($(loaderId))
				$(loaderId).hide();
			}		
		});
	}
}

Authorize.prototype.handleSuccessfulAuthorization = function(){

	var returnUrl = this.returnUrl;
	var callBackFunctions = this.callbackFunctionsWithParams;
	var formId = this.formId;
	var reloadPageAfterCallbacks = this.reloadPageAfterCallbacks;
	var loaderId = this.loaderId;

	$(AUTHORIZE_FORMS_CONTAINER_DIV_ID).innerHTML = '';
	if($(loaderId))
	$(loaderId).show();
	
	if(returnUrl) {
		window.location = returnUrl;
	} else if(formId && $(formId)) {
		$(formId).submit();
	// In case of call back functions all parameters has to be strings
	} else if(callBackFunctions) {
		for(var functionName in callBackFunctions) {
			
		     var parameters = callBackFunctions[functionName];  
		     try {
		    	 var str;
		    	 evalStr = functionName + "(";
		    	 for(var i = 0; i < parameters.length; i++){ 
		    		 if(typeof(parameters[i]) == 'string') {
		    			 
		    			 evalStr += ("'" + parameters[i] + "'");
		    		 } else {
		    			 
		    			 evalStr += parameters[i];
		    		 }
		    		 if(i != (parameters.length - 1)){
		    			 
		    			 evalStr += ',';
		    		 }	
 		    	 }
		    	 evalStr += ');'; 
		    	 
			     eval(evalStr);
			     
		     } catch (err) {
				//alert(err.description);
			 }
	    }
		
		if($(loaderId))
			$(loaderId).hide();
		
		if(reloadPageAfterCallbacks)
			window.location.reload();
	}
}

Authorize.prototype.validateLoginDetails = function(){
	if(($('auth_login_form').platform_name.value != '') || ($('auth_login_form').platform_uid.value != ''))
	{
		return true;
	}
	
	var emailId = $('auth_login_id').value;
	emailId = emailId.replace(/^\s*/, "").replace(/\s*$/, "");
	var password = $('auth_login_password').value;
	var errorStr = "";
	
	if(!emailId) {
		
		errorStr += (BULLET + "Please enter your login id." + NEW_LINE);
	} else {

		var p_email = /^(([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)/;
		var matches = emailId.match(p_email);
		if(matches == null || matches[0] != emailId) {
			
			errorStr += (BULLET + "Please enter a valid login id." + NEW_LINE);
		}
	}

	if(!password) {
		
		errorStr += (BULLET + "Please enter password." + NEW_LINE);
	}

	if(errorStr){
		//alert(errorStr);
		return false;
	} else {
		return true;
	}
}

Authorize.prototype.validateRegisterDetails = function(formId){
	
	if(($(formId).platform_name.value != '') || ($(formId).platform_uid.value != ''))
	{
		return true;
	}	
		
	var emailId = $('auth_register_email_id').value;
	emailId = emailId.replace(/^\s*/, "").replace(/\s*$/, "");
	var password = $('auth_register_password').value;
	var confirmEmailId = $('auth_register_confirm_email_id').value;
	confirmEmailId = confirmEmailId.replace(/^\s*/, "").replace(/\s*$/, "");
	var errorStr = "";
	
	if(!emailId) {
		errorStr += (BULLET + "Please enter your email id." + NEW_LINE);
	} else if(emailId != confirmEmailId ) {

		errorStr += (BULLET + "Confirm email id not match" + NEW_LINE);
	} else {
		
		var p_email = /^(([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)/;
		var matches = emailId.match(p_email);
		if(matches == null || matches[0] != emailId) {
			
			errorStr += (BULLET + "Please enter a valid email id." + NEW_LINE);
		}
	}

	if(!password) {
		
		errorStr += (BULLET + "Please enter password." + NEW_LINE);
	}

	if(errorStr){
		//alert(errorStr);
		return false;
	} else {
		return true;
	}
}

Authorize.prototype.validateRegisteredUserDetails = function(){
	
	var password = $('auth_reg_user_password').value;
	var errorStr = '';
	if(!password) {
		
		errorStr += (BULLET + "Please enter your password." + NEW_LINE);
	}

	if(errorStr){
		//$('register_email_div').innerHTML=errorStr;
		//alert(errorStr);
		return false;
	} else {
		return true;
	}
}

Authorize.prototype.logout = function(){
	
	var loaderId = this.loaderId;
	if($(loaderId))
		$(loaderId).show();
	
	new Ajax.Request("/authorize/logout",
	{
		method:'POST',
		parameters: '',
		onSuccess: function(transport){		
			
			var hostName = transport.responseText;
			if(hostName) {
				window.location = hostName;
			} else {
				window.location = "http://www.commonfloor.com";
			}
		},
		onFailure: function(transport){
			
			alert('Could not connect to CommonFloor Server for this request');
		},
		onComplete: function(transport){
			
			if($(loaderId))
				$(loaderId).hide();
		}		
	});
}

Authorize.prototype.showPlatformOptions = function(){
	
	var markup = "<div><iframe src='/authorize/social-auth-options' width='300' height='300' frameborder=0></iframe></div>";
	messageObj.setHtmlContent(markup);
	messageObj.setCssClassMessageBox(false);
	
	messageObj.setSize('310','310');
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}

Authorize.prototype.getBrowserSize = function(){
	
	var bodyWidth = document.documentElement.clientWidth;
	var bodyHeight = document.documentElement.clientHeight;
	
	var bodyWidth, bodyHeight; 
	// all except Explorer
	if (self.innerHeight){  
	 
	   bodyWidth = self.innerWidth; 
	   bodyHeight = self.innerHeight; 
	   
	// Explorer 6 Strict Mode
	}  else if (document.documentElement && document.documentElement.clientHeight) {
	    		 
	   bodyWidth = document.documentElement.clientWidth; 
	   bodyHeight = document.documentElement.clientHeight; 
	// other Explorers
	} else if (document.body) { 	
		
	   bodyWidth = document.body.clientWidth; 
	   bodyHeight = document.body.clientHeight; 
	} 
	
	return [bodyWidth,bodyHeight];
}

function notUserHandler(redirectUrl){
	
	if(redirectUrl){
	
		authorize=new Authorize('', 'public', redirectUrl);
	} else {
	
		var functions={};
		functions['javascript:void']=new Array('0');
		authorize=new Authorize('', 'public', '', '', functions);
	}
	
	authorize.showAuthorizeForm(true);
}

function objectToString(o){
    
    var parse = function(_o){
    
        var a = [], t;
        
        for(var p in _o){
        
            if(_o.hasOwnProperty(p)){
            
                t = _o[p];
                
                if(t && typeof t == "object"){
                
                    a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
                    
                }
                else {
                    
                    if(typeof t == "string"){
                    
                        a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
                    }
                    else{
                        a[a.length] = [ p+ ": " + t.toString()];
                    }
                    
                }
            }
        }
        
        return a;
        
    }
    
    return "{" + parse(o).join(", ") + "}";
    
}

function publicUserSignUp(redirectUrl, title) {
	
	if(redirectUrl) {
		
		redirectUrl = "/" + redirectUrl;
	} else {
		
		redirectUrl = "/dashboard";
	}
	
	authorize = new Authorize(title, 'public', redirectUrl);
	authorize.setType(2);
	authorize.showAuthorizeForm(true);
}
function publicUserLogin(redirectUrl, title) {
	
	if(redirectUrl) {
		
		redirectUrl = "/" + redirectUrl;
	} else {
		
		redirectUrl = "/dashboard";
	}
	
	authorize = new Authorize(title, 'public', redirectUrl);
	authorize.showAuthorizeForm(true);
}


function evalScript(div) {
	   var x = div.getElementsByTagName("script");
	   var scriptBlocks = [];

	   for(var i=0; i<x.length; i++)
	   {
	       var oScript = document.createElement('script');
	       oScript.text = x[i].text;
	       scriptBlocks[i] = oScript;
	   }

	   for(var i=0; i <scriptBlocks.length; i++) {
	       div.appendChild(scriptBlocks[i]);
	   }
	}

