﻿var PhotoCount = 1;

function CreateFileControl(container, control)
{
	function SetUniqueName(elm)
	{
		elm.id = elm.id + PhotoCount.toString();
		elm.name = elm.name + PhotoCount.toString();
	}

	function ProcessElement(elm)
	{
		if (elm)
		{
			if (elm.value)
				elm.value = "";
			if (elm.text)
				elm.text = "";
			SetUniqueName(elm);
		}
	}

	if ((container != null) && (control != null) && (PhotoCount < MaxPhotoCount))
	{
		clone = control.cloneNode(true);
		if (clone != null)
		{
			PhotoCount++;
			ProcessElement(clone);
			ProcessElement(clone.children[1]);
			ProcessElement(clone.children[4]);
			ProcessElement(clone.children[7]);
			
			container.insertBefore(clone);
			ResizeWindow();
		}          
	}
	else
		alert("Nelze vložit více fotografií najednou.");
}

function ShowRegistration()
{
	// Show
	var container = document.getElementById("Registration");
	if (container)
		container.style.display = "block";
	var button = document.getElementById("Button");
	if (button)
		button.style.display = "block";				
		
	// Hide
	var link = document.getElementById("Link");
	if (link)
		link.style.display = "none";
	ResizeWindow();
}

function HideRegistration()
{
	// Hide
	var container = document.getElementById("Registration");
	if (container)
		container.style.display = "none";
	var button = document.getElementById("Button");
	if (button)
		button.style.display = "none";
		
	// Show
	var link = document.getElementById("Link");
	if (link)
		link.style.display = "block";
	ResizeWindow();
}

function SetImageSource(elementId, value)
{
	var elm = document.getElementById(elementId);
	if (elm != null)
	{
		if (elm.src)
			elm.src = value;
	}
}

function SetImageWidth(elementId, value)
{
	var elm = document.getElementById(elementId);
	if (elm != null)
	{
		elm.style.width = value;
	}
}	

// Functions
function GetBoolValue(node)
{
	if (node)
		return (node.text.toLowerCase() == "true")
	else
		return false;
}

function GetIntValue(node)
{
	if (node)
		return parseInt(node.text)
	else
		return 0;				
}

function GetStrValue(node)
{
	if (node)
		return node.text
	else
		return "";
}

function SetCookie(name, value)
{
	var date = new Date();
	date.setDate(date.getDate() + 30);
	document.cookie = name + "=" + escape(value) + "; expires=" + date.toGMTString() + ";";
}

function GetCookie(name)
{
  // cookies are separated by semicolons
  var cookie = document.cookie.split("; ");
  for (var i=0; i < cookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var crumb = cookie[i].split("=");
    if (name == crumb[0]) 
      return unescape(crumb[1]);
  }
  // a cookie with the requested name does not exist
  return "";
}

function DelCookie(name)
{
  document.cookie = name + "=" + escape(value) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

// Classes			
function CustomObject()
{
	// Fields
	this.Created     = "";
	this.Description = "";
	this.ID   	 = 0;
	this.Modified    = "";
	this.Title	 = "";
	// Methods
	this.BindControl = BindControl;
	this.Parse	 = Parse;
	
	function BindControl()
	{
		SetElementValue('CreatedSpan',	   this.Created);
		SetElementValue('DescriptionSpan', this.Description);
		SetElementValue('ModifiedSpan',	   this.Modified);
		SetElementValue('TitleSpan',	   this.Title);
	}
	
	function Parse(node)
	{
		if (node)
		{
			this.Created     = GetStrValue(node.selectSingleNode("Created"));
			this.Description = GetStrValue(node.selectSingleNode("Description"));
			this.ID			 = GetIntValue(node.selectSingleNode("ID"));
			this.Modified    = GetStrValue(node.selectSingleNode("Modified"));
			this.Title		 = GetStrValue(node.selectSingleNode("Title"));
		}
	}
}

function Gallery()
{}
Gallery.prototype = new CustomObject;

function GalleryPhoto()
{
	// Fields	
	this.Author			  = new GalleryUser();
	this.Gallery		  = new Gallery();
	this.ImageUrl		  = "";
	this.NextPhotoID	  = 0;
	this.PrevPhotoID	  = 0;
	this.ThumbUrl		  = "";
	this.VoteCount		  = 0;
	this.VoteValue		  = 0;
	this.VoteAverageValue = 0;

	// Methods
	this.BindControl = BindControl;
	this.Parse		 = Parse;

	function BindControl()
	{
		GalleryPhoto.prototype.BindControl();
		
		SetElementValue('UserNameSpan',		this.Author.UserName);
		SetElementValue('EmailSpan',		this.Author.Email);
		SetImageSource('Image',				this.ImageUrl);
		SetImageWidth('VoteAverageValue',	(this.VoteAverageValue.toString() + "%"));
		SetElementValue('VoteCount',		this.VoteCount);
		SetElementValue('VoteValue',		this.VoteValue);
	}
	
	function Parse(node)
	{
		if (node)
		{

			GalleryPhoto.prototype.Parse(node);
			
			this.Author.Parse(node.selectSingleNode("Author"));
			this.Gallery.Parse(node.selectSingleNode("Gallery"));
			
			this.ImageUrl		  = GetStrValue(node.selectSingleNode("ImageUrl"));
			this.NextPhotoID	  = GetIntValue(node.selectSingleNode("NextPhotoID"));
			this.PrevPhotoID	  = GetIntValue(node.selectSingleNode("PrevPhotoID"));
			this.ThumbUrl		  = GetStrValue(node.selectSingleNode("ThumbUrl"));
			this.VoteCount		  = GetIntValue(node.selectSingleNode("VoteCount"));
			this.VoteValue		  = GetIntValue(node.selectSingleNode("VoteValue"));
			this.VoteAverageValue = GetIntValue(node.selectSingleNode("VoteAverageValue"));
			this.ID   			  = GetIntValue(node.selectSingleNode("ID"));
		}
	}
} 
GalleryPhoto.prototype = new CustomObject;

function GalleryUser()
{
	// Fields
	this.Email     = "";
	this.FirstName = "";
	this.LastName  = "";
	this.UserName  = ""; 
	this.Password  = "";
	this.Description="";
	
	// Methods
	this.BindSource  = BindSource;
	this.BindControl = BindControl;
	this.Parse		 = Parse;
	this.Render		 = Render;

	function BindControl()
	{
		GalleryUser.prototype.BindControl();
		
		SetElementValue('Email',     this.Email);
		SetElementValue('FirstName', this.FirstName);
		SetElementValue('LastName',  this.LastName);
		SetElementValue('UserName',  this.Nick);
		SetElementValue('Password',  this.Password);
	}
	
	function BindSource()
	{	
		this.Email		= GetElementValue('Email');
		this.FirstName	= GetElementValue('FirstName');
		this.LastName	= GetElementValue('LastName');
		this.UserName   = GetElementValue('UserName');
		this.Password	= GetElementValue('Password');
		this.Description= GetElementValue('AuthorDescription');
	}
	
	function Parse(node)
	{
		if (node)
		{
			GalleryUser.prototype.Parse(node);
			
			this.Email	   = GetStrValue(node.selectSingleNode("Email"));
			this.FirstName = GetStrValue(node.selectSingleNode("FirstName"));
			this.LastName  = GetStrValue(node.selectSingleNode("LastName"));
			this.UserName  = GetStrValue(node.selectSingleNode("UserName"));
			this.Password  = GetStrValue(node.selectSingleNode("Password"));
		}
	}
	
	function Render(writer)
	{
		writer.WriteStartElement("User");
			writer.WriteElementString("Email",		this.Email);
			writer.WriteElementString("FirstName",	this.FirstName);
			writer.WriteElementString("LastName",	this.LastName);
			writer.WriteElementString("UserName",	this.UserName);
			writer.WriteElementString("Password",	this.Password);
			writer.WriteElementString("Description",this.Description);
		writer.WriteEndElement();
	}
}
GalleryUser.prototype = new CustomObject;

function GalleryManager()
{
	// Fields
	this.Url			= "XmlHandler.aspx";
	this.CurrentPhoto	= new GalleryPhoto();
	this.CurrentUser	= new GalleryUser();
	this.LastUserNameCheck  = true;
	// Methods
	this.CheckUserName	  = CheckUserName;
	this.AuthenticateUser = AuthenticateUser;
	this.LoadPhoto        = LoadPhoto;
	this.LoadPrevPhoto	  = LoadPrevPhoto;
	this.LoadNextPhoto	  = LoadNextPhoto;
	this.RegisterUser	  = RegisterUser;
	this.PhotoAddVote	  = PhotoAddVote;	
	
	function CheckUserName(userName, callback)
	{
		Send(this.Url + "?method=CheckUserName&userName=" + userName, '', callback);
	}
	
	function CheckUserName_Callback(response)
	{
		if (this.readyState != 4 || this.status != 200) return false;
		if (response)
		{
			try
			{
				var node = response.documentElement.selectSingleNode("Result");
				if (GetBoolValue(node))
				{
					alert('Uživatelské jméno již existuje!');
				}
				else
				{
					
				}								
			}
			catch(e)
			{
				alert('Chyba pri parsovani');
			}
		}
	}
	
	function AuthenticateUser(userName, password, callback)
	{
		Send(this.Url + "?method=AuthenticateUser&userName=" + userName + "&password=" + password, '', callback);
	}
	
	function AuthenticateUser_Callback(response)
	{
		if (this.readyState != 4 || this.status != 200) return false;
		if (response)
		{
			try
			{
				var node = response.documentElement.selectSingleNode("Result");
			}
			catch(e)
			{
				alert('Chyba pri parsovani');
			}
		}
	}
	
	function RegisterUser(user, callback)
	{
		var writer = new XmlWriter();
		writer.WriteStartElement("Request");
		user.Render(writer);					
		writer.WriteEndElement();
		Send(this.Url + "?method=RegisterUser", writer.Output, callback);
	}
	
	function LoadPhoto(photoID)
	{
		Send(this.Url + "?method=LoadPhoto&photoID=" + photoID, '', LoadPhoto_Callback);
	}
	
	function LoadPrevPhoto()
	{
		this.LoadPhoto(this.CurrentPhoto.PrevPhotoID);
	}	
	
	function LoadNextPhoto()
	{
		this.LoadPhoto(this.CurrentPhoto.NextPhotoID);
	}	
	
	function LoadPhoto_Callback(response)
	{
		if (this.readyState != 4 || this.status != 200) return false;
		if (response)
		{
			var node = response.documentElement.selectSingleNode("Photo");
			galleryManager.CurrentPhoto.Parse(node);
			galleryManager.CurrentPhoto.BindControl();
			ProcessButtons();
		}
	}
	
	function PhotoAddVote_Callback(response)
	{
		if (this.readyState != 4 || this.status != 200) return false;
		if (response)
		{
			var node = response.documentElement.selectSingleNode("Photo");
			galleryManager.CurrentPhoto.Parse(node);
			galleryManager.CurrentPhoto.BindControl();
			ProcessButtons();
			// Set cookie
			node = response.documentElement.selectSingleNode("Cookies/Cookie[@Name=\"GalleryVoting\"]");
			if (node != null)
			{
				var value = GetStrValue(node.selectSingleNode("Value"));
				//var expires = GetStrValue(node.selectSingleNode("Expires"));
				
				SetCookie("GalleryVoting", value);
				alert("Hlasování proběhlo úspěšně.\nPočet hlasujících: " + galleryManager.CurrentPhoto.VoteCount + "\nPočet hlasů: " + galleryManager.CurrentPhoto.VoteValue);
			}
		}
	}
	
	function PhotoAddVote(voteValue)
	{
		if (this.CurrentPhoto != null && this.CurrentPhoto.ID != 0)
		{
			var writer = new XmlWriter();
			writer.WriteStartElement("Request");
			writer.WriteStartElement("Cookies");
			writer.WriteStartElement("Cookie");
			writer.WriteAttributeString("Name", "GalleryVoting");
			writer.WriteElementString("Value", GetCookie("GalleryVoting"));
			writer.WriteEndElement();
			writer.WriteEndElement();
			writer.WriteEndElement();
			Send(this.Url + "?method=PhotoAddVote&photoID=" + this.CurrentPhoto.ID + "&voteValue=" + voteValue, writer.Output, PhotoAddVote_Callback);	
		}
	}
	
	function CreateRequest()
	{
		return new XMLHttpRequest();
	}
	
	function Send(url, data, callback)
	{
		if (url && callback) 
		{
			var request	= CreateRequest();
			request.onreadystatechange = callback;
			request.open("POST", url + "&DontParse=true", true);
			request.send(data);
		}
	}
}
var galleryManager = new GalleryManager();

function RegisterUser_Callback(response)
{
	if (this.readyState != 4 || this.status != 200) return false;
	if (response)
	{
		try
		{
			var node = response.documentElement.selectSingleNode("Result");
			if (GetBoolValue(node))
			{
				alert("Uživatel byl úspěšně registrován.");
				HideRegistration();
			}
			else
			{
				alert("Registrace byla neúspěšná.");
			}
		}
		catch(e)
		{
			alert("Během registrace nastala chyba.");
		}
	}
}

function ProcessRegistration()
{
	galleryManager.CurrentUser.BindSource();
	galleryManager.RegisterUser(galleryManager.CurrentUser, RegisterUser_Callback);
}

function ProcessButtons()
{
   var btn = document.getElementById("PrevButton");
    if (btn)
        btn.style.visibility = galleryManager.CurrentPhoto.PrevPhotoID > 0 ? "visible" : "hidden";
    btn = document.getElementById("NextButton");
    if (btn)
        btn.style.visibility = galleryManager.CurrentPhoto.NextPhotoID > 0 ? "visible" : "hidden";
}

function ResizeWindow()
{
    var container = document.getElementById("container");
    if (container)
    {
        window.resizeTo(container.offsetWidth + 11, container.offsetHeight + 62);
    }
}