function VQApp()
{
	this.utils = new Utils();
	this.toolbars = new Toolbars();
	this.messages = new Messages();
}

function Toolbars()
{
	this.shareLink = function(site)
	{
		var url = escape(document.URL);
		var href;
		switch(site)
		{
			case "digg":
				href = "http://digg.com/submit?phase=2&url=" + url;
				break;
			case "delicious":
				href = "http://del.icio.us/post?title=Ford Team Challenge&url=" + url;
				break;
			case "reddit":
				href = "http://reddit.com/submit?title=Ford Team Challenge&url=" + url;
				break;
			case "stumble":
				href = "http://www.stumbleupon.com/submit?title=Ford Team Challenge&url=" + url;
				break;
			case "facebook":
				href = "http://www.facebook.com/share.php?u=" + url;
				break;
			case "blogger":
				href = "http://www.blogger.com/blog_this.pyra?u=" + url;
				break;
			case "myspace":
				href = "http://www.myspace.com/Modules/PostTo/Pages/?t=Ford Team Challenge&u=" + url;
				break;
			default:
				throw new Error("invalid share target site: " + site);
		}

		window.open(href, "_blank");
		return false;
	}

	this.invite = function()
	{
		var flash = vqApp.utils.getElementById("flashMain");
		if(flash.showEmailForm)
		{
			flash.showEmailForm();
		}

		return false;
	}

	this.register = function()
	{
		window.location.href = "http://www1.uefa.com/user/registration.html?url=" + escape(document.URL);
		return false;
	}

	this.logout = function()
	{
		//TODO
		/*var date = new Date();
		date.setTime(date.getTime() - 24*60*60*1000);
		var val = "SCKUefa=; expires=" + date.toGMTString() + "; path:/";
		document.cookie = val;
		history.go(0);*/
		hdr.user.logout();
		return false;
	}
}

function Lists()
{
	this.showHide = function(link)
	{
		var img = vqApp.utils.getFirstChildElementByTagName(link, "img");

		if(link.parentNode == null || link.parentNode == null)
		{
			throw new Error("links frame not found")
		}

		var frame = link.parentNode.parentNode;

		var content;
		var frameChildren = frame.getElementsByTagName("div");
		var len = frameChildren.length;
		for(var i =  0; i < len; i++)
		{
			var child = frameChildren[i];
			if(child.className == "contentArea")
			{
				content = child;
				break;
			}
		}

		if(content == null)
		{
			throw new Error("links content area not found")
		}

		if(content.style.display == "none")
		{
			content.style.display = "block";
			img.src = "images/btn_contract.gif";
			img.alt = "contract";
		}
		else
		{
			content.style.display = "none";
			img.src = "images/btn_expand.gif";
			img.alt = "expand";
		}

		return false;
	}
}

function EditProfile()
{
	this.init = function()
	{
		this.flash = vqApp.utils.getElementById("inviteFlash");
		var table = vqApp.utils.getElementById("listInvites");
		this.listInvites = vqApp.utils.getFirstChildElementByTagName(table, "tbody");
		this.listInvitesHeader = vqApp.utils.getFirstChildElementByTagName(table, "tr");

		this.txtFirstName = vqApp.utils.getElementById("inviteFirstName");
		this.txtLastName = vqApp.utils.getElementById("inviteLastName");
		this.txtEmail = vqApp.utils.getElementById("inviteEmail");

		this.throbber = vqApp.utils.getElementById("throbber");
		this.addInvite = vqApp.utils.getElementById("addInvite");

		this.errorHeader = vqApp.utils.getElementById("messageErrorJs");
		this.errors = new Array();
		this.setBusy(false, true);		
	}

	this.setBusy = function(busy, invite)
	{
		if(invite)
		{
			this.throbber.style.display = (busy?"block":"none");
			this.addInvite.style.display = (busy?"none":"block");
		}

		this.busy = busy;
	}

	this.inviteUser = function()
	{
		if(this.busy)
		{
			return false;
		}

		vqApp.utils.clearErrors(this.errors, this.errorHeader);
		this.errors = new Array();

		var email = vqApp.utils.trim(this.txtEmail.value);
		if(vqApp.utils.isBlank(email))
		{
			this.errors.push({message:"error.invitee.email.required", element:this.txtEmail});
		}
		else if(!vqApp.utils.isEmail(email))
		{
			this.errors.push({message:"error.invitee.email.invalid", element:this.txtEmail});
		}

		var firstName = vqApp.utils.trim(this.txtFirstName.value);
		if(vqApp.utils.isBlank(firstName))
		{
			this.errors.push({message:"error.invitee.firstName.required", element:this.txtFirstName});
		}

		var lastName = vqApp.utils.trim(this.txtLastName.value);
		if(vqApp.utils.isBlank(lastName))
		{
			this.errors.push({message:"error.invitee.lastName.required", element:this.txtLastName});
		}

		if(this.errors.length == 0)
		{
			this.setBusy(true, true);
			this.flash.inviteUser(email, firstName, lastName);
		}
		else
		{
			vqApp.utils.renderErrors(this.errors, this.errorHeader);
		}

		return false;
	}

	this.inviteUserCallback = function(result, email, firstName, lastName)
	{
		var item = {id:result, email:email, firstName:firstName, lastName:lastName};
		this.renderRow(item);

		this.txtFirstName.value = "";
		this.txtLastName.value = "";
		this.txtEmail.value = "";

		this.setBusy(false, true);
	}

	this.inviteUserError = function(error, code)
	{
		var msg;
		var elem;
		switch(error)
		{
			case "InvalidArgumentUser":
				vqApp.utils.redirectLogin("editprofile.aspx");
				return;
			case "UserIsAlreadyPartOfTeam":
				msg = "error.invitee.isAlreadyInYourTeam";
				elem = this.txtEmail;
				break;
			case "UserIsAlreadyInvited":
				msg = "error.invitee.isAlreadyInvited";
				elem = this.txtEmail;
				break;
			case "InvalidArgumentEmail":
				msg = "error.invitee.email.invalid";
				elem = this.txtEmail;
				break;
			case "InvalidArgumentFirstName":
				msg = "error.invitee.firstName.required";
				elem = this.txtFirstName;
				break;
			case "InvalidArgumentLastName":
				msg = "error.invitee.lastName.required";
				elem = this.txtLastName;
				break;
			default:
				vqApp.utils.redirectError(code);
				return;
		}

		this.errors.push({message:msg, element:elem});
		vqApp.utils.renderErrors(this.errors, this.errorHeader);

		this.setBusy(false, true);
	}

	this.cancelInvite = function(inviteId)
	{
		if(this.busy)
		{
			return false;
		}

		var row = vqApp.utils.getElementById("invite_" + inviteId);
		var cols = row.getElementsByTagName("td");
		var msg;
		var accepted = cols[3].innerHTML == "Accepted";
		if(accepted)
		{
			msg = "confirm.invite.delete";
		}
		else
		{
			msg = "confirm.invite.cancel";
		}

		if(vqApp.utils.confirm(msg))
		{
			this.setBusy(true);
			this.flash.cancelInvite(inviteId);
		}

		return false;
	}

	this.cancelInviteCallback = function(inviteId)
	{
		var row = vqApp.utils.getElementById("invite_" + inviteId);
		this.listInvites.removeChild(row);
		var rows = this.listInvites.getElementsByTagName("tr");
		if(rows.length == 1)
		{
			this.listInvitesHeader.style.display = "none";
		}

		this.setBusy(false);
	}

	this.cancelInviteError = function(inviteId, error, code)
	{
		switch(error)
		{
			case "InvalidArgumentUser":
				vqApp.utils.redirectLogin("editprofile.aspx");
				return;
			case "InviteIsAlreadyCancelled":
				this.cancelInviteCallback(inviteId);
				break;
			default:
				vqApp.utils.redirectError(code);
				break;
		}
	}

	this.renderRow = function(item)
	{
		var row = document.createElement("tr");
		row.id = "invite_" + item.id;
		this.listInvites.appendChild(row);
		this.renderColumn(row, item.firstName);
		this.renderColumn(row, item.lastName);
		this.renderColumn(row, item.email);
		this.renderColumn(row, "Pending");

		var col = document.createElement("td");
		row.appendChild(col);
		var link = document.createElement("a");
		col.appendChild(link);
		link.href = "#";
		link.onclick = function(){return vqApp.editProfile.cancelInvite(item.id)};
		var text = document.createTextNode("Remove");
		link.appendChild(text);

		this.listInvitesHeader.style.display = "";
	}

	this.renderColumn = function(row, value)
	{
		var col = document.createElement("td");
		row.appendChild(col);
		var text = document.createTextNode(value);
		col.appendChild(text);
		return col;
	}

	this.init();
}

function Login()
{
	this.init = function()
	{
		this.txtEmail = vqApp.utils.getElementById("email");
		this.txtPassword = vqApp.utils.getElementById("password");
		this.form = vqApp.utils.getElementById("login");

		this.txtEmail.focus();

		this.errorHeader = vqApp.utils.getElementById("messageErrorJs");
		this.errors = new Array();
	}

	this.validate = function(submit)
	{
		var email = vqApp.utils.trim(this.txtEmail.value);

		vqApp.utils.clearErrors(this.errors, this.errorHeader);
		this.errors = new Array();

		if(vqApp.utils.isBlank(email))
		{
			this.errors.push({message:"error.email.required", element:this.txtEmail});
		}
		else if(!vqApp.utils.isEmail(email))
		{
			this.errors.push({message:"error.email.invalid", element:this.txtEmail});
		}

		var password = vqApp.utils.trim(this.txtPassword.value);
		if(vqApp.utils.isBlank(password))
		{
			this.errors.push({message:"error.password.required", element:this.txtPassword});
		}

		if(this.errors.length == 0)
		{
			if(submit == true)
			{
				this.form.submit();	
			}
			else
			{
				return true;
			}		
		}
		else
		{
			vqApp.utils.renderErrors(this.errors, this.errorHeader);
		}

		return false;
	}

	this.init();
}

function Upload()
{
	this.init = function()
	{
		this.flash = vqApp.utils.getElementById("uploadFlash");

		this.txtTitle = vqApp.utils.getElementById("title");
		this.txtPlayers = vqApp.utils.getElementById("players");
		this.txtDescription = vqApp.utils.getElementById("description");
		this.txtVideo = vqApp.utils.getElementById("video");
		this.txtVideoErr = vqApp.utils.getElementById("upload");

		this.divUplodbar = vqApp.utils.getElementById("uploadbar");
		this.divUplodbar.style.display = "none";
		this.divUplodbarFill = vqApp.utils.getElementById("uploadbarFill");

		this.uploadConfirmation = vqApp.utils.getElementById("uploadConfirmation");
		this.uploadMain = vqApp.utils.getElementById("uploadMain");
		
		this.errorHeader = vqApp.utils.getElementById("messageErrorJs");
		this.errors = new Array();
		
		this.txtTitle.focus();
		this.uploading = false;
	}

	this.setVideo = function(value, size)
	{
		if(value == "null")
		{
			value = "";
		}

		this.videoSize = size;
		this.txtVideo.value = value;
	}

	this.setProgress = function(value)
	{
		this.divUplodbarFill.style.width = value + "%";
	}

	this.upload = function()
	{
		if(this.uploading)
		{
			return false;
		}

		vqApp.utils.clearErrors(this.errors, this.errorHeader);
		this.errors = new Array();

		var title = vqApp.utils.trim(this.txtTitle.value);
		if(vqApp.utils.isBlank(title))
		{
			this.errors.push({message:"error.title.required", element:this.txtTitle});
		}

		var players = vqApp.utils.trim(this.txtPlayers.value);
		if(!vqApp.utils.isInteger(players) || (players = parseInt(players, 10)) < 3)
		{
			this.errors.push({message:"error.players.invalid", element:this.txtPlayers});
		}

		var description = vqApp.utils.trim(this.txtDescription.value);
		var video = vqApp.utils.trim(this.txtVideo.value);
		if(vqApp.utils.isBlank(video))
		{
			this.errors.push({message:"error.video.required", element:this.txtVideoErr});
		}

		if(this.videoSize > 104857600)
		{
			this.errors.push({message:"error.video.size", element:this.txtVideoErr});
		}

		if(this.errors.length == 0)
		{
			this.uploading = true;
			this.divUplodbar.style.display = "block";
			this.flash.upload(title, players, description);
		}
		else
		{
			vqApp.utils.renderErrors(this.errors, this.errorHeader);
		}

		return false;
	}

	this.uploadCallback = function()
	{
		this.uploading = false;
		this.txtTitle.value = "";
		this.txtDescription.value = "";
		this.txtPlayers.value = "";
		this.txtVideo.value = "";
		this.divUplodbar.style.display = "none";
		
		this.uploadMain.style.display = "none";
		this.uploadConfirmation.style.display = "block";
	}

	this.showUpload = function()
	{
		this.uploadMain.style.display = "block";
		this.uploadConfirmation.style.display = "none";	
		return false;
	}
	
	this.uploadError = function(error, code)
	{
		var msg;
		var elem;

		switch(error)
		{
			case "InvalidArgumentUser":
				vqApp.utils.redirectLogin("upload.aspx");
				return;
			case "InvalidFile":
				msg = "error.video.required";
				elem = this.txtVideoErr;
				break;
			case "InvalidFileSize":
				msg = "error.video.size";
				elem = this.txtVideoErr;
				break;
			case "InvalidArgumentTitle":
				msg = "error.title.required";
				elem = this.txtTitle;
				break;
			case "InvalidArgumentPlayers":
				msg = "error.players.invalid";
				elem = this.txtPlayers;
				break;
			default:
				vqApp.utils.redirectError(code);
				return;
		}

		this.txtVideo.value = "";
		this.errors.push({message:msg, element:elem});
		vqApp.utils.renderErrors(this.errors, this.errorHeader);
		this.uploading = false;
		this.divUplodbar.style.display = "none";
	}

	this.init();
}


function History()
{
	this.init = function()
	{
		this.hash = "";

		if(!!(window.attachEvent && !window.opera))
		{
			this.title = document.title;
			var version = navigator.userAgent.match(/MSIE (\d\.\d)/)[1];
			if(version >= 5.5 && version < 8)
			{				
				var frameName = "HistoryFrame";
				var historyFrame = document.createElement("iframe");
				historyFrame.setAttribute("name", frameName);
				historyFrame.setAttribute("id", frameName);
				//historyFrame.setAttribute("src", 'javascript:;');
				historyFrame.style.position = "absolute";
				historyFrame.style.top = "-900px";
				document.body.insertBefore(historyFrame, document.body.firstChild);
				this.setHash = this.setHashIE;
				return;
			}
		}

		this.setHash = this.setHashStandard;
	}

	this.setHashIE = function(hash)
	{
		if(this.hash == hash)
		{
			return;
		}
		
		var frameName = "HistoryFrame";
		try
		{	
			var doc = frames[frameName].document;
			doc.open("text/html");
			doc.write("<html><head></head><body onload=\"parent.vqApp.history.updateHash('" + hash + "');\"></body></html>");
			doc.close();
		}
		catch(error)
		{
//			alert(error.description);
		}
			
	}

	this.setHashStandard = function(hash)
	{
		if(hash == document.location.hash)
		{
			return;
		}
		document.location.hash = hash;
	}

	this.updateHash = function(hash)
	{
		this.hash = hash;
		if(document.location.hash != hash)
		{
			document.location.hash = hash;
		}
		document.title = this.title;
	}

	this.init();
}

function Messages()
{
	this.messages = new Object();

	this.getMessage = function(key)
	{
		var message = this.messages[key];

		if(message == null)
		{
			return key;
		}

		return message;
	}
}

function Utils()
{
	this.getElementById = function(id)
	{
		var elem = document.getElementById(id);
		if(elem == null)
		{
			throw new Error("element not found in document:" + id)
		}
		return elem;
	}

	this.getFirstChildElementByTagName = function(parent, name)
	{
		var elems = parent.getElementsByTagName(name);
		if(elems.length == 0)
		{
			throw new Error("element not found in parent. parent:" + parent.id + ". tag name: " + name)
		}
		return elems[0];
	}

	this.trim = function(value)
	{
		if(value == null)
		{
			return "";
		}

		return value.replace(/^\s+|\s+$/g,"");
	}

	this.isBlank = function(value)
	{
		return (value == "");
	}

	this.isEmail = function(value)
	{
		var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return pattern.test(value);
	}

	this.isInteger = function(value)
	{
		var pattern = /(^-?\d\d*$)/;
		return pattern.test(value);
	}

	this.clearErrors = function(errors, header)
	{
		if(header != null)
		{
			header.style.display = "none";
		}

		var len = errors.length;
		for(var i = 0; i < len; i++)
		{
			var error = errors[i];

			var errorElement = error.element.nextSibling;
			if(errorElement != null && errorElement.className == "errorInline")
			{
				errorElement.parentNode.removeChild(errorElement);
			}
		}
	}

	this.renderErrors = function(errors, header)
	{
		if(header != null)
		{
			header.style.display = "block";
		}

		var len = errors.length;
		for(var i = 0; i < len; i++)
		{
			var error = errors[i];

			var errElement = document.createElement("span");
			errElement.className = "errorInline";
			this.insertAfter(errElement, error.element);

			var message = vqApp.messages.getMessage(error.message);
			errElement.appendChild(document.createTextNode(message));
		}
	}

	this.insertAfter = function(element, refElement)
	{
		var after = refElement.nextSibling;
		if(after != null)
		{
			after.parentNode.insertBefore(element, after);
		}
		else
		{
			refElement.parentNode.appendChild(element);
		}
	}

	this.redirectError = function(code)
	{
		window.location = "error.aspx?error=" + code;
	}

	this.redirectLogin = function(url)
	{
		window.location = "login.aspx?url=" + escape(url);
	}

	this.confirm = function(key)
	{
		return confirm(vqApp.messages.getMessage(key));
	}
}

var vqApp = new VQApp();