/*
 * It should be noted that this is such a complete mess because the functionality required was changing several times a day, and time constraints didn't allow for a rewrite, so I was forced to modify what I'd already written, which is always a nightmare... Such are clients.
 */

if(displayMode == 'large') {
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, changeListener);
}

j=jQuery.noConflict();

var selectedMatch = false;
var selectedRound;
var selectedSeason;
var globalData;
var initComplete = false;


function playerReady() {
	
j.ajax({
	type: 'GET',
	url:slHighlightsConfigUrl,
	dataType: 'json',

	success: function(data) {
		
		initData(data);
	},

	error: function(httpReq, textStatus) {

		j.ajax({
			type: 'GET',
			url:getCacheGenName(),
			dataType: 'json',

			success: function(data) {
				initData(data);
			},

			error : function(httpReq, textStatus) {

				initError("Could not get configuration data");
			}
		});
	}
});
}

var getCacheGenName = function() {

	chunks = slHighlightsConfigUrl.split("/");
	chunks2 = chunks[chunks.length - 1].split(".");
	chunks3 = chunks2[0].split("_");
	return 'index.php?id=' + chunks3[0] + '&type=' + chunks3[1];
}


var initData = function(data) {

	globalData = data;

	selectedSeason = globalData.currentSeason;
	selectedRound = globalData.currentRound;

	if(displayMode == 'large') {
		populateSeasonSelect();
	}

	setUrl();
	selectSeason();
	initComplete = true;
}


var initError = function(error) {

	sendJson('menu', {'error' : error});
}


var populateSeasonSelect = function() {

	var seasonSelect = $('#highlight_season_select').get(0);

	for (var season in globalData.seasons) {

		seasonSelect.options[seasonSelect.options.length] = new Option("Sæson " + season, season);
	}

	$('#highlight_season_select').change(seasonChanged);
}


var seasonChanged = function(value) {

	selectedSeason = $('#highlight_season_select option:selected').val();
	selectedRound = 1;

	setUrl();

	if(globalData.currentSeason == selectedSeason) {
		selectedRound = globalData.currentRound;
	}

	selectSeason();
}



var selectSeason = function() {

	var roundListContainer = $('#highlight_roundlist');
	roundListContainer.html('');

	for (var round in globalData.seasons[selectedSeason]) {

		if(typeof globalData.seasons[selectedSeason][round] != 'object') {
			roundBox(round, false);
		} else {
			roundBox(round, true);
		}

	}

	sendToFlash();
}


var roundBox = function(round, activeOrNot) {

	var roundListContainer = $('#highlight_roundlist');

	if(activeOrNot) {
		cssClass = "roundBoxActive";
	} else {
		cssClass = "roundBoxInactive";
	}

	if(round == selectedRound) {
		cssClass = "currentRound";
	}

	roundListContainer.append("<div class=\"roundBox " + cssClass + "\" id=\"roundBox-" + round + "\">" + round + "</div>");

	if(activeOrNot && (round != selectedRound)) {
		$('#roundBox-' + round).bind('click', {r: round}, roundClicked);
	}
}


var roundClicked = function(event) {


	var round = event.data.r;


	$('#roundBox-' + selectedRound).removeClass('currentRound').addClass('roundBoxActive');
	$('#roundBox-' + round).addClass('currentRound');
	selectedRound = $('#roundBox-' + round).text();

	if(selectedMatch) {
		selectedMatch = 1;
	}

	setUrl();

	//SWFAddress.setValue('saeson-' + selectedSeason + '/runde-' + selectedRound);

	selectSeason();
}


var sendToFlash = function() {

	var flashVars = new Array();


	for(var match in globalData.seasons[selectedSeason][selectedRound]) {
		var tmpArr =
		{'homeTeam' : globalData.teams[globalData.seasons[selectedSeason][selectedRound][match][0]][0],
		'homeScore' : globalData.seasons[selectedSeason][selectedRound][match][1],
		'awayTeam' : globalData.teams[globalData.seasons[selectedSeason][selectedRound][match][2]][0],
		'awayScore' : globalData.seasons[selectedSeason][selectedRound][match][3],
		'vidFile' : globalData.seasons[selectedSeason][selectedRound][match][4]};
		flashVars.push(tmpArr);
	}

	sendJson('menu', flashVars);
	if(displayMode == 'large') {
	    receiveFromFlash(["PLAY"]);
	}
}




function sendJson(target, obj) {

	if(target == 'menu')
		$("#tx_slhighlights_pi1_" + target).get(0).sendTextToFlash(JSON.stringify(obj));
	else {
		$("#tx_slhighlights_pi1_" + target).get(0).sendEvent(obj[0], obj[1]);
	}
}


function receiveFromFlash(obj) {

//alert("Got it from flash" + obj);
	sendJson('player', obj);
}


$(document).ready(function() {
	$('#image-overlay img').bind('click', function(event) {
		receiveFromFlash(["PLAY"]);
		$('#image-overlay').remove();
	});
});


function changeListener(event) {

	
	if(typeof(globalData) == 'undefined') {
		return;
	}

	if(SWFAddress.getValue().match(/kamp-\d+$/)) {
		return;
	}

	parseDeepLink();
	selectSeason();
}


function setUrl() {

	if(displayMode != 'large') {
		return;
	}

	if(SWFAddress.getValue() != '/' && !initComplete) {
		parseDeepLink();
	}

	var deepLink;
	if(selectedMatch) {
		deepLink = 'saeson-' + selectedSeason + '/runde-' + selectedRound + '/kamp-' + selectedMatch;
	} else {
		deepLink = 'saeson-' + selectedSeason + '/runde-' + selectedRound;
	}


	SWFAddress.removeEventListener(SWFAddressEvent.CHANGE, changeListener);
	SWFAddress.setValue(deepLink);
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, changeListener);
}



function parseDeepLink() {

	var deepLinkParts = SWFAddress.getValue().split("/");
	deepLinkParts.shift(); //Removes the empty slash

	selectedSeason = deepLinkParts[0].replace('saeson-', '');
	var valid = false;
	for(var season in globalData['seasons']) {
		if(season == selectedSeason) {
			valid = true;
		}
	}
	if(!valid) {
		selectedSeason = globalData.currentSeason;
	}

	selectedRound = deepLinkParts[1].replace('runde-', '');
	valid = false;
	for(var round in globalData['seasons'][selectedSeason]) {
		if(round == selectedRound) {
			valid = true;
		}
	}
	
	if(!valid) {
		selectedRound = globalData.currentRound;
	}

	if(deepLinkParts.length > 2) {
		
		selectedMatch = deepLinkParts[2].replace('kamp-', '');
		valid = false;


		for(var x = 0 ; x < globalData['seasons'][selectedSeason][selectedRound].length ; x++) {
			if(globalData['seasons'][selectedSeason][selectedRound][x][4] != false && selectedMatch == (x+1)) {
				valid = true;
			}
		}

		if(!valid) {
			selectedMatch = false;
		}

	} else {
		selectedMatch = 1;
	}

}
