var _canvasId = "canvas";
var _canvasElement;
var _canvasCtx;
var _imageMngr;
var _casualAudio = new Audio("music/casual.mp3");
	_casualAudio.loop = true;
	_casualAudio.volume = 1;
var _angzayetyAudio = new Audio("music/angzayety.mp3");
	_angzayetyAudio.loop = true;
	_angzayetyAudio.volume = 0;

// Timer Support.
var _timerTextLocation = {x: 140, y: 196};
var _gameStartTime;
var _highscoreLocation = {x: 310, y: 196};
var _hightscoreCookie = "highscore="

// Game update support.
var _eventChance;
var _lastFrame;
var _isPause;
var _gameOver;

// street support.
var _streetPeople = [];
var _streetStartY;
var _streetStartX;
var _newStreetPersonCooldown;
var _newStreetPersonTimeLeft;
var _newStreetPersonChance;
var _newStreetPersonIsFriendChance;
var _streetPlayerStartX;
var _streetPlayer;
var _streetBackground = [];

// portrait person support.
var _portraitStartX = 540;
var _portraitStartY = 150;

// Buttons Support
var _waveBtnLocation = {x: 155, y: 250};
var _hideBtnLocation = {x: 50, y: 410};
var _moreBtnLocation = {x: 275, y: 410};
var _pressedButton = 0;
var _borderRight = 0;
var _borderWrong = 0;
var _bordersTimer = 0;

// Event Support.
var _phoneObj;
var _closeEvent;
var _eventReadyToClose;

// Friends Support.
var _friends = [];

// Anxiety Support
var _angzayetyLevel = 0 //between 0 and 1
var _angzayetyProg = 0.05

function initiateGame()
{
	_imageMngr = new imagesManager();
	_canvasElement = document.getElementById(_canvasId);
	_canvasCtx = _canvasElement.getContext("2d");

	// street init.
	_streetStartY = 41;
	_streetStartX = _canvasElement.width;
	_newStreetPersonCooldown = 4000;
	_newStreetPersonTimeLeft = 0;
	_newStreetPersonChance = 1/175;
	_newStreetPersonIsFriendChance = 0.2;
	_newStreetPersonIsFriendMaxChance = 0.65;
	_streetBackground = [0];
	_streetPlayerStartX = 120;
	_streetPlayer = generatePersonMeta(new Person(_imageMngr), _streetPlayerStartX, _streetStartY, true, false);

	// event init.
	_eventChance = 1;
	_isPause = false;
	_gameOver = false;
	_phoneObj = {
		x: 50, 
		y: _canvasElement.height, 
		textXoffset: 40, 
		textYoffset: 175, 
		textFont: "20px Arial", 
		textColor: "black", 
		lineSpacing: 23,
		msgTypeXoffset: 145,
		msgTypeYoffset: 335};

	_canvasElement.onclick = handleClick;

	setTimeout(function(){displayLoadingProgress();}, 300);
}

function displayLoadingProgress()
{
	if(_imageMngr != null)
	{
		loadingCount = _imageMngr.isCompleted();
		displayText = _imageMngr._done_count + " / " + _imageMngr._images_count;
		if(loadingCount == 0)
		{
			_casualAudio.play();
			_angzayetyAudio.play();
			(new StartScreen(_imageMngr, _canvasElement, _canvasCtx, timerToString(getHighscore()), startNewGame)).displayStartScreen();
		}
		else
		{
			if(loadingCount != "error")
			{
				setTimeout(function(){displayLoadingProgress();}, 300);
			}
			else
			{
				displayText = "error";
			}

			_canvasCtx.save();

			_canvasCtx.clearRect(0, 0, _canvasElement.width, _canvasElement.height);
			_canvasCtx.fillStyle = "black";
			_canvasCtx.font = "30px Arial";
			_canvasCtx.fillText(displayText, _canvasElement.width / 2, _canvasElement.height / 2);

			_canvasCtx.restore();
		}
	}
}

function startNewGame()
{
	_canvasElement.style.cursor = "";
	_gameStartTime = 0;

	// Start new game.
	_lastFrame = new Date().getTime();
	gameLoop();
}

function gameLoop()
{
	elapsedTime = new Date().getTime() - _lastFrame;
	if(_isPause)
	{
		handleCurrentEvent();
	}
	else
	{
		onUpdate(elapsedTime);
	}

	if(_gameOver)
	{
		if(_gameStartTime > getHighscore())
		{
			var d = new Date();
			d.setTime(d.getTime() + (365*24*60*60*1000));
			var expires = "expires=" + d.toUTCString();

			document.cookie = _hightscoreCookie + _gameStartTime + "; " + expires;
		}
		(new EndScreen(_imageMngr, _canvasElement, _canvasCtx, timerToString(_gameStartTime), timerToString(getHighscore()), function(){
			window.location.reload();
		})).displayEndScreen();
	}
	else
	{
		onDraw(elapsedTime);

		_lastFrame = new Date().getTime();
		setTimeout(function(){gameLoop();}, 10);
	}
}

function drawButtonFrame(isRight, btnIdx)
{
	btnLocation = null;
	if(btnIdx == 1)
	{
		btnLocation = _waveBtnLocation;
	}
	else if(btnIdx == 2)
	{
		btnLocation = _hideBtnLocation;
	}
	else if(btnIdx == 3)
	{
		btnLocation = _moreBtnLocation;
	}

	if(btnLocation != null)
	{
		offsetX = -4;
		offsetY = -4;

		if(isRight)
		{
			_canvasCtx.drawImage(_imageMngr.buttons.right, btnLocation.x + offsetX, btnLocation.y + offsetY);
		}
		else
		{
			_canvasCtx.drawImage(_imageMngr.buttons.wrong, btnLocation.x + offsetX, btnLocation.y + offsetY);
		}
	}
}

function onDraw(elapsedTime)
{
	// Redraw.
	_canvasCtx.drawImage(_imageMngr.background, 0, 0);
	drawStreet();
	if(!_isPause) 
	{
		drawClosePerson();
	}
	drawButtons();
	updateTimer();
	angzayetyCheck();
	if(_borderRight != 0)
	{
		drawButtonFrame(true, _borderRight);
	}
	if(_borderWrong != 0)
	{
		drawButtonFrame(false, _borderWrong);
	}
	if(_bordersTimer > 0)
	{
		_bordersTimer -= elapsedTime;
		if(_bordersTimer <= 0)
		{
			_borderRight = 0;
			_borderWrong = 0;
		}
	}
	

	if(_isPause)
	{
		_canvasCtx.drawImage(_phoneObj.showImage, _phoneObj.x, _phoneObj.y);

		_canvasCtx.save();
		_canvasCtx.fillStyle = _phoneObj.textColor;
		_canvasCtx.font = _phoneObj.textFont;

		for(idx = 0, len = _phoneObj.text.length; idx < len; idx++)
		{
			_canvasCtx.fillText(_phoneObj.text[idx], _phoneObj.x + _phoneObj.textXoffset, _phoneObj.y + _phoneObj.textYoffset + (_phoneObj.lineSpacing * idx));
		}

		_canvasCtx.fillText(_phoneObj.msgType, _phoneObj.x + _phoneObj.msgTypeXoffset, _phoneObj.y + _phoneObj.msgTypeYoffset);
		_canvasCtx.restore();

		drawPersonPortrait(_canvasCtx, _phoneObj.person);
	}
}

function onUpdate(elapsedTime)
{
	_newStreetPersonTimeLeft -= elapsedTime;
	_gameStartTime += elapsedTime;

	// Logic.
	if(Math.random() <= _eventChance)
	{
		createEvent();
	}

	if(_newStreetPersonTimeLeft <= 0)
	{
		if(Math.random() <= _newStreetPersonChance)
		{
			friendChance = _newStreetPersonIsFriendChance * _friends.length;
			if(friendChance > _newStreetPersonIsFriendMaxChance)
			{
				friendChance = _newStreetPersonIsFriendMaxChance
			}
			if(Math.random() <= friendChance)
			{
				newStreetPerson = _friends[Math.round(Math.random() * (_friends.length - 1))]
			}
			else
			{
				newStreetPerson = new Person(_imageMngr);
				
				while(checkIfPersonExists(_friends, newStreetPerson))
				{
					newStreetPerson = new Person(_imageMngr);
				}
			}

			_streetPeople.push(generatePersonMeta(newStreetPerson, _streetStartX, _streetStartY, false, false));

			_newStreetPersonTimeLeft = _newStreetPersonCooldown;
		}
	}

	viewProgress();
}

function changeAngzayety(diff)
{
	_angzayetyLevel += diff;

	if(_angzayetyLevel < 0) {
		_angzayetyLevel = 0;
	}
	if(_angzayetyLevel > 1) {
		_angzayetyLevel = 1
	}
}

function viewProgress()
{
	for(i = 0, len = _streetPeople.length; i < len; i++)
	{
		if(len != _streetPeople.length) {
			console.log("a" + len);
			console.log(_streetPeople.length);
		}
		_streetPeople[i].x -= 0.6 + (_friends.length / 10);
		_newStreetPersonCooldown = 4000 - (_friends.length * 100)

		if(_streetPeople[i].x <= _canvasElement.width * 0.4)
		{
			if(_streetPeople[i].x >= _canvasElement.width / 12)
			{
				_streetPeople[i].isClose = true;
			}
			else if(_streetPeople[i].isClose)
			{
				_streetPeople[i].isClose = false;

				if(checkIfPersonExists(_friends, _streetPeople[i].person))
				{
					friendLevel = _streetPeople[i].person.friendLevel;

					if(friendLevel == FEED_MSG_ADD)
					{
						_borderRight = 1;
						_bordersTimer = 700;
						if(_pressedButton == 1)
						{
							changeAngzayety(-_angzayetyProg);
						}
						else
						{
							changeAngzayety(_angzayetyProg*8);
							_borderWrong = _pressedButton;
						}
					}
					else if(friendLevel == FEED_MSG_BAD)
					{
						_borderRight = 2;
						_bordersTimer = 700;
						if(_pressedButton == 2)
						{
							changeAngzayety(-_angzayetyProg);
						}
						else
						{
							changeAngzayety(_angzayetyProg*8);
							_borderWrong = _pressedButton;
						}
					}
					else if(friendLevel == FEED_MSG_MORE)
					{
						_borderRight = 3;
						_bordersTimer = 700;
						if(_pressedButton == 3)
						{
							changeAngzayety(-_angzayetyProg);
						}
						else
						{
							changeAngzayety(_angzayetyProg*8);
							_borderWrong = _pressedButton;
						}
					}
				}
				else
				{
					if(_pressedButton != 0) {
						changeAngzayety(_angzayetyProg*8);
						_borderWrong = _pressedButton;
						_bordersTimer = 700;
					}
				}

				_pressedButton = 0;
			}
		}
	}

	if(_streetPeople[0] != null && _streetPeople[0].x < -100)
	{
		_streetPeople.splice(0, 1);
	}

	for(i = 0, len = _streetBackground.length; i < len; i++)
	{
		_streetBackground[i] -= 0.6;
	}

	if(_streetBackground[1] <= 0)
	{
		_streetBackground.splice(0, 1);
	}

	if(_streetBackground[1] == null)
	{
		_streetBackground.push(_streetBackground[0] + _imageMngr.street.width);
	}
}

function drawClosePerson()
{
	for (i = 0, len = _streetPeople.length; i < len; i++)
	{
		if(_streetPeople[i].isClose)
		{
			drawPersonPortrait(_canvasCtx, _streetPeople[i].person);
			break;
		}
	}
}

function drawPersonPortrait(ctx, person) 
{
    for(p in person.parts) {
        ctx.drawImage(person.parts[p], _portraitStartX, _portraitStartY);
    }
}

function drawStreetPerson(ctx, personMeta)
{
	imageFrame = personMeta.person.getCurrWalkingFrame(_isPause);
	showImage = _imageMngr.streetPersonWalking[imageFrame];

	if(personMeta.isPlayer)
	{
		showImage = _imageMngr.streetPlayerWalking[imageFrame];
	}

	_canvasCtx.drawImage(showImage, personMeta.x, personMeta.y);
}

function drawStreet()
{
	for(i = 0, len = _streetBackground.length; i < len; i++)
	{
		_canvasCtx.drawImage(_imageMngr.street, _streetBackground[i], 0);
	}

	drawStreetPerson(_canvasCtx, _streetPlayer);

	for (i = 0, len = _streetPeople.length; i < len; i++)
	{
		drawStreetPerson(_canvasCtx, _streetPeople[i]);
	}
}

function timerToString(miliseconds)
{
	seconds = Math.floor((miliseconds / 1000) % 60);
	if(seconds < 10)
	{
		seconds = "0" + seconds;
	}

	minutes = Math.floor((miliseconds / 1000) / 60);
	if(minutes < 10)
	{
		minutes = "0" + minutes;
	}

	timerText =  minutes + ":" + seconds;
	return timerText
}

function updateTimer()
{
	_canvasCtx.save();
	_canvasCtx.fillStyle="black";
	_canvasCtx.font = "30px Arial";

	timerText = timerToString(_gameStartTime);

	_canvasCtx.fillText(timerText, 
		_timerTextLocation.x, 
		_timerTextLocation.y);


	_canvasCtx.fillStyle="gold";
	hightscore = timerToString(getHighscore())
	_canvasCtx.fillText(hightscore, 
		_highscoreLocation.x, 
		_highscoreLocation.y);

	_canvasCtx.restore();
}

function getHighscore()
{
	highscore = 0;
	if(document.cookie.indexOf(_hightscoreCookie) > -1)
	{
		highscore = document.cookie.split(_hightscoreCookie)[1].split(";")[0]
	}

	return highscore;
}

function angzayetyCheck()
{
	if(_angzayetyLevel >= 1)
	{
		_casualAudio.volume = 0;
		_angzayetyAudio.volume = 1;

		_gameOver = true;
	}
	else
	{
		_casualAudio.volume = 1 - _angzayetyLevel;
		_angzayetyAudio.volume = _angzayetyLevel;

		_canvasCtx.save();

		_canvasCtx.globalAlpha = _angzayetyLevel;
		_canvasCtx.drawImage(_imageMngr.angzayety, 0, 0);

		_canvasCtx.restore();
	}
}

function generatePersonMeta(person, startX, startY, isPlayer, isClose)
{
	return {person: person, x: startX, y: startY, isClose: isClose, isPlayer: isPlayer};
}

function drawButtons()
{
	showImage = _imageMngr.buttons.wave.plain;
	if (_pressedButton == 1)
	{
		showImage = _imageMngr.buttons.wave.pressed;
	}
	_canvasCtx.drawImage(showImage, _waveBtnLocation.x, _waveBtnLocation.y);

	showImage = _imageMngr.buttons.hide.plain;
	if (_pressedButton == 2)
	{
		showImage = _imageMngr.buttons.hide.pressed;
	}
	_canvasCtx.drawImage(showImage, _hideBtnLocation.x, _hideBtnLocation.y);

	showImage = _imageMngr.buttons.more.plain;
	if (_pressedButton == 3)
	{
		showImage = _imageMngr.buttons.more.pressed;
	}
	_canvasCtx.drawImage(showImage, _moreBtnLocation.x, _moreBtnLocation.y);
}

function isClickOnButton(x, y, buttonLocation, buttonImage)
{
	if(x >= buttonLocation.x && x <= (buttonLocation.x + buttonImage.width) 
		&& y >= buttonLocation.y && y <= (buttonLocation.y + buttonImage.height))
	{
		return true;
	}

	return false;
}

function handleClick(event)
{
	if(_isPause && _eventReadyToClose)
	{
		_closeEvent = true;
	}
	else
	{
		canvasRect = _canvasElement.getBoundingClientRect();
		x = event.clientX - canvasRect.left;
		y = event.clientY - canvasRect.top;

		if(isClickOnButton(x, y, _waveBtnLocation, _imageMngr.buttons.wave.plain))
		{
			_pressedButton = 1;
		}
		else if(isClickOnButton(x, y, _hideBtnLocation, _imageMngr.buttons.hide.plain))
		{
			_pressedButton = 2;
		}
		else if(isClickOnButton(x, y, _moreBtnLocation, _imageMngr.buttons.hide.plain))
		{
			_pressedButton = 3;
		}
	}
}

function createEvent()
{
	_isPause = true;
	_closeEvent = false;
	_eventReadyToClose = false;
	newEvent = getFeedEvent();

	personToShow = null;
	if(_friends.length < 3)
	{
		_eventChance = 1/400;

		while(newEvent.type != FEED_MSG_ADD)
		{
			newEvent = getFeedEvent();
		}
	}
	else
	{
		_eventChance = 1/2100;
		if(newEvent.type != FEED_MSG_ADD)
		{
			idx = Math.floor(Math.random() * _friends.length);
			personToShow = _friends[idx];

			while(personToShow.friendLevel == newEvent.type)
			{
				newEvent = getFeedEvent();
			}

			if(newEvent.type == FEED_MSG_LOST)
			{
				_friends.splice(idx, 1);
			}
		}
	}

	if (newEvent.type == FEED_MSG_ADD)
	{
		newPerson = new Person(_imageMngr);
		while (checkIfPersonExists(_friends, newPerson) ||
				checkIfPersonExists(_streetPeople, newPerson))
		{
			newPerson = new Person(_imageMngr);
		}

		_friends.push(newPerson);
		newPerson.friendLevel = FEED_MSG_ADD;
		personToShow = newPerson;
	}

	personToShow.friendLevel = newEvent.type;

	_phoneObj.person = personToShow;

	_phoneObj["showImage"] = _imageMngr.phoneImages[newEvent.type];


	textRows = [];
	while(newEvent.msg != "")
	{
		if(newEvent.msg.length < 35)
		{
			textRows[textRows.length] = newEvent.msg;
			break;
		}
		else if(newEvent.msg[35] == " ")
		{
			textRows[textRows.length] = newEvent.msg.substring(0, 35);
			newEvent.msg = newEvent.msg.substring(36);
		}
		else
		{
			idx = 35;
			while(idx > 0)
			{
				if(newEvent.msg[idx] == " ")
				{
					textRows[textRows.length] = newEvent.msg.substring(0, idx);
					newEvent.msg = newEvent.msg.substring(idx + 1);
					break;
				}

				idx--;
			}
		}
	}

	_phoneObj["text"] = textRows;
	_phoneObj["msgType"] = newEvent.type;
}

function handleCurrentEvent()
{
	if(_eventReadyToClose == false)
	{
		if(_phoneObj.y > 235)
		{
			_phoneObj.y -= 10;
		}
		else
		{
			_eventReadyToClose = true;
		}
	}
	
	if(_eventReadyToClose && _closeEvent)
	{
		_phoneObj.y += 10;

		if(_phoneObj.y == _canvasElement.height)
		{
			_isPause = false;
		}
	}
}

function checkIfPersonExists(personArray, newPerson)
{
	retVal = false;

	for(idx = 0, lennn = personArray.length; idx < lennn; idx++)
	{
		if(personArray[idx].hash == newPerson.hash)
		{
			retVal = true;
			break;
		}
	}

	return retVal;
}