/**
 * @version $id $
 *
 * Flash games javascript class
 */

/**
 * Create a Syn.FreeGamesPromo component instance
 * @constructor
 */
Syn.FreeGamesPromo = Syn.Component.extend (
{
	/**
	 * Initialize the component class. This is called automatically by the default constructor.
	 * @member Syn.FreeGamesPromo
	 * @param {Object} config The configuration data structure
 	*/
	init: function(config)
	{
		this._super(config);
		
		this.find('.pagination_bullets ul li.next').connect('click',this,'submit',[ {'action':'loadThumbnailsPage', 'thumbnails_page_index':this.config['thumbnails_page_index']+1} ])
							   .liveConnect('click',this,'showLoading');
		this.find('.pagination_bullets ul li.prev').connect('click',this,'submit',[ {'action':'loadThumbnailsPage', 'thumbnails_page_index':this.config['thumbnails_page_index']-1} ])
							   .liveConnect('click',this,'showLoading');

		$('#'+this.uniqueKey()+' .pagination_bullets ul li a').liveConnect('click', this, 'updateThumbnailsPage');

		// Bind 'change' event to the <select> dropdown.
		this.bindDropdownMenu();

		/**
		 * Note: keeping the reccently played games logic here while waiting to integrate this component
		 * fully with the Games MochiAds integration.  The recently played games functionality will need
		 * to be reapplied for this.
		 * 
		for (var i=0; this.uniqueElmt('games_thumbnail_a'+i).length; i++)
		{
			this.uniqueElmt('games_thumbnail_a'+i).liveConnect('click',this,'launchGame');
		}

		// Note that this index begins at 1 because the element number is printed next to the game link.
		for (var i=1; this.uniqueElmt('games_recent_col1_a'+i).length; i++)
		{
			this.uniqueElmt('games_recent_col1_a'+i).liveConnect('click',this,'launchGame');
		}
		// Note that this index begins at 1 because the element number is printed next to the game link.
		for (var i=1; this.uniqueElmt('games_recent_col2_a'+i).length; i++)
		{
			this.uniqueElmt('games_recent_col2_a'+i).liveConnect('click',this,'launchGame');
		}
		*/
	},

	/**
	 * 
	 */
	onAjaxUpdate: function(config)
	{
		this.config = config;

		this.find('.pagination_bullets ul li.next').connect('click',this,'submit',[ {'action':'loadThumbnailsPage', 'thumbnails_page_index':this.config['thumbnails_page_index']+1} ]);
		this.find('.pagination_bullets ul li.prev').connect('click',this,'submit',[ {'action':'loadThumbnailsPage', 'thumbnails_page_index':this.config['thumbnails_page_index']-1} ]);

		// Re-bind 'change' event to the <select> dropdown.
		this.bindDropdownMenu();
	},

	bindDropdownMenu: function()
	{
		this.uniqueElmt('games_dropdown_select').connect('change',this,'dropdownLaunchGame');
	},

	/**
	 * Submit a new thumbnailsPageIndex as per carousel pagination bullet.
	 */
	updateThumbnailsPage: function(elmt,ev)
	{
		this.submit({'action':'loadThumbnailsPage', 'thumbnails_page_index':$(elmt).html()});
	},

	/**
	 * Shows loading graphic when retrieving data
	 * @member Syn.FreeGamesPromo
	 */
	showLoading: function()
	{
		var ga = this.uniqueElmt('free_games_promo_thumbnails');
		this.uniqueElmt('free_games_promo_loading').css({'width':ga.width(),'height':ga.height()}).toggle();
	},

	/**
	 * Launches the popup window with the flash game
	 * @member Syn.FreeGamesPromo
	 */
	launchGame: function (elmt,ev)
	{
		this.submit({'action':'addRecentlyPlayedGame', 'game_token':$(elmt).attr('rel'), 'thumbnails_page_index':this.config['thumbnails_page_index']}, {norender:false});
		window.open($(elmt).attr('href'), 'gamewrapper', 'menubar=0,toolbar=0,location=0,status=0,scrollbars=0,resizable=1,directories=0,width=742,height=700');
	},

	/**
	 * Launches the popup window with the flash game
	 * @member Syn.FreeGamesPromo
	 */
	dropdownLaunchGame: function (elmt,ev)
	{
		//this.submit({'action':'addRecentlyPlayedGame', 'game_slug':$(elmt).attr('value'), 'thumbnails_page_index':this.config['thumbnails_page_index']}, {norender:false});
		window.location = Syn.Config.Framework.PortalRoot+this.config['games_channel_directory_path']+this.config['play_flash_game_page_path']+'?game_slug='+$(elmt).attr('value');
	}

});

;
/**
 * The Syn.ServicesComponent Class
 */

/**
 * Create a Syn.ServicesComponent instance
 * @constructor
 */
Syn.ServicesComponent = Syn.Component.extend(
{
	/**
	 * Initialize the component class. This is called automatically by the default constructor.
	 * @member Syn.ServicesComponent
	 * @param {Object} config The configuration data structure
	 */
	init: function(config)
	{
		this._super(config);
		this.clicked_components = [];
		this.active_tab = '';
		this.performUpdate();
		this.updatable = config['updatable'];
	},

	onAjaxUpdate: function(config)
	{
		this.config = config;
		this.performUpdate();
	},

	performUpdate: function()
	{
		//hook events up
		// hook up all the tabs except tabs that have the 'services_tab_bare_link' classed anchor tags
		var that = this;
		this.uniqueElmt().find('.services_tab_wrap').each(
			function () {
				if ($(this).find('a[class="services_tab_bare_link"]').length == 0)
				{
					$(this).parent().connect('click', that, 'linkClick');
				}
			}
		);
		
		this.uniqueElmt().find('.services_list_nav > div').connect('mouseover', this, 'linkHover');
		this.uniqueElmt().find('.services_list_nav > div').connect('mouseout', this, 'linkHoverOut');
		this.uniqueElmt().find('.car_arrow_next').connect('click', this, 'nextPage');
		this.uniqueElmt().find('.car_arrow_prev').connect('click', this, 'prevPage');
	},

	nextPage: function()
	{
		this.removeCurrentInstances();
		this.submit({action: 'default', start: this.config['start'], direction: 'next'});
	},

	prevPage: function()
	{
		this.removeCurrentInstances();
		this.submit({action: 'default', start: this.config['start'], direction: 'prev'});
	},

	removeCurrentInstances: function()
	{
		this.active_tab = '';
		for (var k=0;k<this.clicked_components.length;k++)
		{
			Syn.ComponentMgr.remove(this.clicked_components[k]);
		}
		this.clicked_components = [];
	},

	linkClick: function(target, event)
	{
		var self = this;
		var tab = $(target);
		var uri = tab.attr('rel');
		this.uniqueElmt().find('.services_list_wrap').removeClass('on');
		this.uniqueElmt().find('.services_list_nav > div').removeClass('on');

		if (uri != '')
		{
			var zone = tab.parent().parent().find('.services_list_cont');
			zone.children('div').hide();
			var target_div = zone.find('[rel='+uri+']');
			var content_load_function = function (result)
			{
				zone.children('div').hide();
				new_target = zone.find('[rel='+uri+']');
				if (!new_target.size())
				{
					zone.append('<div rel="' + uri + '">' + result.content + '</div>');
					new_target = zone.find('[rel='+uri+']');
					new_target.show();
				}
				var instance = Syn.ComponentMgr.getInstanceByUid(result.init.event_id);
				if (instance != undefined)
				{
					self.clicked_components.push(instance);
				}
			};

			var pos = 'left';
			if (tab.prev().size())
			{
				if (tab.next().size())
				{
					pos = 'center';
				}
				else
				{
					pos = 'right';
				}
			}

			if (uri != this.active_tab)
			{
				if (target_div.size())
				{
					target_div.show();
				}
				else
				{
					zone.find('.services_loading').show();
					this.getComponent(uri, zone.attr('rel'), {'action': 'expanded'}, this, content_load_function);
				}

				this.active_tab = uri;

				zone.parent().addClass('on');

				zone.parent().find('.services_list_head').removeClass().addClass('services_list_head').addClass(pos);

				tab.addClass('on');
			}
			else
			{
				this.active_tab = '';
			}
		}

		this.refreshTabs();
	},

	linkHover: function(target, event)
	{
		if (!$(target).hasClass('on'))
		{
			$(target).addClass('services_hover');
		}
	},

	linkHoverOut: function(target, event)
	{
		$(target).removeClass('services_hover');
	},

	refreshTabs: function()
	{
		var that = this;
		this.uniqueElmt().find('.services_list_nav > div').each(function(i, elem)
		{
			var uri = $(elem).attr('rel');
			if (uri)
			{
				var key = '';
				for (key in that.updatable)
				{
					if (that.updatable[key] === uri)
					{
						that.getComponent(uri, '', {'action': 'thumbnail'}, that, function(result) {
							$(elem).html(result.content);
						});
					}
				}
			}
		});
	}
});
;
/**
 * Function to display only one package at a time
 */
function accordionEffect(myrand)
{
    var mypackages = ['variety','learning','sports','music'];
    for (var x in mypackages)
    {
        if (x != myrand)
        {
            $('#package_' + mypackages[x] + '_display').hide();
            $('#package_' + mypackages[x] + '_header').attr('class','premium_close');
            $('#package_' + mypackages[x] + '_header_link').removeClass('on'); 
        }
    }
}

/**
 * Function to handle toggle functionality
 */
function toggleView(pack, myrand, flag)
{
    var mypackages = ['variety','learning','sports','music'];
    if ((flag == 1 && mypackages[myrand] != pack) || (flag == 2 && mypackages[myrand] == pack))
    {
        if ($('#package_' + pack + '_header').attr('class') != 'premium_open')
        {
            $('#package_' + pack + '_header').attr('class','premium_open'); 
            $('#package_' + pack + '_header_link').addClass('on'); 
            $('#package_' + pack + '_display').slideDown(); 
        }
        else
        {
            $('#package_' + pack + '_header').attr('class','premium_close'); 
            $('#package_' + pack + '_header_link').removeClass('on'); 
            $('#package_' + pack + '_display').hide(); 
        }
    }
    else if ((flag == 2 && mypackages[myrand] != pack) || (flag == 1 && mypackages[myrand] == pack))
    {
        if ($('#package_' + pack + '_header').attr('class') != 'premium_close')
        {
            $('#package_' + pack + '_header').attr('class','premium_close'); 
            $('#package_' + pack + '_header_link').removeClass('on'); 
            $('#package_' + pack + '_display').hide(); 
        }
        else
        {
            $('#package_' + pack + '_header').attr('class','premium_open'); 
            $('#package_' + pack + '_header_link').addClass('on'); 
            $('#package_' + pack + '_display').slideDown(); 
        }
    }
    for (var x in mypackages)
    {
        if (mypackages[x] == pack)
        {
            accordionEffect(x);
            break;
        }
    }
}

$(document).ready(function()
{
    var mypackages = ['variety','learning','sports','music'];
    //This will generate a number between 0 and 4 (since there are five packages)
    var myRand = Math.floor(Math.random()*4);
  
    //Display the premiums in package selected 
    $('#package_' + mypackages[myRand] + '_display').show(); 
    $('#package_' + mypackages[myRand] + '_header').attr('class','premium_open'); 
    $('#package_' + mypackages[myRand] + '_header_link').attr('class','on'); 

    //Hiding everything but package choosen at random
    accordionEffect(myRand);

    //Registering Toggle Events
	$('#package_variety_header_link').toggle(function () { toggleView('variety',myRand, 1); }, function () { toggleView('variety',myRand, 2); });
	$('#package_learning_header_link').toggle(function () { toggleView('learning',myRand, 1); }, function () { toggleView('learning',myRand, 2); });
	$('#package_sports_header_link').toggle(function () { toggleView('sports',myRand, 1); }, function () { toggleView('sports',myRand, 2); });
	$('#package_music_header_link').toggle(function () { toggleView('music',myRand, 1); }, function () { toggleView('music',myRand, 2); });
	
});
;
