// Music Engine Object
var ME = {};

ME.settings = {};
//Settings for ME
ME.settings.searchURL = 'http://music-engine.hoatle.net/search.php';
ME.settings.queryString = '';
ME.settings.startPage = '1';
ME.settings.previewingSongIndex = '';

ME.data = {};
ME.playlist = {};

ME.view = {};

//Enum for dialog box

ME.dialogBox = {};


ME.dialogBox.DOWNLOAD = 0;
ME.dialogBox.PREVIEW = 1;
ME.dialogBox.PREVIEW_CONFIRM = 2;

ME.dialogBox.preview_confirmed = false;
ME.dialogBox.preview_confirmed_no_action = true;

// This method for changing view and transport data as well: dest: canvas, profile, home...; Map: params
ME.view.gotoView = function(dest, params) {
  var dest_view = new gadgets.views.View(dest);
  gadgets.views.requestNavigateTo(dest_view, params);
}




ME.makeJSONRequest = function(url) {
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    gadgets.io.makeRequest(url, ME.getJSONResponse, params);
}

ME.getJSONResponse = function(obj) {
	
	function showErro() {
		var msg = 'Opps! There are some problems with the server. Please try again later!';
		ME.util.showMsg(msg, 'search-msg');
		
		window.setTimeout(function() {
			ME.util.clearMsg('search-msg');
		}, 5000);
		
		ME.util.enableAjaxLoader(false);
		return;
	}
	
	ME.data.searchResult = obj.data;
	// Server problem
	if (!ME.data.searchResult) {
		showErro();
	} else if (ME.data.searchResult == '') {
		showErro();
	} else {
		ME.displaySearchResult();
	}	


}

/*ME.searchbox*/

ME.searchbox = {};

ME.searchbox.init = function() {
	// Attach event to #txtQuery and #btnSearch
	
	var txtQueryEl = document.getElementById('txtQuery');
	txtQueryEl.value = 'Type your keyword here...';
	txtQueryEl.onfocus = function() {
		txtQueryEl.value = ME.settings.queryString;
	}
	
	var btnSearchEl = document.getElementById('btnSearch');
	btnSearchEl.onclick = function() {
		ME.search(txtQueryEl.value, 1);
	}
	// prevent default form submit
	var meSbEl = document.getElementById('me-sb');
	meSbEl.onsubmit = function () {
		ME.search(txtQueryEl.value, 1);
		return false;
	}
}




ME.searchbox.download = function(songIndex) {
	var song = ME.data.searchResult.songs[songIndex];
	var songName = song.sname;
	var songSinger = song.sartname;
	var songAlbum = song.salbum;
	var songDuration = song.sduration/60;
	songDuration = songDuration.toFixed(2);
	var songBitrate = song.sbitrate;
	var songSize = song.ssize;
	var songLink = song.slink;
	
	var dlContent = [];
	dlContent.push('<div id="dl-box">');
	dlContent.push('<p id="dl-notice">This file can be illegal to download.</p><p>Download copyrighted resource is at your own risk!</p>');
	dlContent.push('<fieldset><legend>' + songName + '</legend><ul>');
	dlContent.push('<li>Singer: <span>' + songSinger + '</span></li>');
	dlContent.push('<li>Album: <span>' + songAlbum + '</span></li>');
	dlContent.push('<li>Duration: <span>' + songDuration + ' mins</span></li>');
	dlContent.push('<li>Bitrate: <span>' + songBitrate + ' Kb/s</span></li>');
	dlContent.push('<li>Size: <span>' + songSize + ' Mb</span></li>');
	dlContent.push('</ul></fieldset>');
	dlContent.push('<div id="dl-buttons"><input name="dl-download" id="dl-download" type="button" value="Download" /><input name="dl-cancel" id="dl-cancel" type="button" value="Cancel" /></div>');
	dlContent.push('<div id="dl-link"><a href="' + songLink + '">Right click and Save...</a></div>');
	dlContent.push('</div>');
	
	// Close any other download box and open only one
	if (ZWWin.winIdExisted(ME.dialogBox.DOWNLOAD)) {
		ZWWin.removeElementByWinId(ME.dialogBox.DOWNLOAD);
	}
	var dlDialog = ZWDialog;
	dlDialog.windowid = ME.dialogBox.DOWNLOAD;
	dlDialog.Alert(ME.dialogBox.DOWNLOAD, dlContent.join(''), 'Download: ' + songName, 400, 310, 120, 100);
	
	
	init();
	
	function init() {
		// Init some configuration for the download box
		// Hide Link Download
		var linkDownload = document.getElementById('dl-link');
		linkDownload.style.visibility = 'hidden';
		
		// Attach event to download button and cancel button
		
		var btnDownload = document.getElementById('dl-download');
		
		btnDownload.onclick = function() {
			//var linkDownload = document.getElementById('dl-link');
			linkDownload.style.visibility = 'visible';
		}
		
		var btnCancel = document.getElementById('dl-cancel');
		btnCancel.onclick = function() {
			if (ZWWin.winIdExisted(ME.dialogBox.DOWNLOAD)) {
				ZWWin.removeElementByWinId(ME.dialogBox.DOWNLOAD);
			}
			
		}
		
	}
}


ME.searchbox.songPreview = function(songIndex) {
	/*
	var prSongIndex = ME.settings.previewingSongIndex;
	if (prSongIndex != '') {
		var prSong = ME.data.searchResult.songs[prSongIndex];
		var prSongName = prSong.sname;
		var prSongSinger =  prSong.sartname;
	}
	*/
	
	var song = ME.data.searchResult.songs[songIndex];
	var songName = song.sname;
	var songSinger = song.sartname;
	var songComposer = song.sswname;
	var songLink = song.slink;
	var prContent = [];
	prContent.push('<div id="pr-box">');
		prContent.push('<div id="pr-info">Singer: <span>' + songSinger + '</span> - Composer: <span>' + songComposer + '</span></div>');
		prContent.push('<div id="pr-player"></div>');
		prContent.push('<div id="pr-buttons">');
			prContent.push('<input type="button" name="pr-detail" id="pr-detail" value="Detail" />');
			prContent.push('<input type="button" name="pr-download" id="pr-download" value="Download" />');
		prContent.push('</div>');
	prContent.push('</div>');
	
	init();
	
     /* Comment here because of some complex issue, just resolve later
	// Close any other open preview dialog, can only one opened at a time
	// Remember to confirm to close the opening one

	if (ZWWin.winIdExisted(ME.dialogBox.PREVIEW)) {
		var prcfContent = [];
		prcfContent.push('<div id="pr-confirm-box">');
			prcfContent.push('<p>You are previewing a song.</p>');
			prcfContent.push('<p>Open this song will close that previewing song?</p>');
			prcfContent.push('<div><input type="button" name="pr-cf-yes" id="pr-cf-yes" value="Yes" />');
			prcfContent.push('<input type="button" name="pr-cf-no" id="pr-cf-no" value="No" /></div>');
		prcfContent.push('</div>');
				
		var confirmDialog = ZWDialog;
		confirmDialog.Alert(prcfContent.join(''), 'NOTICE:', 400, 200, 30, 60);
		confirmDialog.windowid = ME.dialogBox.PREVIEW_CONFIRM;
		confirmInit();
		
		// If no action, just close itseft after 5 seconds
		window.setTimeout(function() {
			if (ZWWin.winIdExisted(ME.dialogBox.PREVIEW_CONFIRM)) {
				ZWWin.removeElementByWinId(ME.dialogBox.PREVIEW_CONFIRM);
			}
		}, 5000);
		

	} else {
		init();
	}
	
	function confirmClose() {
		if (!ME.dialogBox.preview_confirmed && !ME.dialogBox.preview_confirmed_no_action) {
			// If yes on confirm to preview another song
			alert('open new');
			init();
		} else if (ME.dialogBox.preview_confirmed && !ME.dialogBox.preview_confirmed_no_action) {
			// If no on confirm to preview another song
			if (ZWWin.winIdExisted(ME.dialogBox.PREVIEW_CONFIRM)) {
				ZWWin.removeElementByWinId(ME.dialogBox.PREVIEW_CONFIRM);
				alert('no open new');
			}
			return;
		}
	}
	
	function confirmInit() {
		// assign event
		var prcfYes = document.getElementById('pr-cf-yes');
		var prcfNo = document.getElementById('pr-cf-no');
		
		prcfYes.onclick = function() {
			ME.dialogBox.preview_confirmed_no_action = false;
			ME.dialogBox.preview_confirmed = true;
			confirmClose();
		}
		
		prcfNo.onclick = function() {
			ME.dialogBox.preview_confirmed_no_action = false;
			ME.dialogBox.preview_confirmed = false;
			confirmClose();
		}
	}
	
	*/
	
	
	// Initialization for previewBox
	function init() {
		// Close any other download box and open only one
		if (ZWWin.winIdExisted(ME.dialogBox.PREVIEW)) {
			ZWWin.removeElementByWinId(ME.dialogBox.PREVIEW);
		}
		var prDialog = ZWDialog;
		prDialog.windowid = ME.dialogBox.PREVIEW;
		prDialog.Alert(ME.dialogBox.PREVIEW, prContent.join(''), 'Preview: ' + songName, 350, 150, 40, 50);
		
		//Attach event to detail and download box
		
		var btnDetail = document.getElementById('pr-detail');
		var btnDownload = document.getElementById('pr-download');
		
		btnDetail.onclick = function() {
			ME.searchbox.songDetail(songIndex);
		}
		
		btnDownload.onclick = function() {
			ME.searchbox.download(songIndex);
		}
		
		createPlayer();
		
		function createPlayer() {
            var flashvars = {
                    file: songLink, 
                    autostart:"true"
            }
            var params = {
                    allowfullscreen:"false", 
                    allowscriptaccess:"always"
            }
            var attributes = {
                    id:"pr-player",  
                    name:"pr-player"
            }
            swfobject.embedSWF("http://music-engine.appspot.com/opensocial/music-engine/player.swf", "pr-player", "300", "40", "9.0.115", false, flashvars, params, attributes);
        }
		
	}
}


ME.searchbox.songDetail = function(songIndex) {
	// Get song info
	var song = ME.data.searchResult.songs[songIndex];
	var songName = song.sname;
	var songComposer = song.sswname;
	var songAlbum = song.salbum;
	var songSinger = song.sartname;
	var songLink = song.slink;
	var songDuration = song.sduration/60; // to count in minute
	songDuration = songDuration.toFixed(2); // round 2 digits
	var songBitrate = song.sbitrate;
	var songSize = song.ssize;
	// Get song tab element
	var songTab = document.getElementById('me-song-tab');
	
	var stContent = [];
	stContent.push('<div id="song-details">');
		stContent.push('<div id="sd-player" class="right">');
			stContent.push('<div id="sd-pl"></div>');
			stContent.push('<div id="sd-pl-toolbar">');
					stContent.push('<ul><li><a onclick="ME.searchbox.addToPlaylist(' + songIndex + '); return false;" href="#"><img title="Add to Playlist" alt="Add to Playlist" src="http://music-engine.appspot.com/opensocial/music-engine/add-playlist.gif" /></a><a onclick="ME.searchbox.download(' + songIndex + ');return false;" href="#"><img title="Download" alt="Download" src="http://music-engine.appspot.com/opensocial/music-engine/download.gif" /></a></li>');
					stContent.push('<li><a onclick="ME.util.unimplemented(); return false;"; href="#">Update your music-stream life</a> - <a onclick="ME.util.unimplemented(); return false;" href="#">Send this to your friends</a></li></ul>');
					stContent.push('</div>');
			stContent.push('</div>');
		stContent.push('<div id="sd-detail" class="left">');
			stContent.push('<fieldset><legend>Song Details:</legend>');
				stContent.push('<ul><li>Song Name: <span>' + songName + '</span></li>');
				stContent.push('<li>Album: <span>' + songAlbum + '</span></li>');
				stContent.push('<li>Singer: <span>' + songSinger + '</span></li>');
				stContent.push('<li>Composer: <span>' + songComposer + '</span></li>');
				stContent.push('<li>Duration: <span>' + songDuration + ' mins</span></li>');
				stContent.push('<li>Bitrate: <span>' + songBitrate + ' Kb/s</span></li>');
				stContent.push('<li>File Size: <span>' + songSize + ' Mb</span></li></ul>');
				stContent.push('</fieldset>');
		stContent.push('</div>');
	stContent.push('</div>');
	
	songTab.innerHTML = stContent.join('');
	
	ME.tab.selectTab(ME.tab.SONG);
	
	init();
	
	function init() {
		
		plInit();
		
		function plInit() {
			var flashvars = {
                    file: songLink, 
                    autostart:"false"
            }
            var params = {
                    allowfullscreen:"true", 
                    allowscriptaccess:"always"
            }
            var attributes = {
                    id:"sd-player",  
                    name:"sd-player"
            }
            swfobject.embedSWF("http://music-engine.appspot.com/opensocial/music-engine/player.swf", "sd-pl", "300", "250", "9.0.115", false, flashvars, params, attributes);
		}
	}
}

/*Playlist  Tab*/
ME.searchbox.addToPlaylist = function(songIndex) {
	var song = ME.data.searchResult.songs[songIndex];
	// Check existence and add to the Array ME.playlist.list
	
	ME.util.unimplemented();
}

ME.displaySearchResult = function() {
	var list = [];
	var songs = ME.data.searchResult.songs;
	var length = songs.length;

	if (length == 0) {
		var msg = 'No result for <strong>' + ME.data.searchResult.query + '</strong>. Please try on other words.';
		ME.util.showMsg(msg, 'result-status');
	} else {
		for (var i = 0; i < length; i++) {
			var listItem = [];
			listItem.push('<li>');
			listItem.push('<a onclick="ME.searchbox.songDetail(' + i +'); return false;" href="#" title="View this song detail"><span class="sname">' + songs[i].sname + '</span></a>: ');
			listItem.push('By <span class="sartname"> ' + songs[i].sartname + '</span> [<a onclick="ME.searchbox.songPreview(' + i + '); return false;" href="#">Preview</a>]');
			listItem.push('<div>');
			listItem.push('<span class="playlist"><a onclick="ME.searchbox.addToPlaylist(' + i + '); return false;" href="#"><img title="Add to Playlist" alt="Add to Playlist" src="http://music-engine.appspot.com/opensocial/music-engine/add-playlist.gif" /></a></span>');
			listItem.push('<span class="detail"><a onclick="ME.searchbox.download(' + i + '); return false;" href="#"><img title="Download" alt="Download" src="http://music-engine.appspot.com/opensocial/music-engine/download.gif" /></a></span>');
			listItem.push('</div></li>');
			
			list.push(listItem.join(''));
		}
		document.getElementById('result-status').innerHTML = 'Results <span id="result-from"></span> - <span id="result-to"></span> of about <span id="result-total"></span> for <span id="result-query"></span>';
		var resultFrom = parseInt((ME.data.searchResult.startPage - 1) + '1');
		var resultTo = resultFrom + ME.data.searchResult.songs.length - 1;
		document.getElementById('result-from').innerHTML = resultFrom;
		document.getElementById('result-to').innerHTML = resultTo;
		document.getElementById('result-query').innerHTML = ME.data.searchResult.query;
		document.getElementById('result-total').innerHTML = ME.data.searchResult.totalResult;
		document.getElementById('result-list').innerHTML = list.join(' ');
		
		var loadingBotEl = '<span id="loading-bottom"><img src="http://music-engine.appspot.com/opensocial/music-engine/ajax-loader.gif" /></span>';
		//Result Paging, showing maximum 10 pages
		var totalPage = Math.round(ME.data.searchResult.totalResult/10);
		var pages = [];
		
		
		
		var i = ME.data.searchResult.startPage;
		var count = 0;
		for (i; i <= totalPage; i++) {
			var pageClass = '';
			var item = '';
			if (ME.data.searchResult.startPage == i) {
				pageClass = 'page-active';
				item = i;
			} else {
				item = '<a onclick="ME.search(\'' + ME.data.searchResult.query + '\', ' + i + '); return false;" href="#">' + i + '</a>';
			}
			pages.push('<li class="' + pageClass + '">' + item + '</li>');
			count++;
			if (count == 5) {
				// Just show maximum 5 pages
				break;
			}
			
		}
		
		count = 0;
		var currentPage = ME.data.searchResult.startPage;
		while (count <= 5 && currentPage > 1) {
			currentPage--;
			count++;
			
			var liItem = '<li><a onclick="ME.search(\'' + ME.data.searchResult.query + '\', ' + currentPage + '); return false;" href="#">' + currentPage + '</a></li>';
			
			pages.unshift(liItem);
		}
		
		
		if (ME.data.searchResult.startPage < totalPage) {
			pages.push('<li class="next"><a onclick="ME.search(\'' + ME.data.searchResult.query + '\', ' + (parseInt(ME.data.searchResult.startPage) + 1) + '); return false;" href="#">Next</a></li>');
		}
		
		if (ME.data.searchResult.startPage > 1) {
			pages.unshift('<li class="previous"><a onclick="ME.search(\'' + ME.data.searchResult.query + '\', ' + (ME.data.searchResult.startPage - 1) + '); return false;" href="#">Previous</a></li>');
		}
		
		// Add loading-bottom element
		pages.unshift(loadingBotEl);
		
		document.getElementById('me-paging').innerHTML = pages.join(' ');
	}
		
	// Adjust widow height, because of img latency loading, just wait for few seconds to adjust window height
	window.setTimeout(function() {
		ME.util.enableAjaxLoader(false);
		gadgets.window.adjustHeight();		
	}, 3000);

		
}



ME.search = function(keyword, page) {
	ME.util.enableAjaxLoader(true);
	if (page == 'undefined') {
		page = 1;
	}
	if (keyword != '') {
		// Encode
		ME.settings.queryString = keyword;
		
		keyword = keyword.replace(/ /g, '%20');		
		ME.settings.startPage = page;
		var url = ME.settings.searchURL + '?q=' + keyword + '&p=' + ME.settings.startPage + '&type=json';
		ME.makeJSONRequest(url);
	}
} 



/*
if (ME.view.currentView == 'canvas') {
	// Canvas staff here in
	
} else if (ME.view.currentView == 'profile' || ME.settings.view == 'home') {
	// Profile Staff here in
}

*/

// Some utility functions

function loadPeople() {
	//alert('load friend begin');
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest('OWNER'), 'owner');
	req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
	req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends');
	req.send(onLoadPeople);
}

function onLoadPeople(obj) {
	if (!obj.hadError()) {
		ME.data.owner = obj.get('owner');
		ME.data.viewer = obj.get('viewer');
		ME.data.viewerFriends = obj.get('viewerFriends');
	} else if (obj.hadError()) {
		alert('Error: ' + obj.getErrorMessage());
	} else {
		alert('Some fatal errors have occured!')
	}
}

/*BEGIN ME.playlist staff */

ME.playlist.list = []; // Keep array of songs in the playlist
ME.playlist.currentSong = ''; // current playing song

// Enum for playlist play mode
ME.playlist.NORMAL= 'normal';
ME.playlist.SONG_REPEAT_ONCE= 'song repeate once';
ME.playlist.PLAYLIST_REPEAT_ONCE = 'playlist repeat once';
ME.playlist.SHUFFLE = 'shuffle';
// Set default for the playlist
ME.playlist.currentMode = ME.playlist.NORMAL; // Can be set to shuffle, repeate song, repeate playlist, play at once

ME.playlist.setMode = function(mode) {
	if (mode != 'normal' || mode != 'random') {
		return
	}
	ME.playlist.currentMode = mode;
}

ME.playlist.add = function(song) {
	// Add song to list
	if (!ME.playlist.songExisted(song)) {
		Me.playlist.list.push(song);
	} else {
		// Song existed
	}
}

// Check the existed song in the list
ME.playlist.songExisted = function(song) {
	var list = ME.playlist.list;
	var length = list.length;
	for (var i = 0; i < length; i++) {
		if (list[i] == song) {
			return true;
		}
	}
	return false;
}

ME.playlist.remove = function(song) {
	// Remove song from list
	if (ME.playlist.songExisted(song)) {
		// Remove from the list now
	} else {
		// No such song in the list
	}
}

ME.playlist.download = function(song) {
	// Download song, open a download dialog
	
}

ME.playlist.prev = function() {
	// Play previous song
}

ME.playlist.next = function() {
	// Play next song
}

ME.playlist.pause = function() {
	// Pause the playing song
}

ME.playlist.stop = function() {
	// Stop the playing song
}


/*END ME.playlist staff */





// Displaying Staff here, for canvas view
ME.tab = {};
ME.tab.tabs = null;

ME.tab.init = function() {
	ME.tab.tabs = new gadgets.TabSet(null, document.getElementById('me-search-tab'), document.getElementById('me-tabs'));
    var params = {
      callback: ME.tab.changeSelectedTab
    };
    
    params.contentContainer = document.getElementById("me-search-tab");
    ME.tab.tabs.addTab("Search", params);
    
    params.contentContainer = document.getElementById("me-song-tab");
    ME.tab.tabs.addTab("Song Detail", params);
    
    params.contentContainer = document.getElementById('me-playlist-tab');
    ME.tab.tabs.addTab("Playlist", params);
  
    params.contentContainer = document.getElementById('me-help-tab');
    ME.tab.tabs.addTab("Help", params);
    
    params.contentContainer = document.getElementById('me-about-tab');
    ME.tab.tabs.addTab("About", params);
    
    ME.tab.tabs.alignTabs("left", 10);
    // choose the first tab
    ME.tab.selectTab(ME.tab.SEARCH);

}

/*Enum Tab*/

ME.tab.SEARCH = 0;
ME.tab.SONG = 1;
ME.tab.PLAY_LIST = 2;
ME.tab.HELP = 3;
ME.tab.ABOUT = 4;

ME.tab.changeSelectedTab = function(tabId) {
	ME.tab.selectedTab = ME.tab.tabs.getSelectedTab();
	var index = ME.tab.selectedTab.getIndex();
	// Adjust window height when tab changed
	// Adjust widow height, because of some latency loading, just wait for few seconds to adjust window height
	window.setTimeout(function() {
		gadgets.window.adjustHeight();
	}, 3000);
	switch (index) {
	case ME.tab.SEARCH:
		//alert('search selected');		
		break;
	case ME.tab.SONG:
		//alert('song');
		break;
	case ME.tab.PLAY_LIST:
		//alert('playlist');
		break;
	case ME.tab.HELP:
		//alert('help');
		break;
	case ME.tab.ABOUT:
		//alert('about');
		break;
		
	default:
		// Uncaught
		break;
	}
}
// select tab by tab-index
ME.tab.selectTab = function(id) {
	ME.tab.tabs.setSelectedTab(id);
}






// Music Engine Initialization
function init() {
	// Some configuration here
	ME.tab.init();
	ME.view.currentView = gadgets.views.getCurrentView().getName();
	loadPeople();
	ME.searchbox.init();
	// hide loading element
	document.getElementById('app-loading').style.display = 'none';
}

ME.util = {};

ME.util.showMsg = function(msg, elId) {
	var el = document.getElementById(elId);
	el.innerHTML = msg;
}

ME.util.clearMsg = function(elId) {
	var el = document.getElementById(elId);
	el.innerHTML = '';
}

ME.util.enableAjaxLoader = function(isShown) {
	var loadingTopEl = document.getElementById('loading-top');
	var loadingBotEl = document.getElementById('loading-bottom');
	if (isShown) {
		if (elementExisted(loadingTopEl)) {
			loadingTopEl.style.visibility = 'visible';
		}
		if (elementExisted(loadingBotEl)) {
			loadingBotEl.style.visibility = 'visible';
		}
		
	} else {
		if (elementExisted(loadingTopEl)) {
			loadingTopEl.style.visibility = 'hidden';
		}
		if (elementExisted(loadingBotEl)) {
			loadingBotEl.style.visibility = 'hidden';
		}
	}
	
	function elementExisted(el) {
		if (!el) {
			return false;
		}
		return true;
	}
}

ME.util.unimplemented = function() {
	var iDialog = ZWDialog;
	//iDialog.windowid = ME.dialogBox.PREVIEW;
	if (ZWWin.winIdExisted(10)) {
		ZWWin.removeElementByWinId(10);
	}
	iDialog.Alert(10, '<div align="center">This feature will be implemented soon!</div>', 'Info: Unimplemented', 350, 150, 60, 80);
}

gadgets.util.registerOnLoadHandler(init); 


