//Voor het geval er ook andere initialisaties gedaan moeten worden

function pageInit() {
	if ( document.getElementById( 'progress_container' ) ){
		checkQueue(0,false);
	}
}

var retry_counter = 0;
var prev_progress = -1;
var timeout_poller = 2000;

var lastPollTimeout = null;
var checkQueueRequester = null;
var checkQueueRequesterTime = null;
var checkQueueMusicPlaying = [];

function requestCheckQueue( time, cleanup, scrollTo ){
	var currentTime = new Date();

	if ( ! time ){
		if ( lastPollTimeout != null ){
			time = lastPollTimeout;
		} else {
			tiem = timeout_poller;
		}
	}
	time = time ? time : timeout_poller;
	cleanup = cleanup ? cleanup : 0;
	scrollTo = scrollTo ? scrollTo : false;
	lastPollTimeout = time;

	if ( checkQueueRequesterTime != null ){
		// De nieuwe check is later dan de reeds geplande
		if ( currentTime.getTime() + time > checkQueueRequesterTime ){
			return true;
		}
	}

	checkQueueRequesterTime = currentTime.getTime() + time;

	checkQueueRequester = setTimeout(
		function(){
			checkQueue( cleanup, scrollTo );
		}, 
		time 
	);

}

function checkQueue(cleanup, scrollTo)
{
		// Reset timeout & time
		clearTimeout( checkQueueRequester );
		checkQueueRequester = null;
		checkQueueRequesterTime = null; 

		if (isNaN(scrollTo) || scrollTo)
		{
			$('html').animate({scrollTop: '-=' + $('html').scrollTop() + 'px'}, 1000);
			$('body').animate({scrollTop: '-=' + $('body').scrollTop() + 'px'}, 1000);			
		}

		if (retry_counter++ > (10 * 60 * 1000 / timeout_poller)) // 10 minutes for firmware upgrade on a slow PC without driver
		{
				// Stop polling.. Perhaps warn the user?
		}
		else
		{
		var url = '../swinxs/checkQueue.php';
		var arguments = {
			cleanup: cleanup
		};

		var music = [];
		for( var j in checkQueueMusicPlaying ){
			music.push( j );
		}
		if ( music.length > 0 ){
			arguments.checkPlay = music.join( ',' );
		}

		jQuery.getJSON( 
			url,
			arguments,
			processResponse
		);
	}
}

var lastKnownAction = null;

function processResponse(responseQueue)
{

		if (responseQueue == null) 
		{
				setTimeout('checkQueue(0, false)', timeout_poller);
				return;
		}

		if ( prev_progress != responseQueue.progress ) 
		{
				// Progress changed, so we'll start polling again.
				retry_counter = 0;
				prev_progress = responseQueue.progress;
		}

		if ( responseQueue.action ){
			lastKnownAction = responseQueue.action;
		}

		if ( responseQueue.playing ){
			for ( var music_id in checkQueueMusicPlaying ){
				if ( responseQueue.playing[ music_id ] == false ){
					checkQueueMusicPlaying[ music_id ].callback();
					delete checkQueueMusicPlaying[ music_id ];
				}
			}
		}

		if (responseQueue.running == 0)
		{
			 // We're done -- remove progress bar
			removeProgressBar();

			switch( lastKnownAction ){
				case 'ADD_PERS_XS' : case 'DELETE_PERS_XS' : {	
					UpdatePersonalPage_XSTags();
				} break;
			
				case 'DOWNLOAD_GAME' : case 'UPDATE_GAME' : case 'DELETE_GAME' : {
					UpdatePersonalPage_Games();
				} break;

				case 'ADD_MUSIC' : case 'DELETE_MUSIC' : {
          UpdatePersonalPage_Music();
        } break;
			}

			lastKnownAction = null;

			requestCheckQueue( 6000 );
		}
		else if (responseQueue.status == 'SUCCESS')
		{

				createProgressBar();

				document.getElementById('queueProgress').style.width = "290px";
				document.getElementById('queueMessage').innerHTML = "Finished " + responseQueue.message + ".";

				requestCheckQueue( timeout_poller, 1 );
		}
		else if (responseQueue.status != 'IN_PROGRESS')
		{
				// To do: make sure we get failure status (not working currently)
				$("#unsuccesful").hide();
				ajaxCall("../swinxs/deleteunsuccesful.php?",function() {},1,0,0);

				createProgressBar();

				document.getElementById('queueMessage').innerHTML = "Error " + responseQueue.message + ".";

				requestCheckQueue( timeout_poller, 1 );
		}
		else
		{
				createProgressBar();

				document.getElementById('queueProgress').style.width = 2 + Math.round(responseQueue.progress/100 * 288) + "px";   
				document.getElementById('queueMessage').innerHTML = "Busy " + responseQueue.message + "... " + responseQueue.progress + "%";

				if ( responseQueue.action == 'INSTALL_FIRMWARE' ){
						if ( responseQueue.progress >= 80 ){
							if ( responseQueue.progress < 90 ){
								// show
								ajaxCall ('../swinxs/flashwarning.php?', function( response ){ 
									var warning = document.getElementById( 'flashwarning' );													
									if ( warning == null ){
										var div = document.createElement( 'div' );
										div.innerHTML = response.responseText;
										div.id = 'flashwarning';
										document.getElementById( 'progress_container' ).appendChild( div );
									}
								},1,0,false);
							} else {
								$('#flashwarning').remove();
							}
						}
				}
			
			requestCheckQueue( timeout_poller, 0 );
		}
}

function createProgressBar () {
	var bar = document.getElementById( 'progress_container' );
	var message = document.getElementById( 'queueMessage' );
	if ( bar != null && message == null ){
		bar.innerHTML = "<p style='height: 60px; position: relative; top: 6px;'><img src='"+ imagePath + "/swinxs/queue_bg.gif' style='height: 50px; width: 290px;'><img id='queueProgress' src='" + imagePath + "/swinxs/queue_progress.gif' style='position: relative; top: -55px; width: 100px; height: 50px;'><img src='"+ imagePath + "/swinxs/queue_mask.png' style='position: relative; top: -110px;'></p><p><span id='queueMessage'></span></p>"; 
	}
}

function removeProgressBar() 
{
			var element = document.getElementById( 'progress_container');
			if (element)
							while (element.firstChild) {
										element.removeChild(element.firstChild);
							};
}

function SwitchSite()
{
        var select = document.switchsite.lang;
        var url = window.location.href;
        window.location.href = url.replace(/\/..\//, '/' + select.options[select.selectedIndex].value + '/');
}

/* Infowindow 'class' */
function InfoWindow(){
	this.Element = null;
	this.baseNodeType = 'div';
	this.markerOffset = 50;
	this.AnimateOnShow = true;
}

InfoWindow.prototype.Create = function( ){
	this.Element = document.createElement( this.baseNodeType );
 	this.Element.className = 'Details';

  var div1 = document.createElement( 'div' );
  var div2 = document.createElement( 'div' );
  var div3 = document.createElement( 'div' );
  var div4 = document.createElement( 'div' );
  var marker = document.createElement( 'div' );

  div1.className = 'Window_RB';
  div2.className = 'Window_LB';
  div3.className = 'Window_RT';
  div4.className = 'Window_LT';
  marker.className = 'Window_Marker';

  marker.style.left = this.markerOffset + 'px';

  div2.appendChild( div1 );
  div3.appendChild( div2 );
  div3.appendChild( div2 );
  div4.appendChild( div3 );
  div4.appendChild( marker );

 	this.Element.appendChild( div4 );
}

InfoWindow.prototype.SetText = function( html_or_node ){
	
	if ( this.Element != null ){
	  if ( typeof(html_or_node) == 'string' ){
			$(this.Element).find( 'div.Window_RB' ).get(0).innerHTML = html_or_node;
	  } else {
			$(this.Element).find( 'div.Window_RB' ).children().remove();
			$(this.Element).find( 'div.Window_RB' ).get(0).appendChild( html_or_node );
	  }
	}

}

InfoWindow.prototype.AddToDocument = function( parentNode, nextNode ){
	if ( nextNode ){
		parentNode.insertBefore( this.Element, nextNode );
	} else {
		parentNode.appendChild( this.Element );
	}

  if ( this.AnimateOnShow ){
    if ($.browser.msie) {
      var element = this.Element;
      var height = $(element).height();
      $(element).css( "height", $(element).height() );
      $(element).children().hide( 1, function(){
         $(element).children().show();
      } );
    } else {
      $(this.Element).children().css( 'opacity', '0' );
      $(this.Element).children().animate( { opacity: 1 }, 2000 );
    }
  }
}

InfoWindow.prototype.Remove = function( ){
	$(this.Element).remove();
}

function CreateInfoWindow( html_or_node, options ){
	var w = new InfoWindow();

	if ( typeof( options ) == 'object' ){
		for( var i in options ){
			switch( i ){
				case 'markerOffset' : {
					w[ i ] = Math.max( options[ i ], 25 );
				} break;
				default:
					w[ i ] = options[ i ];
			}
		}
	}
	w.Create();
	w.SetText( html_or_node );
	return w;
}

function RemoveInfoWindow( handle ){
	handle.Remove();
}

function NavigateToElement( jquery_tag ){
	var p = $( jquery_tag ).position();

	$('html').stop();

	var difference = p.top - $('html').scrollTop();

	$('html').animate(
		{
			scrollTop: '+=' + ( difference ) + 'px'
		}, 
		1000	
	);
}

function UpdatePersonalPage_XSTags(){

	if ( $('#xsTagsPers').length > 0 ){

		jQuery.get( '../swinxs/update_xstags.php', {}, function( data ){

			$('#xsTagsPers').children('.ArticleBody').get( 0 ).innerHTML = "<br />" + data;

			NavigateToElement( '#xsTagsPers' );

			$('li.XSTag').each( function(  ){
				new Homepage_XSTag( this );
			} );
	  } );
	}
}

function UpdatePersonalPage_Games(){

  if ( $('#gamesPers').length > 0 ){

    jQuery.get( '../swinxs/update_games.php', {}, function( data ){

      $('#gamesPers').children('.ArticleBody').get( 0 ).innerHTML = "<br />" + data;

      NavigateToElement( '#gamesPers' );

      $('li.Game').each( function(  ){
        new Homepage_Game( this );
      } );
    } );
  }
}

function UpdatePersonalPage_Music(){

  if ( $('#musicPers').length > 0 ){

    jQuery.get( '../swinxs/update_music.php', {}, function( data ){

      $('#musicPers').children('.ArticleBody').get( 0 ).innerHTML = "<br />" + data;

      NavigateToElement( '#musicPers' );

      $('li.Music').each( function(  ){
        new Homepage_Music( this );
      } );
    } );
  }
}

/* Actions */
function Add_Language( language_id ){
	location.href = '../swinxs/addlang.php?lang_id=' + language_id;
}

function Select_Language( language_id ){
	location.href = '../swinxs/selectlang.php?lang_id=' + language_id;
}

function Delete_Language( language_id ){
  ajaxCall( "../swinxs/deletelang.php?lang_id=" + language_id,function(){
		checkQueue();
	},1,0,0 );
}


function Add_Game( game_id ){
	ajaxCall('../swinxs/addgame.php?game_id=' + game_id,function() {
		checkQueue();
	},1,0,0); 
}

function Buy_Game( game_id ){
  ajaxCall('../swinxs/buygame.php?game_id=' + game_id,function() {
    checkQueue();
  },1,0,0);
}

function Delete_Game( id, game_id ){
  ajaxCall( '../swinxs/deletegame.php?id=' + id + '&game_id=' + game_id, function(){
		checkQueue();
	}, 1, 0, 0 );
}

function Update_Game( id, game_id ){
  ajaxCall( '../swinxs/updategame.php?id=' + id + '&game_id=' + game_id, function(){
		checkQueue();
	}, 1, 0, 0 );
}

function Play_Music( music_id, callback ){
	$.get(
		'../home/personal.php',
		{
			playmusic: music_id
		}
	);

	if ( callback ){
		checkQueueMusicPlaying[ music_id ] = { 
			music_id: music_id, 
			callback: callback 
		};
	}
	requestCheckQueue( 1000 );
}

function Stop_Music( music_id ){
  $.get(
    '../home/personal.php',
    {
      stopmusic: music_id
    }
  );
}

function Delete_Music( music_id ){
	ajaxCall('../swinxs/deletemusic.php?file_id=' + music_id, function(){
		checkQueue();
	}, 1, 0, 0);
}

function Add_XS_Sound( rfid ){
	$.get(
    '../home/personal.php',
    {
      add_sound_xs: rfid
    },
    function(){
      checkQueue();
    }
  );
}

function Play_XS_Sound( rfid ){
	$.get(
    '../home/personal.php',
    {
      playxs: rfid
    }
  );
}

function Update_XS( rfid, name, callback ){
  $.post(
    '../home/personal.php',
    {
      storexs: rfid,
      value: name
    },
    function(){
			if ( jQuery.isFunction( callback ) ){
				callback();
			}
    }
  );
}

function TabbedMenu( jqueryTabs ){
  this.Tabs = jqueryTabs;
  this.TabCount = this.Tabs.length;
  this.UL_Menu = null;
	this.IntervalOpener = null;

  this.BuildMenu();
}

TabbedMenu.prototype.BuildMenu = function(){
  this.UL_Menu = document.createElement( 'ul' );
  this.UL_Menu.className = 'Tabs';
  var self = this;
  $(this.Tabs).each( function( index ){
    var li = document.createElement( 'li' );
    var kop = $(this).children().get( 0 );
    li.style.width = Math.floor( 99 / self.TabCount ) + '%';
    li.appendChild( kop );
    $(kop).click( function(){
			clearInterval( self.IntervalOpener );
      self.OpenTab( index );
    } );
    $(kop).addClass( 'Tab_' + ( index + 1 ) );
    self.UL_Menu.appendChild( li );
    if ( index > 0 ){
      $(this).hide();
    }
  } );

  this.OpenTab( 0 );

  var currentH2 = $('div.Container').children().get( 0 );
  $(currentH2).replaceWith( $(this.UL_Menu) );

  this.IntervalOpener = setInterval( function(){
    self.OpenNextTab();
  }, 10000 );

	this.OpenTab( 0 );
}

TabbedMenu.prototype.OpenNextTab = function( ){
  this.OpenTab( this.CurrentIndex == this.TabCount - 1 ? 0 : this.CurrentIndex + 1 );
}

TabbedMenu.prototype.OpenTab = function( index ){
  this.Tabs.hide();
  var active_tab = this.Tabs.get( index );
  $( active_tab ).show();
  this.CurrentIndex = index;

  var width = $(this.UL_Menu).width();
  var left = Math.floor( ( ( width * 0.99 ) / this.TabCount ) * index + 50 );
  $(this.UL_Menu).css( { backgroundPosition: left + 'px bottom'} );

	if ( index == 2 ){
		window.frames.SwinxsLocator.SwinxsLocator.ReInit();
	}

}

function UpdateTabs(){
  var pageContent = $('div.PageContent').get( 0 );
  var tabs = $(pageContent).children( 'div.Tab' );
  if ( tabs.length > 1 ){
    new TabbedMenu( tabs );
  }
}


