/*************************** Global vars *****************************/
// Base URL for JSON files.
BASEURL		= 'http://www.sverigetopplistan.se';
SCRIPTURL	= BASEURL + '/netdata/ghj001.mbr/';

// Loading image html 
LOADING		= '<img id="loadimg" src="images/loading_bargraph.gif" alt="Laddar..." />';
LOADINGMSG	= 'Vänta...';

// No-image cover artworks to use when not available
NOIMAGE_KVA	= 'images/noimage_kva.png';
NOIMAGE_KVB	= 'images/noimage_kvb.png';

// Session variables
DEFAULT		= null;

// Already built charts html - cache
CHARTSCACHE	= new Array();

// History Array
HISTORY = new Array();

//Stores current page action to be used in bookmarks/scripts
CURRENTACTION = "";
/************************* End of Global vars *************************/

/**
 * Main function
 */
$(function(){
	//Initiates session, gets default data and builds Urval structure
	startSession();

	//prepare page to react to ajax showing a loading image
	$(document).ajaxStart(function(){
		showLoading();
	}).ajaxStop(function(){
		hideLoading();
	});
	//configure ajax to timeout in 10 seconds
	$.ajaxSetup({
		timeout: 10000,
		error: function(x,e){
			showAjaxError(x,e);
			hideLoading();
		}
	});

	//Create jQuery-UI buttons
	$('input:submit').button();

	//Make links open in new tab/window
	externalLinks();
});

/**
 * Function which starts the session in the server and loads the json
 * response with default vars and chart to load.
 */
function startSession() {
	var url =
		($.cookie("xpdato") == null || $.cookie("xpwlnr") == null) ?
		SCRIPTURL + 'startsession.json?callback=?' : 
		SCRIPTURL + 'startsession.json?xpdato=' + $.cookie("xpdato") + '&xpwlnr=' + $.cookie("xpwlnr") + '&callback=?';
	//Start session and load defaults
	$.getJSON(
		url,
		function (data) {
			if (isDefined(data) && data.success == 'true') {
				//Retrieve session data and default chart
				$.cookie("xpdato", data.xpdato);
				$.cookie("xpwlnr", data.xpwlnr);
				DEFAULT = data.load;

				//Then load navigation
				loadNavigationList();
				
				//Load Urval panel
				loadUrval();

				//Load right action, according to url params
				frontController();
			}
			else {
				console.log('Error retrieving default info. Server offline, invalid JSON file or inexistent chart.');
				showContent('\
					<p class="msg ui-state-highlight ui-corner-all">\
						<span class="ui-icon ui-icon-alert"></span>\
						Ett fel inträffade. Försök igen om en liten stund.\
					</p>'
				);
			}
		}
	);
}



/**
 * Function which retrieves json file for chartgroups and builds the
 * navigation list from the featured groups (group: 'F')
 */
function loadNavigationList() {
	//The element where it will be inserted
	element = 'div#navigering ul.menu';
	
	//load navigation list
	$.getJSON(
		SCRIPTURL + 'chartgroups.json?xpdato=' + $.cookie("xpdato") + '&xpwlnr=' + $.cookie("xpwlnr") + '&callback=?',
		function(data) {
			var navhtml;

			if (isDefined(data.chartsgroups)) {
				
				//If first element is defined
				if (data.chartsgroups[0].listGroup == 'F') {

					//Retrieve featured charts group and start list
					var feat = data.chartsgroups[0].charts;

					//Add a list item with Home link to default chart
					var listitems = '\
						<li class="special">\
							<a href="javascript:void(0);" onclick="loadChart(' + DEFAULT.liid + ', ' + DEFAULT.dspy + ', ' + DEFAULT.dspp + ');" >Hem</a>\
						</li>';

					//For each list item (a featured chart) add its list item and link
					$.each(feat, function(chartkey) {

						//get chart by its key params
						var chart = feat[chartkey];

						//build list item with name and url
						listitems += '\
							<li>\
								<a href="javascript:void(0);" onclick="loadChart(' + chart.liid + ', ' + chart.dspy + ', ' + chart.dspp + ');">' + chart.rubr + '</a>\
							</li>';
					});

					navhtml = listitems;
				}
			}
			else {
				console.log('Error retrieving links from server. Server down or invalid JSON file.');
				//If there is no valid action or valid parameters, show msg to load default chart
				navhtml = '\
					<p class="msg ui-state-highlight ui-corner-all">\
						<span class="ui-icon ui-icon-alert"></span>\
						Ett fel inträffade när navigeringen skulle hämtas.\
					</p>';
			}
			//Insert parsed result or error msg into innerpanel
			$(element).prepend(navhtml);
		}
	);
}

/**
 * Function that loads a chart in content panel from its category id
 * (liid), year (dspy) and period (dspp).
 * First builds the URL and then parse it.
 */
function loadChart(liid, dspy, dspp) {

	if (!liid || !dspy || !dspp) {
		
		//If there is no valid action or valid parameters, show msg to load default chart
		console.log("Can't load chart, missing parameter. LIID = " + liid + "; DSPY = " + dspy + "; DSPP = " + dspp);
		showContent('\
			<p class="msg ui-state-highlight ui-corner-all">\
				<span class="ui-icon ui-icon-alert"></span>\
				Vald lista kan inte hämtas, Klicka <a href="#" onclick="loadChart(' + DEFAULT.liid + ', ' + DEFAULT.dspy + ', ' + DEFAULT.dspp + ');">här</a> för att hämta startlistan.\
			</p>'
		);
		return;
	}

	//save current content in history and save current action
	saveHistory();
	saveCurrentAction({'action':'loadchart', 'liid':liid, 'dspy':dspy, 'dspp':dspp});

	//Check if this chart was loaded before and stored in cache
	var cachedHtml;
	if (cachedHtml = getChart(liid, dspy, dspp)) {
		
		//then show chart
		showContent(cachedHtml);

		//Callback function to run after loading
		if (typeof callback == 'function')
			callback();

		//and return
		return;
	}

	//If it was not cached, build chart url from the parameters
	var chartURL = SCRIPTURL + 'chart.json?liid=' + liid + '&dspy=' + dspy + '&dspp=' + dspp + '&callback=?';

	//Then load chart
	$.getJSON(
		chartURL,
		function(data) {

			if (data.success == 'true') {

				//If first element is defined
				if (isDefined(data.chart[0].arso)) {

					//create array with chart parts
					var a = {
						dataRubr	: data.rubr,
						dataText	: data.text,
						tableTop	: buildTopTable(data),
						tableChart	: buildChartTable(data, 1, data.chart.length),
						buttonBox	: buildButtonBox(data, true)
					}

					//Build chart data/table
					var html = 
						a.buttonBox
						+ '<h2 class="mainchart" >' + a.dataRubr + ' - ' + a.dataText + '</h2>'
						+ a.tableTop
						+ a.tableChart
						+ a.buttonBox;

					//store chart in cache
					storeChart(data.liid, data.dspy, data.dspp, html);

					//Insert parsed result or error msg into innerpanel
					showContent(html);

					//Callback function to run after loading
					if (typeof callback == 'function') {
						callback();
					}
				}
			}
			else {
				console.log("Could not load chart. " + data.msg);
				showContent(
					'<p class="msg ui-state-highlight ui-corner-all">\
						<span class="ui-icon ui-icon-alert"></span>\
						Hämtning av listan misslyckades.\
					</p>'
				);
			}
		}
	);
}


function showLoading() {
	$('div#loadpanel').fadeIn(100);
}

function hideLoading() {
	$('div#loadpanel').fadeOut(100);
}

function showContent(htmlContent) {
	//fadeout content div...
	$('div#content').fadeOut(100, function() {

		//...then replace content with html and fade it in
		$('div#content').html(htmlContent).fadeIn(100);

		//After all, compact buylink blocks
		compactBuyLinks('div#content .entrybuttons', '.buytitle', '.accordion');

		//and make links open in new tab/window
		externalLinks();
	});	
}

function saveHistory() {
	//save current content in history, if not empty
	var current = $('div#content').html();
	if (current)
		HISTORY.push(current);
}

function showAjaxError(x, e) {
	//hide loading msg
	hideLoading();
	//Log msg according to error
	if(x.status == 0) {
		console.log('You seem to be offline or trying cross-domain request.');
	}
	else if(x.status == 404) {
		console.log('404 - Requested URL not found.');
	}
	else if(x.status == 500) {
		console.log('500 - Internal Server Error.');
	}
	else if(e == 'parsererror') {
		console.log('Some error occurred while parsing requested JSON file.');
	}
	else if(e == 'timeout') {
		console.log('Your request has timed out. Please, try again.');
	}
	else {
		console.log('Unknow error. ' + x.responseText);
	}
	//Show error msg in content
	showContent('<p class="msg ui-state-highlight ui-corner-all">\
			<span class="ui-icon ui-icon-alert"></span>\
			There was an error requesting data to the server.\
		</p>');
}

function goBack() {
	if(HISTORY.length > 0) {
		//replace content with last from history
		$('div#content').fadeOut(100, function(){
			showContent(HISTORY.pop());
		});
	}
	else
		history.go(-1);
	return false;
}


function buildBackButton() {
	return '<a class="backbutton" href="javascript:void(0);" onClick="goBack();" title="Gå till föregående sida" >\
			<img src="images/back.png" alt="Bakåt" />\
		</a>';
}


function buildCoverImage(path, artist, title, classes) {
	return '<img class="' + classes + '" src="' + path + '" alt="' + artist + ' - ' + title + '" />';
}

function buildCertImage(cert, classes) {
	if (!cert)
		return '';

	//build array with cert image data
	var a = {
		imgsrc	: (cert.replace(' ', '_')).toLowerCase(),
		classes	: classes ? classes : 'cert',
		title	: cert
	};
	return '<img src="images/' + a.imgsrc + '.png" class="' + a.classes + ' noprint" title="' + a.title + '" alt="' + a.title + '" />\
		<span class="printonly">' + a.title + '</span>';
}

function buildTopCertImage(cert, classes) {
	if (!cert)
		return '';

	//build array with cert image data
	var a = {
		imgsrc	: (cert.replace(' ', '_')).toLowerCase(),
		classes	: classes,
		title	: cert
	};
	return '<img src="images/top_' + a.imgsrc + '.png" class="' + a.classes + '" title="' + a.title + '" alt="' + a.title + '" />';
}

function buildTopLngImage(lng) {
	if (lng == 'S')
		return '<img class="lng" src="images/se.png" alt="Svensk artist" title="Svensk artist" /><br />';
	return '';
}


function buildTopTable(data) {
	var row = data.chart[0];
	//insert in row all processed data
	row.classes	= getPosRowClasses(row.lng, row.bul);
	row.newPbpl	= buildPBPL(row.pbpl);
	row.newFgpl	= buildFGPL(row.fgpl, row.bul, true);
	row.newAvli	= buildAVLI(row.avli, true);
	row.newKva	= buildCoverImage(row.kva ? BASEURL + row.kva : NOIMAGE_KVA, row.arso, row.tit, 'kva');
	row.newCert	= buildTopCertImage(row.cert, 'cert');
	row.newArso = (row.arso).replace(new RegExp("\/", "g"),"/ ");
	row.newLng	= buildTopLngImage(row.lng);
	row.catName = buildCatName(row.bol, row.boltxt);
	row.buttons	= buildEntryButtons(data.liid, row.sart, row.buyExt);
	return '\
		<div class="box">\
			<table class="toppos">\
				<tbody>\
					<tr class="' + row.classes + '">\
						<td class="number pbpl">' + row.newPbpl + '</td>\
						<td class="number avli fgpl">\
							' + row.newFgpl + '<br />\
							<br />\
							' + row.newAvli + '\
						</td>\
						<td class="image kva">\
							' + row.newKva + row.newCert + '\
						</td>\
						<td class="text info">\
							<span class="artist">' + row.newArso + '</span><br />\
							<span class="title">' + row.tit + '</span><br />\
							' + row.newLng + '<br />\
							<span class="label">' + row.labl + '</span><br />\
							' + row.catName + '\
							<span class="catnum">' + row.katn + '</span><br /><br />\
							' + row.buttons + '\
						</td>\
					</tr>\
				</tbody>\
			</table>\
		</div>';
}

function buildChartTable(data, startRow, endRow) {
	var chartTable = '';

	//Build middle content of chart table, parsing each row
	for (var i = startRow; i < endRow; i++) {

		//If there is artists defined, get row
		if (isDefined(data.chart[i].arso)) {
			var row = data.chart[i];

			//insert processed data into row var
			row.swedish		= (row.lng == 'S' ? 'swedish' : '');
			row.classes		= getPosRowClasses(row.lng, row.bul, i);
			row.lngTitle	= (row.lng == 'S' ? 'Svensk artist' : '');
			row.newPbpl		= buildPBPL(row.pbpl, row.bul);
			row.newFgpl		= buildFGPL(row.fgpl, row.bul);
			row.newAvli		= buildAVLI(row.avli);
			row.newKvb		= buildCoverImage(row.kvb ? BASEURL + row.kvb : NOIMAGE_KVB, row.arso, row.tit, 'kvb');
			row.newLng		= (row.lng == 'S' ? '<br /><span class="lng printonly">Svensk artist</span>' : '');
			row.buttons		= buildEntryButtons(data.liid, row.sart, row.buyExt);
			row.newCert		= buildCertImage(row.cert);
			row.catName		= buildCatName(row.bol, row.boltxt);
			
			chartTable += '\
				<tr class="' + row.classes + '" >\
					<td class="number pbpl ' + row.swedish + '" title="' + row.lngTitle + '" >' + row.newPbpl + '</td>\
					<td class="number fgpl">' + row.newFgpl + '</td>\
					<td class="number avli">' + row.newAvli + '</td>\
					<td class="image kvb">' + row.newKvb + '</td>\
					<td class="text info">\
						<span class="artist">' + row.arso + '</span><br />\
						<span class="title">' + row.tit + '</span>\
						' + row.newLng + '\
						' + row.buttons + '\
					</td>\
					<td class="image cert">' + row.newCert + '</td>\
					<td class="text label">\
						<span class="label">' + row.labl + '</span><br />\
						' + row.catName + '\
						<span class="catnum">' + row.katn + '</span>\
					</td>\
				</tr>';
		}
	}

	//Return the whole table
	var copyrightText = buildChartCopyrightText(data.copyright);
	return '\
		<table class="charttable" >\
			<thead>\
				<tr>\
					<th title="Placering" >Placering</th>\
					<th title="Föregående placering på listan" >FG</th>\
					<th title="Antal placeringar på listan" >AVLI</th>\
					<th></th>\
					<th>Artist och titel</th>\
					<th>Guld/Platina certifiering</th>\
					<th>Skivmärke, Distribuerande bolag och katalognummer</th>\
				</tr>\
			</thead>\
			<tbody>\
				' + chartTable + '\
			</tbody>\
		</table>\
		' + copyrightText;
}

function buildQuicknavButtons(data) {
	//show navbuttons only in chart table pages
	if (!isDefined(data.nexter) && !isDefined(data.prevper))
		return "";
	//build next period button
	var nextper =
		data.nextper != 'false' ?
			'<a class="quicknav_next" href="javascript:void(0);" onclick="loadChart(' + data.liid + ', ' + data.nextper.dspy + ', ' + data.nextper.dspp + ')" title="Nästa period - ' + data.nextper.text + '">\
				<img src="images/chart_next.png" alt="Nästa" />\
			</a>' :
			'<span class="quicknav_next"><img src="images/chart_next_off.png" alt="" /></span>';
	//build previous period button
	var prevper =
		data.prevper != 'false' ?
			'<a class="quicknav_prev" href="javascript:void(0);" onclick="loadChart(' + data.liid + ', ' + data.prevper.dspy + ', ' + data.prevper.dspp + ')" title="Föregående period - ' + data.prevper.text + '">\
				<img src="images/chart_previous.png" alt="Föregående" />\
			</a>' :
			'<span class="quicknav_prev"><img src="images/chart_previous_off.png" alt="" /></span>';
	//return both buttons together
	return prevper + ' ' + nextper;
}

function buildCatName(bol, boltxt) {
	var data = new Object();
	//build boolean shorthand
	data.hasTxt = (isDefined(boltxt) && boltxt != '');

	//add processed params to data var
	data.mouseover	= (data.hasTxt ? 'mouseover' : '');
	data.title		= (data.hasTxt ? ('title="' + boltxt + '"') : '');
	data.bol		= bol;
	
	//and build catalog name html to return
	return '<span class="catname ' + data.mouseover + '" ' + data.title + ' >' + data.bol + '</span>';
}


function buildLoadChartButton(liid, dspy, dspp) {
	return '\
		<a href="javascript:void(0);" onclick="loadChart(' + liid + ', ' + dspy + ', ' + dspp + ')" title="Visa lista" >\
			<img src="images/loadchart.png" alt="Visa lista" style="vertical-align: middle;" />\
		</a>';
}

function buildEntryButtons(liid, sart, buyExt, appendContent) {
	// build array with parameters
	var a = {
		appendContent	: (appendContent ? appendContent : ''),
		liid			: liid,
		sart			: sart,
		buyLink			: buildBuyLink(buyExt)
	};
	return '\
		<div class="entrybuttons">\
			' + a.appendContent + '\
			<a class="details" href="javascript:void(0);" onclick="loadChartEntry(' + a.liid + ', ' + a.sart + ')" title="Visa artikel" >\
				<img src="images/details.png" alt="Visa artikel" />\
			</a>\
			' + a.buyLink + '\
		</div>';
}


function buildBuyLink(buyExt) {
	if (buyExt == 'false')
		return '';

	var links = '';
	var size = buyExt.length;

	//iterate and build links
	for (var i = 0; i < size; i++) {
		//get item in var for performance
		var item = buyExt[i];
		//insert processed param (icon src)
		item.buyIconSrc = BASEURL + item.buyIcon;
		
		links += '\
			<a class="buybutton" href="' + item.buyURL + '" title="' + item.buyName + '" rel="external" >\
				<img class="buyicon" src="' + item.buyIconSrc + '" alt="' + item.buyName + ' " />\
			</a> ';
	}
	
	return '\
		<span class="title buytitle" title="Köp" >\
				<img src="images/buy.png" alt="Köp" />\
		</span>\
		<div class="accordion" >' + links + '</div>';
}

function getPosRowClasses(lng, bul, rownum) {
	var parity		= (rownum % 2 == 1 ? 'odd ' : 'even ');
	var rowclass	= parity + (lng == 'S' ? 'swedish ' : '');
	switch (bul) {
		//same position on list
		case ''		: {rowclass += 'possame'; break;}
		//down on list
		case '-'	: {rowclass += 'posdown'; break;}
		//up or new to list
		case '+'	: {rowclass += 'posup'; break;}
		case '++'	: {rowclass += 'posup newcomer'; break;}
		case '+++'	: {rowclass += 'posup topnewcomer'; break;}
		//same position or no info
		default		: {break;}
	}
	return rowclass;
}

function buildPBPL(pbpl) {
	return '<span class="pbpl" title="Placering på listan" >' + pbpl + '</span>';
}

function buildFGPL(fgpl, bul, topPos) {
	var title;
	var value;
	var preffix = topPos ? 'FGPL<br />[' : '';
	var suffix = topPos ? ']' : '';
	switch(fgpl) {
		case ('&#197;T')	: {title = 'Återinträdd på listan'; break;}
		case ('NY')			: {title = (bul == '+++' ? 'Högsta nykommling på listan' : 'Nykommling på listan'); break;}
		default				: {title = 'Föregående placering på listan'; break;}
	}
	return '<span class="fgpl" title="' + title + '" >' + preffix + ' ' + fgpl + ' ' + suffix + '</span>';
}


function buildAVLI(avli, topPos) {
	var preffix = topPos ? 'AVLI<br />[' : '';
	var suffix = topPos ? ']' : '';
	return '<span class="avli" title="Antal placeringar på listan" >' + preffix + ' ' + avli + ' ' + suffix + '</span>';
}

function buildChartCopyrightText(copyright) {
	if (copyright)
		return '<p class="copyright" >&copy; ' + copyright + '</p>';
	return '';
}


function saveCurrentAction(params) {
	if (isDefined(params)) {
		CURRENTACTION = params.action + '?action=' + params.action;
		for (var key in params) {
			if (key != 'action')
				CURRENTACTION += '&' + key + '=' + params[key];
		}
	}
}

function buildButtonBox(data, showFacebook) {
	if (isDefined(data)) {
		//build array with buttons
		var a = {
			backButton:	buildBackButton(),
			playlist:	buildPlaylistButton(data),
			facebook:	showFacebook ? buildFacebookButton() : "",
			navButtons:	buildQuicknavButtons(data)
		};
		return '\
			<div id="buttonbox" class="box2" >\
				<span>' + a.backButton + '</span>\
				<span>' + a.playlist + '</span>\
				<span>' + a.facebook + '</span>\
				<span class="quicknav">' + a.navButtons + '</span>\
			</div>';
	}
}

function buildPlaylistButton(data) {
	if (isDefined(data.addbuttons)) {
		var buttons = "";
		for(var i in data.addbuttons) {
			data.addbuttons[i].baseURL = BASEURL;
			var b = data.addbuttons[i];
			buttons += '\
				<span class="playlistbutton">\
					<a href="' + b.buttonURL + '" title="' + b.buttonName + '" rel="external" >\
						<img src="' + b.baseURL + b.buttonIcon + '" alt="' + b.buttonName + '" />\
					</a>\
				</span>';
		}
		return buttons;
	}
	return "";
}

function buildFacebookButton() {
	return '\
		<script src="http://connect.facebook.net/sv_SE/all.js#xfbml=1"></script>\
		<fb:like href="' + BASEURL + '/netdata/ghj001.mbr/' + CURRENTACTION + '" layout="button_count"  width="325" font="arial" colorscheme="light" show_faces="false"></fb:like>';
}

/**
 * Function which stores a built chart html to cache so it can be
 * retrieved later without having to load it again from the server.
 * @param liid string Category of chart
 * @param dspy string Year of the chart
 * @param dspp string Period/publication of chart
 * @return void
 */
function storeChart(liid, dspy, dspp, html) {
	var key = liid + "." + dspy + "." + dspp;
		//stores (or overwrite) chart html
		CHARTSCACHE[key] = html;
}

/**
 * Function which retrieves a previously built chart html from the cache.
 * Return the built html of cached chart or false if not stored.
 * @param liid string Category of chart
 * @param dspy string Year of the chart
 * @param dspp string Period/publication of chart
 * @return html string HTML code with chart content or false if it was
 * not cached.
 */
function getChart(liid, dspy, dspp) {
	var key = liid + "." + dspy + "." + dspp;
	//if chart is defined and stored in cache
	if (isDefined(CHARTSCACHE[key]))
		return CHARTSCACHE[key]; //return it
	
	//if not defined (not cached), return false
	return false;
}

