/* Cactuslab : integration with back-end */

var personDetail = null;
var validateEmailAddress;
var SWF;
var integrationContextPath = "../csol/";

window.addEvent('domready', function() {
	checkLoggedIn();
});

function integrationFlashProxy(func) {
	var proxy;
	if (navigator.appName.indexOf("Microsoft") != -1) {
        proxy = window["xdproxy"];
    } else {
        proxy = document["xdproxy"];
    }
    
    if (proxy) {
    	func(proxy);
    } else {
    	setTimeout(function() {
    		integrationFlashProxy(func);
    	}, 500);
    }
}

Json.RemoteHalf = XHR.extend({

	initialize: function(url, options){
		var path = url;
			var host = document.location.host;
		var protocol = document.location.protocol;
		if( protocol != 'https:' ) {
			if( host == 'localhost:8080' || host == 'localhost.:8080' ) {
				host = 'localhost.:8443';
			} else if( host == 'karl.office.cactuslab.com:8080' ) {
				host = 'karl.office.cactuslab.com:8443';
			} else if( host == 'gary.office.cactuslab.com:8080' ) {
				host = 'gary.office.cactuslab.com:8443';
			} else if( host == 'dev.cactuslab.com:8080' ) {
				host = 'dev.cactuslab.com:8443';
			} else if( host == 'www.coca-cola.com.au' ) {
				host = 'secure.coca-cola.com.au';
			} else if( host == 'coca-cola.com.au' ) {
				host = 'secure.coca-cola.com.au';
			}
		}
					
		var request = document.location.pathname;
		if( path.match(/^\.\./) ) {
		 	if( request.match(/^\/cokeau/) ) {
				request = "/cokeau/ssldocs" + request.substring(7);
			} else {
				request = "/ssldocs" + request;
			}
		} else {
		 	if( request.match(/^\/cokeau/) ) {
				request = "/cokeau/ssldocs";
			 	if( path.match(/^\/cokeau/) ) {
					path = path.substring(7);
				}
			} else {
				request = "/ssldocs";
			}
		}
		if( path.match(/^[^\/]/) && request.match(/[^\/]$/) ) {
			path = "/" + path;
		}
			
		path = 'https://' + host + request + path;

		this.url = path;
		this.addEvent('onSuccess', this.onComplete);
		this.parent(options);
		this.setHeader('Content-type', 'application/x-www-form-urlencoded');
	},

	send: function(obj){
		var f = "callback" + new Date().getTime() + "_" + Math.round(Math.random() * 10000);
		var me = this;
		window[f] = function(json) {
			if (json != null) {
				var data = eval('(' + json + ')');
				me.options.onComplete(data);
			} else {
				me.onError();
			}
		};
		
		if( !this.url.match(/loggedin/) ) {
			integrationFlashProxy(function(proxy) {
				proxy.ajax(me.url, obj, f);
			});
		} else {
			jq.ajax({ url:this.url, data:Object.toQueryString(obj), dataType: "jsonp", success: this.options.onComplete });
		}
	},

	onComplete: function(){
		this.fireEvent('onComplete', Json.evaluate(this.response.text));
	}

});

Json.RemoteForm = XHR.extend({

	initialize: function(url, options){
		var path = url;
		var host = document.location.host;
		var protocol = document.location.protocol;
		if( protocol != 'https:' ) {
			if( host == 'localhost:8080' || host == 'localhost.:8080' ) {
				host = 'localhost.:8443';
			} else if( host == 'karl.office.cactuslab.com:8080' ) {
				host = 'karl.office.cactuslab.com:8443';
			} else if( host == 'gary.office.cactuslab.com:8080' ) {
				host = 'gary.office.cactuslab.com:8443';
			} else if( host == 'dev.cactuslab.com:8080' ) {
				host = 'dev.cactuslab.com:8443';
			} else if( host == 'www.coca-cola.com.au' ) {
				host = 'secure.coca-cola.com.au';
			} else if( host == 'coca-cola.com.au' ) {
				host = 'secure.coca-cola.com.au';
			}
		}
			
		var request = document.location.pathname;
		if( path.match(/^\.\./) ) {
		 	if( request.match(/^\/cokeau/) ) {
				request = "/cokeau/ssldocs" + request.substring(7);
			} else {
				request = "/ssldocs" + request;
			}
		} else {
		 	if( request.match(/^\/cokeau/) ) {
				request = "/cokeau/ssldocs";
			 	if( path.match(/^\/cokeau/) ) {
					path = path.substring(7);
				}
			} else {
				request = "/ssldocs";
			}
		}
		if( path.match(/^[^\/]/) && request.match(/[^\/]$/) ) {
			path = "/" + path;
		}
		
		path = 'https://' + host + request + path;
	
		this.url = path;
		this.addEvent('onSuccess', this.onComplete);
		this.parent(options);
		this.setHeader('Content-type', 'application/x-www-form-urlencoded');
	},

	send: function(form){
		var data = $(form).toObject();
		
		var f = "callback" + new Date().getTime() + "_" + Math.round(Math.random() * 10000);
		var me = this;
		window[f] = function(json) {
			if (json != null) {
				var data = eval('(' + json + ')');
				me.options.onComplete(data);
			} else {
				me.onError();
			}
		};
		
		if( !this.url.match(/loggedin/) ) {
			integrationFlashProxy(function(proxy) {
				proxy.ajax(me.url, data, f);
			});
		} else {
			jq.ajax({ url:this.url, data:$(form).toQueryString(), dataType: "jsonp", success: this.options.onComplete });
		}
	},

	onComplete: function(){
		this.fireEvent('onComplete', Json.evaluate(this.response.text));
	}

});

function setLoggedIn(loggedIn, interactive) {
	if (loggedIn) {
    	CSOL.switchSlidePane('loggedInPanel');
    	if (SWF) {
    		SWF.allFlashCall('onLogin');
    	}
		CSOL.loggedIn = true;
		if (CSOL.handleLoggedIn) {
			CSOL.handleLoggedIn(true, interactive);
		}
    } else {
    	if (CSOL.loggedIn) {
			CSOL.switchSlidePane('loggedOutPanel');
			if (SWF) {
				SWF.allFlashCall('onLogout');
			}
    		CSOL.loggedIn = false;
			if (CSOL.handleLoggedIn) {
				CSOL.handleLoggedIn(false, interactive);
			}
		} else {
			if (CSOL.handleLoggedIn) {
				CSOL.handleLoggedIn(false, interactive);
			}
		}
    }
}

function checkLoggedIn() {
	new Json.RemoteHalf(integrationContextPath + "loggedin.do", {
		onComplete: handleLoggedinResult
	}).send();
}

function escapeEntities(str) {
	str = str.replace(/&/, "&amp;");
	str = str.replace(/</, "&lt;");
	str = str.replace(/>/, "&gt;");
	return str;
}

function checkFooty(result) {
	if (result.optinFooty && !isMemberOf("footy07", result.memberships)) {
		CSOL.showPage('regoFooty');
		return true;
	} else {
		return false;
	}
}

function updateLogin(result, interactive) {
	if (result.screenName) {
		$E('.loginNameLabel', Extensions.getPrebuilt('loggedInPanel')).setHTML(escapeEntities(result.screenName));
	}
	
	setLoggedIn(result.loggedIn, interactive);
	if (result.loggedIn) {
		personDetail = result;
	}
}

function handleMessages(result) {
	if (result.messages && result.messages.length > 0) {
		var msg = "";
		for (var i = 0; i < result.messages.length; i++) {
			msg += result.messages[i] + "\n";
		}
		if (CSOL.showAlert) {
			msg = msg.replace(/\n/g, "<br />");
			CSOL.showAlert(msg);
		} else {
			alert(msg);
		}
	}
}

function handleLoggedinResult(result) {
	handleLoginResultCommon(result, false);
}

function handleLoginResult(result) {
	handleLoginResultCommon(result, true);
}

function handleLoginResultCommon(result, interactive) {
	updateLogin(result, interactive);
	handleMessages(result);
	
	if (result.loggedIn) {
		checkFooty(result);
	} else if (result.notLocal) {
		personDetail = result;
		showWelcomeEditProfile();
	} else if (result.validationRequired) {
		showValidateRegistration(result.emailAddress);
	}
}

function handleRegisterResult(result) {
	if (result.registered) {
		updateLogin(result, true);
		if (result.validationRequired) {
			showValidateRegistration(result.emailAddress);
		} else {
			if (!checkFooty(result)) {
				CSOL.showPage('regoComplete');
			}
		}
	}
	
	handleMessages(result);
}

function handleEditProfileResult(result) {
	if (result.edited) {
		updateLogin(result, true);
		if (result.validationRequired) {
			CSOL.showPage('regoValidate');
		} else {
			if (!checkFooty(result)) {
				CSOL.hideWindow('registration');
			}
		}
	}
	
	handleMessages(result);
}

function handleRegisterFootyResult(result) {
	if (result.registered) {
		CSOL.showPage('regoComplete');
	}
	handleMessages(result);
}

function handleValidateRegistrationResult(result) {
	if (result.validated) {
		updateLogin(result, true);
		if (!checkFooty(result)) {
			CSOL.showPage('regoComplete');
		}
	}
	handleMessages(result);
}

function isMemberOf(website, memberships) {
	for (var i = 0; i < memberships.length; i++) {
		if (memberships[i] == website) {
			return true;
		}
	}
	return false;
} 

function login(email, password, panel) {
	if (email != "" && email != "Enter your email" && password != null && password != "Enter your password") {
		new Json.RemoteHalf(integrationContextPath + "login.do", {
			onComplete: handleLoginResult
		}).send({'emailAddress': email, 'password': password});
	} else {
		if (panel) {
			alert("Please fill in your email and password.");
		}
		else {
			alert("Please enter your email address and password at the top of the page.");
		}
	}
}

function editProfile(form) {
	new Json.RemoteForm(integrationContextPath + "editprofile.do", {
		onComplete: handleEditProfileResult
	}).send(form);
}

function register(form) {
	new Json.RemoteForm(integrationContextPath + "register.do", {
		onComplete: handleRegisterResult
	}).send(form);
}

function registerFooty(form) {
	new Json.RemoteForm(integrationContextPath + "registerfooty.do", {
		onComplete: handleRegisterFootyResult
	}).send(form);
}

function showEditProfile() {
	CSOL.showPage('editProfile');
}

function showWelcomeEditProfile() {
	CSOL.showPage('welcomeEditProfile');
}

function showValidateRegistration(email) {
	validateEmailAddress = email;
	CSOL.showPage('regoValidate');
}

function validateRegistration(code) {
	new Json.RemoteHalf(integrationContextPath + "validate.do", {
		onComplete: handleValidateRegistrationResult
	}).send({emailAddress: validateEmailAddress, validationCode: code});
}

function logout() {
	new Json.RemoteHalf(integrationContextPath + "logout.do", {
		onComplete: function(result){
			setLoggedIn(!result.loggedOut, true);
		}
	}).send();
}

function tellAFriend(form) {
	new Json.RemoteForm(integrationContextPath + "tellafriend.do", {
		onComplete: function(result) {
			if (result.success) {
				CSOL.showPage('tellAFriendThanks');
			} else {
				handleMessages(result);
			}
		}
	}).send(form);
}

function resetPassword(form) {
	new Json.RemoteForm(integrationContextPath + "resetpassword.do", {
		onComplete: function(result) {
			if (result.passwordReset) {
				CSOL.showPage('resetPasswordThanks');
			} else {
				handleMessages(result);
			}
		}
	}).send(form);
}

function contactUs(form) {
	new Json.RemoteForm(integrationContextPath + "contactus.do", {
		onComplete: function(result) {
			if (result.success) {
				CSOL.showPage('contactUsThanks');
			} else {
				handleMessages(result);
			}
		}
	}).send(form);
}

function sendPassword(email) {
	if (email != "" && email != "Enter your email") {
		new Json.RemoteHalf(integrationContextPath + "forgottenpassword.do", {
			onComplete: function(result) {
				if (result.passwordSent) {
					CSOL.showPage('passwordReminder');
				} else {
					handleMessages(result);				
				}					
			}
		}).send({'emailAddress': email});
	} else {
		alert("Please fill in your email");	
	}
}

function populateForm(form, data) {
	for (var i = 0; i < form.elements.length; i++) {
		var name = form.elements[i].name;
		if (data[name] != undefined) {
			if (form.elements[i].type == "radio") {
				if (form.elements[i].value == data[name]) {
					form.elements[i].checked = true;			
				}
			} else if (form.elements[i].type == "checkbox") {
				form.elements[i].checked = data[name];			
			} else {
				form.elements[i].value = data[name];
			}
		}
	}
}

function populatePersonForm(form) {
	populateForm(form, personDetail);
}
