﻿// JScript File
var MyMusic = new MusicManager();

// Music Manager
function MusicManager(){}
MusicManager.prototype.Listen = __ListenIt;
MusicManager.prototype.Downloads = new DownloadManager;
MusicManager.prototype.Navigator = new Navigator();
MusicManager.prototype.Search = _search;
MusicManager.prototype.Help = _toggleHelp;
MusicManager.prototype.EnablePageAction = _showGray;
MusicManager.prototype.ConfirmationButton = null;
MusicManager.prototype._CookieName = 'MusicAlerts';
MusicManager.prototype.IsAlertDisabled = _IsAlertDisabled;

// Download Manager
function DownloadManager(){}
DownloadManager.prototype.Get = __g2;
DownloadManager.prototype.Add = __addSongConfirmation;
DownloadManager.prototype.AddAlbum = __addAlbumConfirmation;
DownloadManager.prototype.Remove = __removeSong;
DownloadManager.prototype.AddAll = __AddRange;
DownloadManager.prototype._ItemCount = null;
DownloadManager.prototype._Action = null;

function Navigator(){this.Pager	= null;}
Navigator.prototype.__Move = navigator_move;
Navigator.prototype.Forward = navigator_move_forward;
Navigator.prototype.Backward = navigator_move_backward;
Navigator.prototype.Direction = {backward:0, forward:1};

document.onkeydown = handle_keydown;

// Global Variables
var __x			 = null;
var __inprogress = 0;
var __target	 = null;

function _search(queryField, musicTypeField)
{
	var q = findObj(queryField);
	var m = findObj(musicTypeField);
			
	if(q.value.length < 2)
	{
		alert(validation_message);
		q.focus();
	}
	else
	{
		var url = '/music/search.aspx?q={0}&music={1}'.Format(q.value, m.value);
		document.location.href = url;
	}
}

function _toggleHelp()
{
	var args = _toggleHelp.arguments;
	if(args.length > 0)
	{
		var caller = args[0].getElementsByTagName('b')[0];
		var src = findObj(args[1]);	
		
		src.style.display = (src.style.display == 'none' ? '' : 'none');	
		caller.innerHTML = (src.style.display == 'none' ? 'Εμφάνιση βοήθειας' : 'Απόκρυψη βοήθειας');
		args[0].title = caller.innerHTML;
		
		document.forms[0].action = document.location.href;
		_saveSettingsCaller("display:" + src.style.display, Math.random());
	}
}

function __g2(caller, num)
{
    var hidden = findObj(rq);
    if(hidden)hidden.value = num;
}

// Disable Delete
function __disableDelete(caller)
{
	var inp = caller.parentNode.getElementsByTagName('input');
	var del = inp[inp.length - 1];
	
	if(del.src.toLowerCase().endsWith('delete.gif'))
	{		
		var img = new Image(); 
		img.src = '/images/NewMusic/delete_inactive.gif';
		img.title = 'Το τραγούδι δεν μπορεί να αφαιρεθεί από το μουσικό καλάθι σας επειδή το έχετε ήδη κατεβάσει.';		
		img.width = 24;
		img.height = 18;
		del.parentNode.replaceChild(img, del);	
	}		
}

// Open Song Listener
function __ListenIt(id)
{
    var args = __ListenIt.arguments;
    var parameter = (args.length > 1 && args[1] == 'album' ? 'albumId' : 'songId');
	var _opt = 'top=50,left=200,width=300,height=250,status=yes,resizable=no';
	var nw = window.open('/music/listen.aspx?' + parameter + '=' + id + 
	'&referrer=' + escape(document.location.href), 'Listener', _opt);
	nw.focus();
}

//function swap_tab(caller, tab, container, tabIndex, tabStrip)
function swap_tab(tabStrip, tabIndex)
{	
	if(!__inprogress)	
	{
		// Set Ids
		var tabs = eval(tabStrip);
		tab = findObj(tabs.tabs[tabIndex]);
		container = findObj(tabs.containers[tabIndex]);
						
		// Mark that an action is in progress		
		__inprogress = true;
								
		if(tab.getAttribute('loaded') != 'true')
		{	
			// Disable tab change								
			tabs.status = tabs.statusType.pending;
			
			__x = new XmlHttpRequest();
			
			var pf = (location.hostname.indexOf('10.1.1.') > -1 ? 'Viva/' : '');
			__x.url = location.protocol + '//' + location.hostname + '/' + pf + 'XmlCallback/NewMusic.aspx';
			__x.parameters = 'tab=' + tabIndex;
			__x.caller = tab;
		    __x.requestResponse = __tabLoader;
		    __x.target = container;
		    __x.onComplete = "var t = eval('" + tabStrip + "'); t.status = t.statusType.ready;"
		    __x.setLoader();
		    __x.create();
		}						
	}	
}

// Tab Loader
function __tabLoader()
{	
	if(__x.request && __x.request.readyState == 4)
	{		
		var xml  = __x.request.responseXML;
		var node = null;
		
		if(__x.onComplete.length > 0)
		    eval(__x.onComplete);
		
		__x.target.innerHTML = getNodeText(xml, 'data');				
		__inprogress = 0;
		__x.caller.setAttribute('loaded', 'true');
	}
}

// Get Text
function getNodeText(xml, xPath)
{
	var text = '';
	if(isOpera)
	{
		var nodes = xml.getElementsByTagName(xPath);
		if(nodes.length > 0)
			text = nodes[0].firstChild.nodeValue;		
	}
	else
	{
		var node = xml.selectSingleNode('//' + xPath);		
		text = isIE ? node.text : node.textContent;
	}
	return __getText(text);
}

// Remove Song
function __removeSong(caller, item)
{
	caller.disabled = true;
	
	var x = null;
	
	var tr = caller.parentNode.parentNode;
	for(var i = 0; i < tr.cells.length - 1; i++)
		tr.cells[i].style.textDecoration = 'line-through';
	
	document.body.style.cursor = 'wait';								
	x = new XmlHttpRequest();
	x.url = MyViva.get_baseUrl() + '/XmlCallback/actions.aspx';
	x.parameters = 'p=' + escape(item);		
	x.requestResponse = _response;
	x.create();		
					
	// Get resposne and inform user
	function _response()
	{
		if(x.request && x.request.readyState == 4)
		{			
			document.body.style.cursor = '';
			handle_delete_response(caller, x.request.responseXML);		
		}
	}
	return(false);
}

function handle_delete_response(caller, xml)
{
	var node = (isOpera ? xml.getElementsByTagName('result')[0] : xml.selectSingleNode('//result'));	
	if(node)
	{
		var _r = parseInt(node.firstChild.nodeValue);
		switch(_r)
		{
			// Invalid User
		    case 1:
		        document.location.href = MyViva.get_baseUrl() + '/Alert.aspx?alert=' + _r + '&returnUrl=' + escape(MyViva.get_returnUrl());
		        break;
		        
		    case 2:
		        document.location.href = MyViva.get_baseUrl() + '/MyViva/BuyPoints.aspx?alert=1';
		        break;
		        
			case 3: // Everything is ok			
				var tr = caller.parentNode.parentNode;
				var table = tr.parentNode;
				table.deleteRow(tr.rowIndex);
				var rows = table.rows.length - 1;
				
				// Decrease
				__updateMusicBox(-1);
			if(rows < 1)
					document.location.reload();
				break;
				
			default: // Unexpected error
				document.location.href = MyViva.get_baseUrl() + '/ErrorPage.aspx?err=5&returnUrl=' + escape(MyViva.get_returnUrl());
				break;
		}
	}
	else
		document.location.href = MyViva.get_baseUrl() + '/ErrorPage.aspx?err=5&returnUrl=' + escape(MyViva.get_returnUrl());
}


// Get text
function __getText(text){var s = document.createElement('div');	s.innerHTML = text;	return s.getElementsByTagName('div')[1].innerHTML; }

// Update Music Box
function __updateMusicBox()
{	
	var arg = 1;
	
	if(__updateMusicBox.arguments.length == 1 && !isNaN(__updateMusicBox.arguments[0]))
		arg = parseInt(__updateMusicBox.arguments[0]);

	var mbox = findObj('MusicBoxCount');
	var c = mbox.innerHTML.replace(/[(]|[)]/gi, '');
	
	if(parseInt(c) + arg < 1)
		arg = 0;

	mbox.parentNode.title = mbox.parentNode.title.replace(c, parseInt(c) + arg);
	mbox.innerHTML = '({0})'.Format(parseInt(c) + arg);

	MyViva.updatePoints();
}

function __addSongConfirmation(caller, item)
{
    if ($get(MyMusic.ConfirmationButton).checked)
        setCookie(MyMusic._CookieName, '1');
    
    var popup = $find('MusicConfirmationButton');
    var label = $get('MusicConfirmationText');

    var price = parseFloat(caller.getAttribute('price'));
    label.innerHTML = 'Έχετε επιλέξει να<br />αγοράσετε <b>1</b> τραγούδι αξίας <b>{0} points</b>'.Format(price.toLocaleString());

    if (MyMusic.IsAlertDisabled())
    {
        MyMusic.EnablePageAction(false);
        __addSong(caller, item);
    }
    else
    {
        popup.set_OnOkScript(function() { __addSong(caller, item); });
        popup.show();
    }
}

function _IsAlertDisabled(){return (getCookie(MyMusic._CookieName) == '1');}

function _showGray(enable)
{
    var gray = $find('MusicGray');
    if(gray != null)
    {
        // Change div background
        gray.set_BackgroundCssClass('modalBackground');
        
        if (!enable)
            gray.show();
        else
            gray.hide();
    }
}

// Add Song to users music box
function __addSong(caller, item)
{			
	var x = null;
	// Request new add
	if(caller.getAttribute('added') != 'true')
	{		
		document.body.style.cursor = 'wait';
		
		x = new XmlHttpRequest();		
		x.url = MyViva.get_baseUrl() + '/XmlCallback/actions.aspx';
		x.parameters = 'p={0}&r={1}&c={2}'.Format(escape(item), escape(MyViva.get_returnUrl()), escape(caller.id));
		
		MyMusic.Downloads._Action = 'Song';
		
		x.requestResponse = _response;
		x.create();
		
		if(typeof(invalidate) != 'undefined')
			findObj(invalidate).value = 1;
	}
	// Get resposne and inform user
	function _response()
	{
		if(x.request && x.request.readyState == 4)
		{			
			document.body.style.cursor = '';
			__readResposne(caller, x.request.responseXML);
		}
	}
}

function __addAlbumConfirmation(caller, args)
{
    var popup = $find('MusicConfirmationButton');
    var label = $get('MusicConfirmationText');

    var price = parseFloat(caller.getAttribute('price'));
    label.innerHTML = 'Έχετε επιλέξει να<br />αγοράσετε <b>1</b> album αξίας <b>{0} points</b>'.Format(price.toLocaleString());

    popup.set_OnOkScript(function() { __AddAlbum(caller, args); });
    popup.show();
}

function __AddAlbum(caller, args)
{
    var x = null;
    // Request new add
    if (caller.getAttribute('added') != 'true')
    {
        document.body.style.cursor = 'wait';
        x = new XmlHttpRequest();
        x.url = MyViva.get_baseUrl() + '/XmlCallback/actions.aspx';
        x.parameters = 'p={0}&r={1}&c={2}'.Format(escape(args), escape(MyViva.get_returnUrl()), escape(caller.id));
        MyMusic.Downloads._Action = 'Album';
        x.requestResponse = _response;
        x.create();

        if (typeof (invalidate) != 'undefined')
            findObj(invalidate).value = 1;
    }
    // Get resposne and inform user
    function _response()
    {
        if (x.request && x.request.readyState == 4)
        {
            document.body.style.cursor = '';
            __readResposne(caller, x.request.responseXML);
        }
    }
}

function __delayedAdd(caller, key)
{	
	var obj = findObj(caller);
	if(obj && !obj.src.toLowerCase().endsWith('inactive.gif'))
		MyMusic.Downloads.Add(obj, key);
}

// Manage response
function __readResposne(caller, xml)
{
    var node = (isOpera ? xml.getElementsByTagName('result')[0] : xml.selectSingleNode('//result'));
	
	if(node != null)
	{
	    var _r = parseInt(node.firstChild.nodeValue);
		switch(_r)
		{
			// Invalid User
		    case 1:
		        document.location.href = MyViva.get_baseUrl() + '/Alert.aspx?alert=' + _r + '&returnUrl=' + escape(MyViva.get_returnUrl());
		        break;
		        
			case 2:
			    document.location.href = MyViva.get_baseUrl() + '/MyViva/BuyPoints.aspx?alert=1';
			    break;
				
			case 3: // Everything is ok

                // Enable page click
			    MyMusic.EnablePageAction(true);
			
			    // begin
				begin_fade(caller);
				//return;
				
				var count = (isOpera ? xml.getElementsByTagName('itemCount')[0] : xml.selectSingleNode('//itemCount'));
				var itemCount = parseInt(count.firstChild.nodeValue);
				
				if(isNaN(itemCount))
				    itemCount = 0;

				MyMusic.Downloads._ItemCount = itemCount;
				
				__makeInactive(caller);
				break;
			default: // Unexpected error
				document.location.href = MyViva.get_baseUrl() + '/ErrorPage.aspx?err=5&returnUrl=' + escape(MyViva.get_returnUrl());
				break;
		}
	}				 
	else // Unexpected error
		document.location.href = MyViva.get_baseUrl() + '/ErrorPage.aspx?err=5&returnUrl=' + escape(MyViva.get_returnUrl());
}

function __makeInactive(caller)
{
    caller.className = 'nmbuy_inactive';

    caller.setAttribute('added', 'true');
    caller.style.cursor = 'default';
    caller.onclick = new Function("return(false);");

    var tooltip = caller.getAttribute('tooltip');
    caller.title = (tooltip ? tooltip : '');
}

// Get offset top of an object
function get_offset(obj)
{
	obj.style.position = 'relative';
	var offset = obj.offsetTop;
	obj.style.position = '';		
	return offset;
}

// Get Offset Left
function __getLeft()
{
	var d = $('a[id$=LoginBox_Music]:first');
	var v = ($(d).offset().left + $(d).width());
	return v;
}

function begin_fade(caller)
{
	
	// Find Container Row
	var in_index = false;
	var tag = caller.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;	
	if(tag.tagName == 'DIV') {in_index = true; tag = caller.parentNode.parentNode;}
	
	// Find Container Table
	var mynode = caller.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;	
	if(in_index) mynode = caller.parentNode.parentNode.parentNode.parentNode;
	
	// Row Index
	var index = caller.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.rowIndex;
	if(in_index) index = tag.rowIndex;
	
	with(mynode)
	{
		setAttribute('nomover', '1');
		style.background = '#f1f1f1';
	}
	
	__appendTop = index * 26;
	
	// Clone row
	var t = tag.cloneNode(true);	
	t = tag.parentNode.parentNode;
	
	// Create fader
	var div = document.createElement("div");
	with(div)
	{
		t.style.position = 'relative';		
		style.top = ((t.offsetTop + __appendTop) - 6) + 'px';
		
		style.left = t.offsetLeft + 'px';
		// Create a unique name for the fader
		id = '__fader' + Math.random().toString().substring(2) ;
		style.height = '26px';
		style.width = t.offsetWidth + 'px';
		if(isIE)
			style.filter = 'alpha(opacity=60)';
		else
			style.MozOpacity = 0.6;
		style.border = '1px solid #BFBFBF';
		
		style.position = 'absolute';		
		style.zIndex = 100;	
		
		// Set inner content
		innerHTML = '<table width="100%" cellspacing="0" cellpadding="0" style="font: 10px Verdana;"><tr>' + 
					tag.innerHTML + '</tr></table>';
	}	
	
	// Add div to document	
	document.body.appendChild(div);
	
	// Start fading
	setTimeout("__dec('" + div.id + "')", 30);							
}

var __count		= 0;
var __maxLeft	= null;
var __appendTop	= null;
var __topStep	= 25;
var __leftStep	= 35;

function __dec(faderId)
{
	// Get Object
	var div = findObj(faderId);
	if(div)
	{
		__count++;
		
		// Calculate offset left	
		__maxLeft = __getLeft();
					
		// Calculate steps
		if(__count == 1)
		{		 
			var target = div.offsetTop - 100;		
			var index = Math.ceil(((__appendTop / 26) + 1) - 2); //* 2;
			
			__topStep = __topStep + index;
			__leftStep = __leftStep - index;
			if(location.href.toLowerCase().indexOf('search.aspx') > -1)
				__leftStep += parseInt(__leftStep / 3); // Increase step 
		}
		
		// Reposition div
		// with(div)	
		//{
		div.style.top = (parseInt(div.style.top) - __topStep) + 'px';
		div.style.width = (parseInt(div.offsetWidth) - __leftStep) + 'px';
		if(parseInt(div.style.width) < 160)
			div.style.width = '160px';
		//alert('Step: {2} ---- Offset: {0} - Width: {1}'.Format(div.offsetWidth, div.style.width, __leftStep));
		div.style.left = (__maxLeft - parseInt(div.offsetWidth) + 'px');
		//}
		
		// Restore	
		if(parseInt(div.style.top) < 110)
		{
			// Re initialize 
			__topStep	= 25;
			__leftStep	= 35;
			__count = 0;
			// Remove fader
			document.body.removeChild(div);
			
			// Update item count
			var count = MyMusic.Downloads._ItemCount;
			if(isNaN(count))
			    count = 0;

			__updateMusicBox(count);
			
			if(MyMusic.Downloads._Action == 'Album')
			{
			    var input = document.getElementsByTagName('input');
			    var buttons = new Array();

			    for (var i = 0; i < input.length; i++) {
			        if (input[i].type == 'button'
	                    && input[i].className == 'nmbuy' && input[i].getAttribute('_ev') != null) {
			            __makeInactive(input[i]);
			        }
			    }
			}
		}
		else // redo
			setTimeout("__dec('" + faderId + "')", 30);
	}
}


function handle_keydown(e)
{	
	var ns6 = (!document.all && document.getElementById);
	var key = (ns6 ? e.keyCode : event.keyCode);	
	if(!ns6) e = event;
	
	if(e.ctrlKey && e.altKey && key == 68)
		MyMusic.Downloads.AddAll();
	else if(e.altKey && (key == 78 || key == 80))
	{		
		if(key == 78)
			MyMusic.Navigator.Forward();
		else if(key == 80)
			MyMusic.Navigator.Backward();		
	}
	else if(key == 27)
	{
	    var p = $find('MusicConfirmationButton');
	    if (p != null)
	        p.hide();
	}
}

function navigator_move_forward(){this.__Move(this.Direction.forward);}
function navigator_move_backward(){this.__Move(this.Direction.backward);}

function navigator_move(direction)
{		
	var pager = null;
	if(this.Pager.length > 0 && (pager = findObj(this.Pager)))
	{
		var links = pager.getElementsByTagName('a');
		var link = null; var url = '';
		for(var i = 0; i < links.length; i++)
		{
			link = links[i];
			if(direction == this.Direction.backward 
					&& link.getAttribute('prevpage') == 'true')
			{
				url = link.toString();
				break;
			}
			else if(direction == this.Direction.forward
				&& link.getAttribute('nextpage') == 'true')
			{
				url = link.toString();
				break;
			}
		}
		if(url.length > 0)
			document.location.href = url;
	}
}

var storage = null;

function __AddRange()
{
	var input = document.getElementsByTagName('input');
	var buttons = new Array();
	
	for(var i = 0; i < input.length; i++)
	{
	    if (input[i].type == 'button'
	        && input[i].className == 'nmbuy' && input[i].getAttribute('_ev') != null)
	    {
	        buttons.push(input[i]);
	    }
	}

	storage = buttons;
	_begin();
}

function _begin()
{
	if(storage.length > 0)
	{
		var button = storage.shift();
		button.click();
		
//		if(button.onclick.toString().contains('MyMusic') > -1)
//		{
//			var click = button.onclick.toString();		
//			click = click.replace('function onclick(event) {', '');
//			click = click.replace('function anonymous()', ''); click = click.replace('{', ''); click = click.replace('}', '');
//			click = click.replace('return(false);', '');
//			click = click.replace('return (false);', '');
//			click = click.replace('this', "findObj('" + item + "')");			
//			eval(click);		
//		}

		setTimeout("_begin()", 100);
	}
}
