// FLASH USED VARIABLES ########################################################
var lcId=new Date().getTime();
var proxyLcId=lcId;
var resources_url='/resources/';
// flashBaseUrl='/playlive/flash/'; FIXME not used
var useVBS=(navigator.appName && navigator.appName.indexOf("Microsoft")!=-1 && navigator.userAgent.indexOf("Windows")!=-1 && navigator.userAgent.indexOf("Windows 3.1")==-1);
var isSafari=navigator.appName && navigator.appName.indexOf("Safari")!=-1
var externPlayerURL = "/playlive/flash/player/extern/"
//var externPlayerURL = "/flash/player/extern/"

// DOM Builders: add flash into HTML page ######################################
function FLASH_writeMiniplayer(alternate, json_func, nbTracks, background_color)
{
  if(isSafari){
    var h=95+(nbTracks*40)+27;
  } else {
    var h=95+((nbTracks-1)*22)+40+27;
  }
  var myLcId = alternate+"_"+lcId;
  var htmlId="swfId_"+myLcId;
  var mp=new SWFObject(resources_url+"flash/miniplayer.swf?nocache="+myLcId,htmlId,270,270,"7",background_color);
  // CONFIG
  mp.addVariable("htmlId",htmlId);
  mp.addVariable("json_func",json_func);
  // IE Hook
  if (useVBS)
    {
      document.write('<script language=\"VBScript\"\>\n');
      document.write('On Error Resume Next\n');
      document.write('Sub '+htmlId+'_FSCommand(ByVal command, ByVal args)\n');
      document.write('Call doFSCommand(command, args)\n');
      document.write('End Sub\n');
      document.write('</script\>\n');
    }
  mp.write(alternate);
}

function FLASH_writeMeloPlayer(alternate, json_func, background_color)
{
  var myLcId = alternate +"_"+lcId;
  var htmlId="swfId_"+myLcId;
  var mp=new SWFObject(resources_url+"flash/melooplayer.swf?nocache="+myLcId,htmlId,270,200,"7",background_color);
  // CONFIG
  mp.addVariable("htmlId",htmlId);
  mp.addVariable("json_func",json_func);
  // IE Hook
  if (useVBS)
    {
      document.write('<script language=\"VBScript\"\>\n');
      document.write('On Error Resume Next\n');
      document.write('Sub '+htmlId+'_FSCommand(ByVal command, ByVal args)\n');
      document.write('Call doFSCommand(command, args)\n');
      document.write('End Sub\n');
      document.write('</script\>\n');
    }
  mp.write(alternate);
}

function FLASH_writeMicroplayer(alternate, json_func, width, background_color, ajaxCall)
{
  if (!ajaxCall) ajaxCall = 't'; // default : ajaxCall is true
  var myLcId=++lcId;
  var htmlId="swfId_"+myLcId;
  var mp=new SWFObject(resources_url+"flash/microplayer.swf?nocache="+myLcId,htmlId,width,17,"7",background_color);
  // CONFIG
  mp.addVariable("htmlId",htmlId);
  mp.addVariable("json_func",json_func);
  // IE Hook
  if ((ajaxCall!='t') && useVBS)
    {
      document.write('<script language=\"VBScript\"\>\n');
      document.write('On Error Resume Next\n');
      document.write('Sub '+htmlId+'_FSCommand(ByVal command, ByVal args)\n');
      document.write('Call doFSCommand(command, args)\n');
      document.write('End Sub\n');
      document.write('</script\>\n');
    }
  mp.write(alternate);
}

// JAVASCRIPT FUNCTIONS CALLED FROM ADOBE FLASH ################################

// for external player
function open_player(flashvars){
  var height = 520;
  var width = 830;
  var top = (window.screen.height-height)/2;
  var left  = (window.screen.width-width)/2;
  var url = externPlayerURL+ "?width="+790+"&height="+495;
  if (flashvars)
    url += "&"+ flashvars;
  window.open(url, 'player_externe', 'toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1,width='+width+',height='+height+',left='+left+',top='+top);
}

function load_into_opener(url){
  // must be called from player window
  if (!window.opener){
      open(url, 'main_page');
  }
  window.opener.location = url;
}

function focus_window(){
  // must be called from external player window
  window.focus();
}

/* function focus_player(){ */
/*   // must NOT be called from player */
/*   window.open('', 'player_externe').focus(); */
/* } */

// Handler on Ajax requests initiated by flash
function flash_handler(sentContent) {
  return function(type, res, evt) {
    if (type =='error') {
      if (evt.status==403){
	document.location = evt.responseText;}
      else if (evt.status==500){
	document.write(evt.responseText);}
      else{
	alert(res.message);}
    } else {
      toggle_cursor(true, "flash request completed");
    }
  }
}

// Flash FSCommand calls managment (IE only)
function doFSCommand(command,args)
{
	var o;
	if(typeof args=='string')
	{
		var subArgs=unescape(args);
		o=subArgs.parseJSON();
	}
	else if(command)
	{
		o=args;
	}
	eval(command)(o);
}

function FLASH_swap(o)
{
    switch (o.action) {
      case 'view_comments':
      case 'view_track_detail_page' :
	swap_ajax('ajax-body', 'Song', o.song_id, 'body');
	break;
      case 'view_all_tracks_page' :
	swap_ajax('ajax-body', 'Band', o.band_id, 'body_songs');
	break;
      case 'write_comment' :
        open_dialog('/post-comment/validate/'+o.object_type+'/'+o.object_id+'/'+o.referer_type+'/'+o.referer_id+'/mini/', {'action':'send'});
	break;
      default:
	var out='';
	for(var i in o)
	{
		out+="---> "+i+" ::: "+o[i]+"\n";
		for(var ii in o[i])
			out+="\t\t"+ii+" ::: "+o[i][ii]+"\n";
	}
	alert(o['action']+"\n"+out);
    }
}

function FLASH_resize(o)
{
  var itm=document.getElementById(o.htmlId);
  itm.height=o.h;
}

function FLASH_vote(o)
{
  dojo.io.bind({url: flash_url + '/player/vote/',
		handler: flash_handler(),
		content: {'song_id': o.song_id, 'note': o.note, 'user_id': o.user_id},
		method: 'post'});
}

function FLASH_listened(o)
{
  dojo.io.bind({url: flash_url + '/player/listened/',
		handler: flash_handler(),
		content: {'song_id': o.song_id, 'full': o.full, 'user_id': o.user_id},
		method: 'post'});
}

function FLASH_openWin( args )
{
	if( typeof args == 'string' )
		args = unescape(args).parseJSON ();
	else if ( args.url == undefined )
		return;

	var $fp=window.open(
		args.url,
		(args.winName==void(0)) ? "pop_"+new Date().getTime() : args.winName
	);
}

// JSON ########################################################################

/***
	object.toJSONString()
	This method produces a JSON text from an object. The
	object must not contain any cyclic al references.

	array.toJSONString()
	This method produces a JSON text from an array. The
	array must not contain any cyclical references.

	string.parseJSON()
	This method parses a JSON text to produce an object or
	array. It will return false if there is an error.

*/

(
	function ()
	{
		var m={'\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'},
		s ={
			array: function (x)
			{
				var a = ['['], b, f, i, l = x.length, v;
				for (i = 0; i < l; i += 1)
				{
					v = x[i];
					f = s[typeof v];
					if (f)
					{
						v = f(v);
						if (typeof v == 'string')
						{
							if (b)
							{
								a[a.length] = ',';
							}
							a[a.length] = v;
							b = true;
						}
					}
				}
				a[a.length] = ']';
				return a.join('');
			},
			'boolean': function (x)
			{
				return String(x);
			},
			'null': function (x)
			{
				return "null";
			},
			number: function (x)
			{
				return isFinite(x) ? String(x) : 'null';
			},
			object: function (x)
			{
				if (x)
				{
					if (x instanceof Array)
					{
						return s.array(x);
					}
					var a = ['{'], b, f, i, v;
					for (i in x)
					{
						v = x[i];
						f = s[typeof v];
						if (f)
						{
							v = f(v);
							if (typeof v == 'string')
							{
								if (b)
								{
									a[a.length] = ',';
								}
								a.push(s.string(i), ':', v);
								b = true;
							}
						}
					}
					a[a.length] = '}';
					return a.join('');
				}
				return 'null';
			},
			string: function (x)
			{
				if (/["\\\x00-\x1f]/.test(x))
				{
					x = x.replace(/([\x00-\x1f\\"])/g, function(a, b)
															{
																var c = m[b];
																if (c)
																{
																	return c;
																}
																c = b.charCodeAt();
																return '\\u00' + Math.floor(c / 16).toString(16)+(c % 16).toString(16);
															}
														);
				}
				return '"' + x + '"';
			}
		};

		Object.prototype.toJSONString = function ()
		{
			return s.object(this);
		};

		Array.prototype.toJSONString=function()
		{
			return s.array(this);
		};
	}
)();

String.prototype.parseJSON=function()
{
	try
	{
		return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(this.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + this + ')');
	}
	catch (e)
	{
		return false;
	}
};

