text:
package com.xboxcollectorsplace.ui;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Locale;

import com.google.gson.Gson;
import com.xboxcollectorsplace.App;
import com.xboxcollectorsplace.R;
import com.xboxcollectorsplace.bl.BLParameters;
import com.xboxcollectorsplace.bl.BLUtils;
import com.xboxcollectorsplace.bl.controllers.StorageController;
import com.xboxcollectorsplace.bl.entities.Catalog;
import com.xboxcollectorsplace.bl.entities.DLC;
import com.xboxcollectorsplace.bl.entities.Game;
import com.xboxcollectorsplace.bl.entities.Link;
import com.xboxcollectorsplace.bl.entities.Game.Genre;
import com.xboxcollectorsplace.bl.entities.Game.Status;
import com.xboxcollectorsplace.bl.entities.OptionString;
import com.xboxcollectorsplace.utils.JustifiedTextView;
import com.xboxcollectorsplace.utils.XLog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * Full screen activity, contains all the details of the game selected in the caller activity
 */
public class GameDetailActivity extends ActionBarActivity implements OnClickListener
{
	//------------------------------------------------------------------------- ATTRIBUTES*/

	private ImageView _imgCover;
	private TextView _txtTitle;
	private TextView _txtRelease;
	private TextView _txtGenre;
	private TextView _txtDeveloper;
	private Spinner _spnStatus;
	private RelativeLayout _lytAchievements;
	private TextView _txtAchievements;
	private ImageButton _btnEditAchievements;
	private ProgressBar _progressAchievements;
	private TextView _txtOnline;
	private TextView _txtCoop;
	private TextView _txtSplitScreen;
	private TextView _txtSystemLink;
	private TextView _txtLabelKinect;
	private TextView _txtKinect;
	private TextView _txtNoDLCs;
	private JustifiedTextView _txtSynopsis;
	private LinearLayout _lytDLCs;
	private LinearLayout _lytLinks;
	private EditText _edtNotes;
	private ProgressBar _prgCover;

	private StatusAdapter _statusAdapter;

	private Game _game;
	private boolean _isArcade = false;
	private boolean _reloadCollection = false;

	//------------------------------------------------------------------------- ON CREATE*/

    public void onCreate(Bundle savedInstanceState)
    {
    	try
    	{
			super.onCreate(savedInstanceState);
		    this.setContentView(R.layout.activity_game_detail);

		    this._game = ((Game) this.getIntent().getSerializableExtra(BLParameters.PARAMETERS.GAME));

			this._imgCover = (ImageView)this.findViewById(R.id.imgCover);
		    this._txtTitle = (TextView)this.findViewById(R.id.txtTitle);
		    this._txtRelease = (TextView)this.findViewById(R.id.txtRelease);
			this._txtGenre = (TextView)this.findViewById(R.id.txtGenre);
			this._txtDeveloper = (TextView)this.findViewById(R.id.txtDeveloper);
			this._spnStatus = (Spinner)this.findViewById(R.id.spnStatus);
			this._lytAchievements = (RelativeLayout)this.findViewById(R.id.lytAchievements);
			this._txtAchievements = (TextView)this.findViewById(R.id.txtAchievements);
			this._btnEditAchievements = (ImageButton)this.findViewById(R.id.btnEditAchievements);
			this._progressAchievements = (ProgressBar)this.findViewById(R.id.progressAchievements);
			this._txtOnline = (TextView)this.findViewById(R.id.txtOnline);
			this._txtCoop = (TextView)this.findViewById(R.id.txtCoop);
			this._txtSplitScreen = (TextView)this.findViewById(R.id.txtSplitScreen);
			this._txtSystemLink = (TextView)this.findViewById(R.id.txtSystemLink);
			this._txtSynopsis = (JustifiedTextView)this.findViewById(R.id.txtSynopsis);
			this._txtLabelKinect = (TextView)this.findViewById(R.id.txtLabelKinect);
		    this._txtKinect = (TextView)this.findViewById(R.id.txtKinect);
		    this._txtNoDLCs = (TextView)this.findViewById(R.id.txtNoDLCs);
		    this._lytDLCs = (LinearLayout)this.findViewById(R.id.lytDLCs);
		    this._lytLinks = (LinearLayout)this.findViewById(R.id.lytLinks);
		    this._edtNotes = (EditText)this.findViewById(R.id.edtNotes);
		    this._prgCover = (ProgressBar)this.findViewById(R.id.prgCover);

		    ActionBar actionBar = this.getSupportActionBar();
	        	actionBar.setDisplayShowHomeEnabled(false);
	        	actionBar.setDisplayShowTitleEnabled(false);

		    ArrayList<OptionString> statusList = new ArrayList<OptionString>();
		    	statusList.add(new OptionString(getString(R.string.catalog_status_not_own), Game.Status.NOT_OWN.toString()));
				statusList.add(new OptionString(getString(R.string.catalog_status_own), Game.Status.OWN.toString()));
				statusList.add(new OptionString(getString(R.string.catalog_status_finished), Game.Status.FINISHED.toString()));
				statusList.add(new OptionString(getString(R.string.catalog_status_completed), Game.Status.COMPLETED.toString()));

		    this._statusAdapter = new StatusAdapter(this, R.layout.simple_spinner_item_custom, statusList);
				this._statusAdapter.setDropDownViewResource(R.layout.spinner_line_dropdown);
			this._spnStatus.setAdapter(this._statusAdapter);
			this._btnEditAchievements.setOnClickListener(this);

			if (this.getIntent().getExtras().containsKey(BLParameters.PARAMETERS.IS_ARCADE))
		    {
		    	this._isArcade = this.getIntent().getBooleanExtra(BLParameters.PARAMETERS.IS_ARCADE, false);
		    }

			Game gameLoaded = StorageController.loadGame(this._game.getId(), this._isArcade);
			if (gameLoaded != null)
			{
				this._game = gameLoaded;
			}

		    this.loadGameDetails();
		    this.supportInvalidateOptionsMenu();

		    this.loadBasicData();
			this.loadExtendedData();
			this.loadDLCs();
			this.loadLinks();
	    }
    	catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.onCreate]", ex);
		}
    }

    //------------------------------------------------------------------------- PRIVATE METHODS*/

    /**
     * Loads the details of the current game from the detail assets
     */
    private void loadGameDetails()
    {
    	try
    	{
	    	String detailCatalogJSON = null;
		    Gson gson = new Gson();
		    DecimalFormat decimalFormat = new DecimalFormat("##");

		    // Due to the high amount of games, they are divided in files of 100 games each one.
		    // To selected the appropriate file, the game ID is divided by 100, truncated, and
		    // checked if the result number is a multiple of 100, to substract 1 to the result in
		    // that case. For example, for game 535, the correct asset will be the 5th one,
		    // (535 / 100 = 5,xx => 5), for the game 500 it will be the 4th asset (500 is multiple
		    // of 100, so => 500 -1 = 499 => 499 / 100 = 4,xx => 4). Its done this way because
		    // games in assets go from 1 to 100
		    InputStream inputStream;
		    if (!_isArcade)
			{
		    	inputStream = App.getContext().getAssets().open(BLParameters.GENERAL_PARAMETERS.DETAILS_PATH + decimalFormat.format(this._game.getId() % 100 == 0 ? (this._game.getId() - 1) / 100 : this._game.getId() / 100) + BLParameters.GENERAL_PARAMETERS.XML_FILE);
			}
		    else
		    {
		    	inputStream = App.getContext().getAssets().open(BLParameters.GENERAL_PARAMETERS.ARCADE_DETAILS_PATH + decimalFormat.format(this._game.getId() % 100 == 0 ? (this._game.getId() - 1) / 100 : this._game.getId() / 100) + BLParameters.GENERAL_PARAMETERS.XML_FILE);
			}

	    	if (inputStream != null)
			{
	    		detailCatalogJSON = BLUtils.inputStreamToString(inputStream, BLParameters.GENERAL_PARAMETERS.CODIFICATION_UTF_8);
			}

	    	Catalog detailCatalog = gson.fromJson(detailCatalogJSON, Catalog.class);
			for (Game game : detailCatalog.getCatalog())
	    	{
	    		if (game.getId() == this._game.getId())
	    		{
	    			this._game.setDetails(game.getDetails());
	    			break;
	    		}
	    	}
    	}
    	catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.loadGameDetails]", ex);
		}
    }

    /**
     * Displays the basic data of the game: title, release date, genre, developer and status
     */
    private void loadBasicData()
    {
    	try
    	{
    		new LoadCover().execute();

	    	this._txtTitle.setText(this._game.getTitle().toUpperCase(Locale.getDefault()));
	    	this._txtRelease.setText(BLUtils.translateDate(this._game.getRelease()));

			if (this._game.getGenre() != null && this._game.getGenre().size() > 0)
			{
				for (Genre genre : this._game.getGenre())
				{
					switch (genre)
					{
						case ACTION:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_action) + "\n");
							break;
						case ADVENTURE:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_adventure) + "\n");
							break;
						case ACTION_ADVENTURE:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_action_adventure) + "\n");
							break;
						case FPS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_fps) + "\n");
							break;
						case JRPG:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_jrpg) + "\n");
							break;
						case RACING:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_racing) + "\n");
							break;
						case RPG:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_rpg) + "\n");
							break;
						case RTS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_rts) + "\n");
							break;
						case SPORTS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_sports) + "\n");
							break;
						case SURVIVAL:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_survival) + "\n");
							break;
						case TPS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_tps) + "\n");
							break;
						case ARPG:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_arpg) + "\n");
							break;
						case TRPG:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_trpg) + "\n");
							break;
						case BTU:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_btu) + "\n");
							break;
						case CFS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_cfs) + "\n");
							break;
						case FIGHTING:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_fighting) + "\n");
							break;
						case HS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_hs) + "\n");
							break;
						case HUNTING_FISHING:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_hunting_fishing) + "\n");
							break;
						case TD:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_tower_defense) + "\n");
							break;
						case MUSICAL:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_musical) + "\n");
							break;
						case MUSOU:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_musou) + "\n");
							break;
						case OPEN_WORLD:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_open_world) + "\n");
							break;
						case PARTY:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_party) + "\n");
							break;
						case PLATFORMER:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_platformer) + "\n");
							break;
						case POKER:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_poker) + "\n");
							break;
						case PUZZLE:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_puzzle) + "\n");
							break;
						case TBS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_tbs) + "\n");
							break;
						case SIM:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_sim) + "\n");
							break;
						case STEALTH:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_stealth) + "\n");
							break;
						case CARDS_BOARD:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_cards_board) + "\n");
							break;
						case STU:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_stu) + "\n");
							break;
						case VISUAL_NOVEL:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_visual_novel) + "\n");
							break;
						case PINBALL:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_pinball) + "\n");
							break;
						case FITNESS:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_fitness) + "\n");
							break;
						case MMORPG:
							this._txtGenre.setText(this._txtGenre.getText().toString() + this.getString(R.string.genre_mmorpg) + "\n");
							break;
						default:
							break;
					}
				}

				this._txtGenre.setText(this._txtGenre.getText().toString().substring(0, this._txtGenre.getText().toString().length() - 1));
			}

			if (this._game.getDetails().getDeveloper() != null && this._game.getDetails().getDeveloper().size() > 0)
			{
				for (String developer : this._game.getDetails().getDeveloper())
				{
					this._txtDeveloper.setText(this._txtDeveloper.getText().toString() + developer + "\n");
				}

				this._txtDeveloper.setText(this._txtDeveloper.getText().toString().substring(0, this._txtDeveloper.getText().toString().length() - 1));
			}

			this._spnStatus.setSelection(this._statusAdapter.getItemPosition(this._game.getStatus().toString()));
    	}
    	catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.loadBasicData]", ex);
		}
    }

    /**
     * Displays the following data of the game: Total achievements, unlocked achievements (using
     * a progressbar), number of multiplayer players, use of kinect and synopsis (using the
     * JustifiedTextView controller)
     */
    private void loadExtendedData()
    {
    	try
    	{
    		this._progressAchievements.setMax(this._game.getTotalAchievements());
			this._progressAchievements.setProgress(this._game.getCurrentAchievements());
		    this._txtAchievements.setText(this._game.getCurrentAchievements() + "/" + this._game.getTotalAchievements());
		    this._lytAchievements.bringToFront();

		    this._txtOnline.setText(this._game.getOnline() > 0 ? (this._game.getOnline() >= 10000 ? this.getString(R.string.detail_multiplayer_mmo) : this._game.getOnline() + " " + this.getString(R.string.general_players)) : this.getString(R.string.general_no));
		    this._txtCoop.setText(this._game.getCoop() > 0 ? (this._game.getCoop() >= 10000 ? this.getString(R.string.detail_multiplayer_mmo) : this._game.getCoop() + " " + this.getString(R.string.general_players)) : this.getString(R.string.general_no));
		    this._txtSplitScreen.setText(this._game.getSplitScreen() > 0 ? this._game.getSplitScreen() + " " + this.getString(R.string.general_players) : this.getString(R.string.general_no));
		    this._txtSystemLink.setText(this._game.getSystemLink() > 0 ? this._game.getSystemLink() + " " + this.getString(R.string.general_players) : this.getString(R.string.general_no));

		    switch(this._game.getKinect())
		    {
			    case BLParameters.KINECT.NOT_USED:
			    default:
			    	this._txtLabelKinect.setVisibility(View.GONE);
			    	this._txtKinect.setVisibility(View.GONE);
			    	break;
			    case BLParameters.KINECT.OPTIONAL_FEATURES:
			    	this._txtLabelKinect.setVisibility(View.VISIBLE);
			    	this._txtKinect.setVisibility(View.VISIBLE);
			    	this._txtKinect.setText(getString(R.string.detail_kinect_optional_features));
			    	break;
			    case BLParameters.KINECT.REQUIRED:
			    	this._txtLabelKinect.setVisibility(View.VISIBLE);
			    	this._txtKinect.setVisibility(View.VISIBLE);
			    	this._txtKinect.setText(getString(R.string.detail_kinect_required));
			    	break;
		    }

		    this._txtSynopsis.setText(this._game.getDetails().getSynopsis(), BLParameters.GENERAL_PARAMETERS.TRUNCATE_POSITION_GAME_SYNOPSIS);
	    }
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.loadExtendedData]", ex);
		}
    }

    /**
     * Displays game DLCs using a dynamically generated list. For each one the following info is
     * displayed: Cover (can be vertical or horizontal, if it exists), name, DLC type, release
     * date, achievements, synopsis and a check indicating if it has been downloaded or not
     * (checkable by the user)
     */
    private void loadDLCs()
    {
    	boolean isTablet = getResources().getBoolean(R.bool.isTablet);

    	try
    	{
    		// Array indicating the downloaded DLCs. If the game is still not stored in Shared
    		// Preferences (its not in the collection) this will be empty
    		ArrayList<DLC> downloadedDLCS = this._game.getDownloadedDLCs();

    		if (this._game.getDetails().getDLCs() != null && this._game.getDetails().getDLCs().size() > 0)
 		    {
    			this._lytDLCs.setVisibility(LinearLayout.VISIBLE);
 		    	this._txtNoDLCs.setVisibility(LinearLayout.GONE);

    			LayoutInflater layoutInflater = LayoutInflater.from(this);

    			for (int i = 0; i < this._game.getDetails().getDLCs().size(); i++)
    			{
    				// DLC info is loaded from the game
    				final DLC dlc = this._game.getDetails().getDLCs().get(i);

    				// Entry is initializated
    				LinearLayout lytDLC = (LinearLayout)layoutInflater.inflate(R.layout.item_dlc_list, null);
    				LinearLayout lytDLCCover = (LinearLayout)lytDLC.findViewById(R.id.lytDLCCover);
    				LinearLayout lytDLCHorizontal = (LinearLayout)lytDLC.findViewById(R.id.lytDLCHorizontal);
    				ImageView imgDLCHorizontal = (ImageView)lytDLC.findViewById(R.id.imgDLCHorizontal);
    				ImageView imgDLCCover = (ImageView)lytDLC.findViewById(R.id.imgDLCCover);
    				TextView txtDLCName = (TextView)lytDLC.findViewById(R.id.txtDLCName);
    				TextView txtDLCType = (TextView)lytDLC.findViewById(R.id.txtDLCType);
    				TextView txtDLCReleaseDate = (TextView)lytDLC.findViewById(R.id.txtDLCReleaseDate);
    				LinearLayout lytDLCAchievements = (LinearLayout)lytDLC.findViewById(R.id.lytDLCAchievements);
    				TextView txtDLCAchievements = (TextView)lytDLC.findViewById(R.id.txtDLCAchievements);
    				JustifiedTextView txtDLCSynopsis = (JustifiedTextView)lytDLC.findViewById(R.id.txtDLCSynopsis);
    				CheckBox chkDLCDownloaded = (CheckBox)lytDLC.findViewById(R.id.chkDLCDownloaded);

    				// Name
    				txtDLCName.setText(dlc.getName());

    				// DLC Type
    				switch (dlc.getType())
    				{
    					case 0:
    						txtDLCType.setText(getString(R.string.dlc_type_sp_add_on));
    						break;
    					case 1:
    						txtDLCType.setText(getString(R.string.dlc_type_mp_add_on));
    						break;
    					case 2:
    						txtDLCType.setText(getString(R.string.dlc_type_equipment));
    						break;
    					case 3:
    						txtDLCType.setText(getString(R.string.dlc_type_car_pack));
    						break;
    					case 4:
    						txtDLCType.setText(getString(R.string.dlc_type_minor_sp_add_on));
    						break;
    					case 5:
    						txtDLCType.setText(getString(R.string.dlc_type_sp_add_on_separately));
    						break;
    					case 6:
    						txtDLCType.setText(getString(R.string.dlc_type_mp_add_on_separately));
    						break;
    					case 7:
    					default:
    						txtDLCType.setText(getString(R.string.dlc_type_other));
    						break;
    					case 8:
    						txtDLCType.setText(getString(R.string.dlc_type_sp_mp_add_on));
    						break;
    					case 9:
    						txtDLCType.setText(getString(R.string.dlc_type_track_pack));
    						break;
    				}

    				// Release Date
    				if (!TextUtils.isEmpty(dlc.getReleaseDate()))
    				{
    					txtDLCReleaseDate.setVisibility(View.VISIBLE);
    					txtDLCReleaseDate.setText(BLUtils.translateDate(dlc.getReleaseDate()));
    				}
    				else
    				{
    					txtDLCReleaseDate.setVisibility(View.GONE);
    				}

    				// Achievements
    				if (dlc.getAchievements() > 0)
    				{
    					lytDLCAchievements.setVisibility(View.VISIBLE);
    					txtDLCAchievements.setText(String.valueOf(dlc.getAchievements()));
    				}
    				else
    				{
    					lytDLCAchievements.setVisibility(View.GONE);
    				}

    				// Synopsis
    				if (!TextUtils.isEmpty(dlc.getSynopsis()))
    				{
    					txtDLCSynopsis.setVisibility(View.VISIBLE);
    					txtDLCSynopsis.setTextSize(isTablet ? 12 : 11);
    					txtDLCSynopsis.setText(dlc.getSynopsis(), BLParameters.GENERAL_PARAMETERS.TRUNCATE_POSITION_DLC_SYNOPSIS);
    				}
    				else
    				{
    					txtDLCSynopsis.setVisibility(View.GONE);
    				}

    				// If the array is smaller than the actual number of DLCs, a entry will be
    				// added indicating that the current DLC is not downloaded. This is because
    				// if downloadedDLCs array doesnt exist, it is generated dinamically the
    				// first time that the game is loaded
    				if (downloadedDLCS.size() > i)
    				{
    					chkDLCDownloaded.setChecked(downloadedDLCS.get(i).getDownloaded());
    				}
    				else
    				{
    					downloadedDLCS.add(new DLC(dlc.getId(), false));
    				}

    				Bitmap cover;
    				Bitmap imgHorizontal;
    				if (!_isArcade)
    				{
    					cover = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(getPackageName() + BLParameters.GENERAL_PARAMETERS.COVER_DLC_PATH + this._game.getId() + "_" + dlc.getId() , null, null));
    					imgHorizontal = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(getPackageName() + BLParameters.GENERAL_PARAMETERS.COVER_HORIZONTAL_DLC_PATH + this._game.getId() + "_" + dlc.getId() , null, null));
        			}
    				else
    				{
    					cover = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(getPackageName() + BLParameters.GENERAL_PARAMETERS.ARCADE_COVER_DLC_PATH + this._game.getId() + "_" + dlc.getId() , null, null));
    					imgHorizontal = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(getPackageName() + BLParameters.GENERAL_PARAMETERS.ARCADE_COVER_HORIZONTAL_DLC_PATH + this._game.getId() + "_" + dlc.getId() , null, null));
        			}

    				// Vertical cover
    		    	if (cover != null)
    		    	{
    		    		lytDLCCover.setVisibility(ImageView.VISIBLE);
    		    		imgDLCCover.setImageBitmap(cover);
    		    	}
    		    	else
    		    	{
    		    		lytDLCCover.setVisibility(ImageView.GONE);
    		    	}

    		    	// Horizontal cover
    		    	if (imgHorizontal != null)
    		    	{
    		    		lytDLCHorizontal.setVisibility(ImageView.VISIBLE);
    		    		imgDLCHorizontal.setImageBitmap(imgHorizontal);
    		    	}
    		    	else
    		    	{
    		    		lytDLCHorizontal.setVisibility(ImageView.GONE);
    		    	}

    		    	// Listener for the check
    		    	chkDLCDownloaded.setOnCheckedChangeListener(new OnCheckedChangeListener()
    				{
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
						{
							ArrayList<DLC> downloadedDLCSs = _game.getDownloadedDLCs();

							for (DLC donwloadedDLC : downloadedDLCSs)
							{
								if (donwloadedDLC.getId() == dlc.getId())
								{
									donwloadedDLC.setDownloaded(isChecked);
								}
							}

							_game.setDownloadedDLCs(downloadedDLCSs);
						}
					});

    		    	// The DLC entry is added to the layout
    				this._lytDLCs.addView(lytDLC);

    				// A separator is added to the layout in case there are more DLCs
    				if (i != this._game.getDetails().getDLCs().size() - 1)
    				{
	    				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1);
	 		    			layoutParams.setMargins(0, 5, 0, 5);
	 		    		LinearLayout linearLayout = new LinearLayout(App.getContext());
	 		    			linearLayout.setLayoutParams(layoutParams);
	 		    			linearLayout.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

		    			this._lytDLCs.addView(linearLayout);
    				}
    			}
 		    }
 		    else
 		    {
 		    	this._lytDLCs.setVisibility(LinearLayout.GONE);
 		    	this._txtNoDLCs.setVisibility(LinearLayout.VISIBLE);
 		    }
	    }
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.loadDLCs]", ex);
		}
    }

    /**
     * Displays game links using a dynamically generated list. For each one the following info is
     * displayed: Web description, web name and web icon. Also, each entry has a clicklistener,
     * when clicked, a internet browser will be opened to access the link
     */
    private void loadLinks()
    {
    	boolean isTablet = getResources().getBoolean(R.bool.isTablet);

    	try
    	{
    		if (this._game.getDetails().getLinks() != null && this._game.getDetails().getLinks().size() > 0)
 		    {
    			LayoutInflater layoutInflater = LayoutInflater.from(this);

    			for (int i = 0; i < this._game.getDetails().getLinks().size(); i++)
    			{
    				// Link info is loaded from the game
    				final Link link = this._game.getDetails().getLinks().get(i);

    				// Entry is initializated
    				LinearLayout lytLink = (LinearLayout)layoutInflater.inflate(R.layout.item_link_list, null);
    				TextView txtWebDesc = (TextView)lytLink.findViewById(R.id.txtWebDesc);
    				TextView txtWebName = (TextView)lytLink.findViewById(R.id.txtWebName);
    				ImageView imgIcon = (ImageView)lytLink.findViewById(R.id.imgIcon);

    				// Web description and name
    				txtWebDesc.setText(link.getType());
					txtWebName.setText(link.getSite());

					// Web icon, depends on the site
					if (!TextUtils.isEmpty(link.getType()))
					{
						if (link.getSite().equals(BLParameters.LINKS.YOUTUBE))
						{
							imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_yt));
						}
						else if (link.getSite().equals(BLParameters.LINKS.GAMEFAQS))
						{
							imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_gf));
						}
						else if (link.getSite().equals(BLParameters.LINKS.TRUEACHIEVEMENTS))
						{
							imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_ta));
						}
						else if (link.getSite().equals(BLParameters.LINKS.XBOXACHIEVEMENTS))
						{
							imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_xa));
						}
						else if (link.getSite().equals(BLParameters.LINKS.METACRITIC))
						{
							imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_mc));
						}
						else
						{
							imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_www));
						}
					}

					// Listener of the link, it opens a browser when clicked
    				lytLink.setBackgroundDrawable(getResources().getDrawable(R.drawable.link_background));
    				lytLink.setOnClickListener(new OnClickListener()
    				{
						public void onClick(View view)
						{
							Intent linkIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link.getUrl()));
							startActivity(linkIntent);
						}
					});

    				// The Link entry is added to the layout
    				this._lytLinks.addView(lytLink);

    				// A separator is added to the layout in case there are more links
    				if (i != this._game.getDetails().getLinks().size() - 1)
    				{

	    				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1);
	 		    			layoutParams.setMargins(isTablet ? 25 : 15, 0, isTablet ? 15 : 10, 0);
	 		    		LinearLayout linearLayout = new LinearLayout(App.getContext());
	 		    			linearLayout.setLayoutParams(layoutParams);
	 		    			linearLayout.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

		    			this._lytLinks.addView(linearLayout);
    				}
    			}
 		    }
    		else
 		    {
    			LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		    		layoutParams.setMargins(10, 5, 5, 0);
		    	TextView txtNoLinks = new TextView(App.getContext());
			    	txtNoLinks.setText(this.getString(R.string.detail_no_links));
			    	txtNoLinks.setTextSize(14);
			    	txtNoLinks.setTextColor(this.getResources().getColor(R.color.black));
			    	txtNoLinks.setLayoutParams(layoutParams);
			    	txtNoLinks.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);

 		    	this._lytLinks.addView(txtNoLinks);
 		    }

    		this._edtNotes.setText(this._game.getNotes());
    	}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.loadExtras]", ex);
		}
    }

    /**
     * Displays an error dialog
     */
    private void showErrorDialog(String dialogText)
	{
    	try
    	{
    		final Dialog dialog = new Dialog(this, R.style.DialogTheme);
	     		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.dialog_custom_alert);

			TextView txtDialog = (TextView) dialog.findViewById(R.id.txtDialog);
				txtDialog.setText(dialogText);

			Button btnDialogPositive = (Button) dialog.findViewById(R.id.btnDialogPositive);
				btnDialogPositive.setText(getString(R.string.general_ok));
				btnDialogPositive.setOnClickListener(new OnClickListener() {
					public void onClick(View v)
					{
						dialog.dismiss();
					}
				});

			Button btnDialogNegative = (Button) dialog.findViewById(R.id.btnDialogNegative);
				btnDialogNegative.setVisibility(Button.GONE);

			dialog.show();
    	}
    	catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.showErrorDialog]", ex);
		}
	}

    /**
     * Displays a confirmation dialog indicating that the game is going to be deleted
     */
    private void showDeleteConfirmationDialog(String dialogText)
	{
    	try
    	{
    		final Dialog dialog = new Dialog(this, R.style.DialogTheme);
	     		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.dialog_custom_alert);

			TextView txtDialog = (TextView) dialog.findViewById(R.id.txtDialog);
				txtDialog.setText(dialogText);

			Button btnDialogPositive = (Button) dialog.findViewById(R.id.btnDialogPositive);
				btnDialogPositive.setText(getString(R.string.general_yes));
				btnDialogPositive.setOnClickListener(new OnClickListener() {
					public void onClick(View v)
					{
						deleteGame();
					}
				});

			Button btnDialogNegative = (Button) dialog.findViewById(R.id.btnDialogNegative);
				btnDialogNegative.setText(getString(R.string.general_no));
				btnDialogNegative.setOnClickListener(new OnClickListener() {
					public void onClick(View v)
					{
						dialog.dismiss();
					}
				});

			dialog.show();
		}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.showConfirmationDialog]", ex);
		}
	}

    /**
     * Deletes the current game, removing it from the collection stored in Shared Preferences
     */
    private void deleteGame()
    {
    	try
    	{
    		boolean operationSuccess = false;

	    	if (StorageController.existsGame(this._game.getId(), this._isArcade))
			{
	    		operationSuccess = StorageController.removeGame(this._game.getId(), this._isArcade);
			}

	    	if (operationSuccess)
	    	{
	    		BLUtils.showToast(this.getString(R.string.detail_remove_game).replace("X", this._game.getTitle()), true);
	    		setResult(RESULT_OK, new Intent());
	    		this.finish();
	    	}
	    	else
	    	{
	    		this.showErrorDialog(this.getString(R.string.general_error));
	    	}
    	}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.deleteGame]", ex);
		}
    }

    /**
     * Redraws every text of the activity in order for the language change to take effect
     */
    private void changeTextLanguage()
    {
    	try
    	{
    		this.supportInvalidateOptionsMenu();
    		this._txtGenre.setText("");
    		this._txtDeveloper.setText("");
    		this._lytDLCs.removeAllViews();
    		this._lytLinks.removeAllViews();

    		ArrayList<OptionString> statusList = new ArrayList<OptionString>();
		    	statusList.add(new OptionString(getString(R.string.catalog_status_not_own), Game.Status.NOT_OWN.toString()));
				statusList.add(new OptionString(getString(R.string.catalog_status_own), Game.Status.OWN.toString()));
				statusList.add(new OptionString(getString(R.string.catalog_status_finished), Game.Status.FINISHED.toString()));
				statusList.add(new OptionString(getString(R.string.catalog_status_completed), Game.Status.COMPLETED.toString()));
			this._statusAdapter = new StatusAdapter(this, R.layout.simple_spinner_item_custom, statusList);
				this._statusAdapter.setDropDownViewResource(R.layout.spinner_line_dropdown);
			this._spnStatus.setAdapter(this._statusAdapter);

			((TextView)this.findViewById(R.id.txtReleaseDescription)).setText(this.getString(R.string.detail_release));
			((TextView)this.findViewById(R.id.txtGenreDescription)).setText(this.getString(R.string.detail_genre));
			((TextView)this.findViewById(R.id.txtDeveloperDescription)).setText(this.getString(R.string.detail_developer));
			((TextView)this.findViewById(R.id.txtStatusDescription)).setText(this.getString(R.string.detail_status));
			((TextView)this.findViewById(R.id.txtAchievementsDescription)).setText(this.getString(R.string.detail_achievements));
			((TextView)this.findViewById(R.id.txtMultiplayerDescription)).setText(this.getString(R.string.detail_multiplayer));
			((TextView)this.findViewById(R.id.txtOnlineDescription)).setText(this.getString(R.string.detail_multiplayer_online));
			((TextView)this.findViewById(R.id.txtCoopDescription)).setText(this.getString(R.string.detail_multiplayer_coop));
			((TextView)this.findViewById(R.id.txtSplitScreenDescription)).setText(this.getString(R.string.detail_multiplayer_split_screen));
			((TextView)this.findViewById(R.id.txtSystemLinkDescription)).setText(this.getString(R.string.detail_multiplayer_system_link));
			((TextView)this.findViewById(R.id.txtLabelKinect)).setText(this.getString(R.string.detail_kinect));
			((TextView)this.findViewById(R.id.txtSynopsisDescription)).setText(this.getString(R.string.detail_synopsis));
			((TextView)this.findViewById(R.id.txtDLCsDescription)).setText(this.getString(R.string.detail_dlcs));
			((TextView)this.findViewById(R.id.txtLinksDescription)).setText(this.getString(R.string.detail_links));
			((TextView)this.findViewById(R.id.txtNotesDescription)).setText(this.getString(R.string.detail_notes));
			this._txtNoDLCs.setText(this.getString(R.string.detail_no_dlc));
			this._edtNotes.setHint(getString(R.string.detail_notes_hint));
    	}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.changeTextLanguage]", ex);
		}
    }

    /**
     * Called after making an import, loads the new editable data of the current game, if there
     * is any data at all. Non editable data is reloaded too in case the language has been changed
     * (possible when making the import at Photo Gallery Activity)
     */
    private void reloadAfterImport()
	{
		try
		{
			this._reloadCollection = true;
			Catalog collection = StorageController.loadCollection(this._isArcade);

			boolean found = false;
			if (collection != null && collection.getCatalog() != null
					&& collection.getCatalog().size() > 0)
			{
				for (Game game : collection.getCatalog())
				{
					if (game.getId() == this._game.getId())
					{
						// If the game is in the new collection, the new editable data is loaded
						this._game.setCurrentAchievements(game.getCurrentAchievements());
						this._game.setStatus(game.getStatus());
						this._game.setDownloadedDLCs(game.getDownloadedDLCs());
						this._game.setNotes(game.getNotes());
						found = true;
						break;
					}
				}
			}

			// If the game is not in the new collection, editable data is reset
			if (!found)
			{
				this._game.setCurrentAchievements(0);
				this._game.setDownloadedDLCs(new ArrayList<DLC>());
				this._game.setNotes("");
				this._game.setStatus(Status.NOT_OWN);
			}

			// Its possible that the language has been changed too (when calling the method after
			// coming from Photo Gallery), we load all the data again
			this.supportInvalidateOptionsMenu();
    		this._txtGenre.setText("");
    		this._txtDeveloper.setText("");
    		this._lytDLCs.removeAllViews();
    		this._lytLinks.removeAllViews();

			this.loadBasicData();
			this.loadExtendedData();
			this.loadDLCs();
			this.loadLinks();
		}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.reloadAfterImport]", ex);
		}
	}

    //------------------------------------------------------------------------- EVENTS*/

    /**
	 * Event related to the push of the back button. If the collection is to be reloaded (mainly
	 * because the language has been changed, a new game has been added or a game has been deleted)
	 * it returns an OK and a true boolean to the caller activity
	 */
    public boolean onKeyDown(int keyCode, KeyEvent event)
  	{
  	    if (keyCode == KeyEvent.KEYCODE_BACK)
  	    {
  	    	if (this._reloadCollection)
  	    	{
  	    		this.setResult(RESULT_OK, new Intent());
  	    	}
  	    	this.finish();

  	        return true;
  	    }

  	    return super.onKeyDown(keyCode, event);
  	}

    /**
	 * Event related to the creation of the action menu
	 */
    public boolean onCreateOptionsMenu(Menu menu)
    {
  		try
  		{
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.game_detail_menu, menu);
	    }
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.onCreateOptionsMenu]", ex);
		}

        return true;
    }

    /**
	 * Event related to the display of the action menu. Depending on whether the game is in the
	 * collection or not, remove icon will be displayed and OK icon title will change
	 * (add or edit)
	 */
    public boolean onPrepareOptionsMenu(Menu menu)
	{
		try
		{
			if (StorageController.existsGame(this._game.getId(), this._isArcade))
			{
				menu.findItem(R.id.options_ok).setTitle(getString(R.string.options_save_changes));
				menu.findItem(R.id.options_remove).setVisible(true);
			}
			else
			{
				menu.findItem(R.id.options_ok).setTitle(getString(R.string.options_add_game));
				menu.findItem(R.id.options_remove).setVisible(false);
			}
		}
	    catch (Exception ex)
	    {
	    	XLog.e("[GameDetailActivity.onPrepareOptionsMenu]", ex);
	    }

		return true;
	}

    /**
	 * Event related to the selection of one of the items of the action bar
	 */
    public boolean onOptionsItemSelected(MenuItem item)
	{
    	boolean operationSuccess = false;
    	String toastText = "";
    	Intent output = new Intent();

    	try
		{
		    switch (item.getItemId())
		    {
			    case R.id.options_ok:
			    	// Editable data is saved and the game is added to the collection or edited
			    	// in case it existed
			    	this._game.setStatus(Game.Status.valueOf(this._statusAdapter.getItem(this._spnStatus.getSelectedItemPosition()).getOptionKey()));
		    		this._game.setNotes(this._edtNotes.getText().toString());
		    		this._game.setDetails(null);

		    		if (StorageController.existsGame(this._game.getId(), this._isArcade))
	    			{
			    		operationSuccess = StorageController.editGame(this._game, this._isArcade);
			    		toastText = this.getString(R.string.detail_edit_game);
	    			}
			    	else
			    	{
			    		operationSuccess = StorageController.addGame(this._game, this._isArcade);
			    		toastText = this.getString(R.string.detail_add_game);
			    	}

			    	if (operationSuccess)
			    	{
			    		BLUtils.showToast(toastText.replace("X", this._game.getTitle()), true);
			    		setResult(RESULT_OK, output);
			    		this.finish();
			    	}
			    	else
			    	{
			    		this.showErrorDialog(this.getString(R.string.general_error));
			    	}
			    	break;
			    case R.id.options_remove:
			    	this.showDeleteConfirmationDialog(this.getString(R.string.detail_remove_game_confirmation));
			    	break;
			    case R.id.options_summary:
			    	output = new Intent(this, SummaryActivity.class);
			    	output.putExtra(BLParameters.PARAMETERS.IS_ARCADE, this._isArcade);
			    	startActivity(output);
			        break;
			    case R.id.options_export:
			    	output = new Intent(this, FileSelectorActivity.class);
			    	output.putExtra(BLParameters.PARAMETERS.IMPORT_MODE, false);
			    	startActivity(output);
			        break;
			    case R.id.options_import:
			    	output = new Intent(this, FileSelectorActivity.class);
			    	output.putExtra(BLParameters.PARAMETERS.IMPORT_MODE, true);
			    	startActivityForResult(output, BLParameters.ACTIVITY_CODES.IMPORT);
			        break;
			    case R.id.options_config:
		    		startActivityForResult(new Intent(this, ConfigActivity.class), BLParameters.ACTIVITY_CODES.CONFIG);
			        break;
		    	case R.id.options_photo_gallery:
		    		output = new Intent(this, PhotoGalleryActivity.class);
			    	output.putExtra(BLParameters.PARAMETERS.GAME, (this._isArcade ? "A" : "R") + String.valueOf(this._game.getId()));
			    	output.putExtra(BLParameters.PARAMETERS.GAME_TITLE, this._game.getTitle());
			    	output.putExtra(BLParameters.PARAMETERS.IS_ARCADE, this._isArcade);
			    	startActivityForResult(output, BLParameters.ACTIVITY_CODES.PHOTO_GALLERY);
			        break;
		    }
		}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.onOptionsItemSelected]", ex);
		}

    	return true;
	}

    /**
     * Event related to the touch of the Edit Achievements button.
     * Activity is called to edit the unlocked achievements
     */
	public void onClick(View view)
	{
		try
		{
			if (view.getId() == this._btnEditAchievements.getId())
			{
				Intent intent = new Intent(this, EditAchievementsActivity.class);
				intent.putExtra(BLParameters.PARAMETERS.CURRENT_ACHIEVEMENTS, this._game.getCurrentAchievements());
				intent.putExtra(BLParameters.PARAMETERS.TOTAL_ACHIEVEMENTS, this._game.getTotalAchievements());
	    		startActivityForResult(intent, BLParameters.ACTIVITY_CODES.EDIT_ACHIEVEMENTS);
			}
		}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.onClick]", ex);
		}
	}

	/**
     * Event related to the return from other activity.
     */
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		try
		{
			super.onActivityResult(requestCode, resultCode, data);

			if (requestCode == BLParameters.ACTIVITY_CODES.EDIT_ACHIEVEMENTS && resultCode == Activity.RESULT_OK)
			{
				// New unlocked achievements must be displayed
				if (data != null)
				{
					int achievements = data.getIntExtra(BLParameters.PARAMETERS.CURRENT_ACHIEVEMENTS, 0);
					this._game.setCurrentAchievements(achievements);
					this._progressAchievements.setProgress(achievements);
					this._txtAchievements.setText(this._game.getCurrentAchievements() + "/" + this._game.getTotalAchievements());
				}
			}
			if (requestCode == BLParameters.ACTIVITY_CODES.CONFIG && resultCode == Activity.RESULT_OK)
			{
				// Language changed. Every text must be refreshed
				this.changeTextLanguage();

				this.loadBasicData();
				this.loadExtendedData();
				this.loadDLCs();
				this.loadLinks();
			}
			if (requestCode == BLParameters.ACTIVITY_CODES.PHOTO_GALLERY && resultCode == Activity.RESULT_OK)
			{
				// Language could have been changed. Every text must be refreshed
				this.changeTextLanguage();

				if (data.getBooleanExtra(BLParameters.PARAMETERS.RELOAD_COLLECTION, false))
				{
					// Import made, all editable data must be reloaded
					this.reloadAfterImport();
				}
				else
				{
					this.loadBasicData();
					this.loadExtendedData();
					this.loadDLCs();
					this.loadLinks();
				}
			}
			if (requestCode == BLParameters.ACTIVITY_CODES.IMPORT && resultCode == Activity.RESULT_OK)
			{
				this.reloadAfterImport();
			}
		}
		catch (Exception ex)
		{
			XLog.e("[GameDetailActivity.onActivityResult]", ex);
		}
	}

    //------------------------------------------------------------------------- INNER CLASSES*/

	/**
	 * Adapter used by the spinners. Description is shown (optionName) and value is returned upon
	 * selection (optionKey)
	 */
    private class StatusAdapter extends ArrayAdapter<OptionString>
    {
        private ArrayList<OptionString> values;

        public StatusAdapter(Context context, int textViewResourceId, ArrayList<OptionString> values)
        {
            super(context, textViewResourceId, values);
            this.values = values;
        }

        public int getCount()
        {
           return values.size();
        }

        public OptionString getItem(int position)
        {
           return values.get(position);
        }

        public int getItemPosition(String key)
        {
        	int position = 0;

        	if (!TextUtils.isEmpty(key))
        	{
	        	for (int i = 0; i < values.size(); i++)
	        	{
	        		if (key.equalsIgnoreCase(values.get(i).getOptionKey()))
	        		{
	        			position = i;
	        		}
	        	}
        	}

        	return position;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
        	View view = super.getView(position, convertView, parent);

            if (view instanceof TextView)
            {
                ((TextView)view).setText(values.get(position).getOptionName());
            }

            return view;
        }

        public View getDropDownView(int position, View convertView, ViewGroup parent)
        {
        	 View row = super.getDropDownView(position, convertView, parent);

        	 if (row instanceof CheckedTextView)
        	 {
                 ((CheckedTextView)row).setText(values.get(position).getOptionName());
             }

             return row;
        }
    }

    /**
  	 * Asynchronous method used to load the cover, made this way due to the high amount of time
  	 * it required to load the cover from the covers zip stored in the device (no longer used).
  	 * A loading icon is showed in the place of the cover during this process
  	 */
    private class LoadCover extends AsyncTask<Boolean, Void, Boolean>
	{
    	Bitmap _cover;

		@Override
		protected void onPreExecute()
		{
			_prgCover.setVisibility(ProgressBar.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Boolean... parameters)
		{
			try
			{
	    		if (!_isArcade)
		    	{
	    			//TODO: Only for Google Play. This code was for retrieving the cover from
	    			//the covers expansion zip
	    			/*ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(App.getContext(), 1, 0);
	        		InputStream fileStream = expansionFile.getInputStream(BLParameters.GENERAL_PARAMETERS.COVER_PATH + _game.getId() + ".jpg");
	        		_cover = BitmapFactory.decodeStream(fileStream);
	        		fileStream.close();*/
	    			_cover = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(getPackageName() + BLParameters.GENERAL_PARAMETERS.COVER_PATH  + _game.getId() , null, null));
		    	}
		    	else
		    	{
		    		//TODO: Only for Google Play. This code was for retrieving the cover from
	    			//the covers expansion zip
		    		/*ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(App.getContext(), 1, 0);
	        		InputStream fileStream = expansionFile.getInputStream(BLParameters.GENERAL_PARAMETERS.ARCADE_COVER_PATH + _game.getId() + ".jpg");
	        		_cover = BitmapFactory.decodeStream(fileStream);
	        		fileStream.close();*/
		    		_cover = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(getPackageName() + BLParameters.GENERAL_PARAMETERS.ARCADE_COVER_PATH  + _game.getId() , null, null));
		    	}
			}
			catch (Exception ex)
			{
				XLog.e("[GameDetailActivity.LoadCover.doInBackground]", ex);
			}

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result)
		{
			_prgCover.setVisibility(ProgressBar.GONE);

			if (_cover != null)
	    	{
	    		_imgCover.setImageBitmap(_cover);
	    	}
	    	else
	    	{
	    		_imgCover.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.cover_unknown));
	    	}
		}
	}
}


Learn from history, or be condemned to repeat it. That goes double in the world of tech! Why did GroupOn, Yahoo, and MySpace stumble while AirBnB, Google, and Facebook thrived? This course seeks to answer questions like this, studying the past two decades to summarize some key trends of the tech industry. It rounds off with some specific ideas on how an individual or a company may deal with these trends.


text:
All posts in category Chile
By Kenneth Roberts and Eduardo Silva*
Ex-president Sebastián Piñera addresses his supporters at a campaign rally last month. / Twitter: @sebastianpinera
Chilean politics in the run-up to national presidential and legislative elections on November 19 have revealed that – within major lines of continuity – significant changes in the political alignments that have structured the country's democracy since the end of the Pinochet dictatorship in 1990 are taking place.
Continuity is most pronounced on the conservative side of the political spectrum, where the two main conservative parties, Renovación Nacional (RN) and Unión Demócrata Independiente (UDI), have joined forces with smaller parties to sponsor the presidential candidacy of billionaire business mogul and former President Sebastián Piñera. In public opinion surveys of voter intentions, Piñera has maintained a healthy lead over a collection of centrist and leftist candidates. He appears likely to come out on top in the first round of voting – and significant abstention (if fewer than 5.5 million registered voters vote) could push him over the top. If he is forced into a run-off, the final outcome will rest heavily on the ability of his opponents in the divided center-left bloc to coalesce forces.
The center-left space is where most change is concentrated. The core parties in the Nueva Mayoría coalition that backed incumbent Socialist President Michelle Bachelet have won five of Chile's six presidential elections since the transition to democracy in 1990. For the first time, however, the main centrist party, the Partido Demócrata Cristiano (PDC), has opted out of the alliance to run its own candidate, Senator Carolina Goic. With Goic languishing in the polls, however, the primary challengers to Piñera are located further to the left, including the Nueva Mayoría's favorite, Senator Alejandro Guillier. Although early speculation pegged him as an outsider, he is now firmly identified with the moderate reformist left and represents continuity with the current government.
A new left-leaning group, the Frente Amplio, has nominated Beatriz Sánchez, an independent journalist. She arguably represents a larger challenge to the status quo, as her candidacy gives political expression to social actors who are sharply critical of Chile's political establishment and the neoliberal economic model. Even though the Broad Front's electoral strength is untested, it brings together a number of small parties alienated from Nueva Mayoría and inspired by Chile's massive student protest movement and other activist networks that have mobilized around labor, environmental, and pension reform issues in recent years. Sánchez favors more redistributive taxation and greater state intervention in strategic enterprises and utilities, as well as in water property rights and forestry where social conflict has been high. She is also for replacing the private pensions system with a mixed public-private one and getting private banking out of the student loan business.
This election will likely show that the broad center-left coalition that dominated Chilean politics since the 1990 transition has effectively splintered, with the Christian Democrats seeking to carve out an independent space in the political center and a movement-based alternative emerging on the mainstream parties' left flank. Uniting such disparate forces to compete against Piñera in a run-off election, should one be required, will clearly be a formidable task. Nueva Mayoría candidate Alejandro Guillier, considered the strongest run-off candidate to take on Piñera, is already in conversation with Christian Democrats and Sánchez's Frente Amplio. In a run-off, he is thought likely to get around 60 percent of the Christian Democratic vote, with more conservative Christian Democrats voting for Piñera. His appeal to Frente Amplio voters could suffer because of their unhappiness with Nueva Mayoría.
The specter of high abstention looms large for second-round voting, too. President Bachelet's low approval ratings for most of her second term in office, although recently reversed, signaled low enthusiasm despite her successful pushing through a series of major reforms, including a reform of the electoral law to enhance proportional representation, a tax reform to increase revenues for social programs, the initiation of free university education for low-income students, and a much-debated law to legalize abortions in limited circumstances. Last, but not least, mainstream parties across the board have been weakened by a series of corruption and campaign finance scandals, leaving many citizens alienated from parties.
*Eduardo Silva is Professor of Political Science at Tulane University, and Kenneth Roberts is Professor of Government at Cornell University.
by clalsstaff on November 2, 2017 • Permalink
Posted in Chile
Tagged Elections
Posted by clalsstaff on November 2, 2017
https://aulablog.net/2017/11/02/chile-election-likely-to-show-big-political-shifts/
Chile's Transition to Clean Energy Matrix
By Thomas Andrew O'Keefe*
Parque Eólico Canela in Coquimbo, Chile, one of many wind-producing farms in Northern Chile. / Wikimedia / Creative Commons
Since Michelle Bachelet's return to the presidency in March 2014, Chile has aggressively pursued an ambitious program to transition the country's energy matrix toward non-conventional renewable resources. The emphasis on non-conventional includes mini-hydro facilities with a generating capacity under 20 Megawatts, geothermal, solar, wind, biomass, and potentially ocean currents. Chile aims to generate 60 percent of its electricity from domestic renewable energy resources (including all forms of hydro) by 2035, and 70 percent by 2050. To encourage that transition, Chile is one of only two Latin American countries (the other being Mexico) to establish a carbon tax, under which energy-intensive industries and utilities that exceed mandated emissions levels are charged US$5.00 per ton of CO2 emissions. Chile's drive to adopt a cleaner energy matrix is motivated as much by a desire to reduce greenhouse gas emissions as it is to enhance energy security.
During the mid-1990s, Chile faced consecutive years of severe drought that had hugely detrimental impacts on the country's dams, responsible at the time for around 50 percent of the country's electricity. An abundance of natural gas in neighboring Argentina led to the construction of pipelines across the Andes and new thermal generators in Chile, but Argentina began cutting natural gas exports in 2004 (and eventually stopped them altogether) because disastrous policies there had caused domestic shortages. Bolivia, in turn, rebuffed Santiago's entreaties to purchase its gas unless Chile granted it territorial compensation for the loss of Bolivian access to the Pacific after the 19th century War of the Pacific. Chile had to build two expensive receiving terminals to import Liquefied Natural Gas (LNG) from East Asia as well as Trinidad and Tobago. The Chileans were also forced to use more coal and diesel, exacerbating the already precarious air quality in many Chilean cities, particularly during the winter.
In recent years, more than half of all investment in non-conventional, renewable energy in Latin America and the Caribbean has been directed to Chile, primarily to build solar and wind parks to supply the mining industry in the north of the country. The shift to renewable energy has largely been financed by the private sector, with no subsidies other than reimbursement for small-scale photovoltaic and other nonconventional contributors to the grid at the full retail price (and no transmission charge). Chile's antipathy to subsidies reflects the country's market-based economic orientation and a conscious decision to prioritize state-of-the-art renewable technology sourced from elsewhere rather than encourage the development of its own industry. The recent investment boom in renewables was driven by the business-friendly climate, the fact that Chile is not a significant hydrocarbons producer, and the inflationary impact of the last three years of drought on the price of hydroelectricity.
Chile has several other things going for it in achieving its goals, including a good regulatory framework and resources that are in growing demand. Chilean regulators allow generators to sell electricity in only one of three time blocks during the day — giving solar and wind power a competitive edge in public purchase agreement auctions. This more than halved the bidding price offered by generators and made solar power competitive with natural gas and even electricity sourced from hydro. In the near future, as the country's energy matrix shifts to greater reliance on solar and wind power, Chile intends to utilize hydroelectricity to supply peaks in demand for electric power (usually in the evening hours) to make up for intermittencies in sunshine and wind. (At the moment, fossil fuels provide that function.) New developments in storage technology will also help. Chile is one of the world's largest producers of lithium, needed to make storage batteries. The interconnection of Chile's northern and central grids in 2018 should also facilitate greater use of different renewables and redirect the electric power generated from them to where it is most needed. Chile, already a leader in Latin American alternative energy production, is poised to enhance that position.
* Thomas Andrew O'Keefe is President of Mercosur Consulting Group, Ltd. He taught a seminar on "Energy and Climate Cooperation in the Americas: The Role of Chile" at Stanford's Santiago campus during the summer 2017 quarter.
by clalsstaff on September 11, 2017 • Permalink
Tagged Energy, Environment & Climate
Posted by clalsstaff on September 11, 2017
https://aulablog.net/2017/09/11/chiles-transition-to-clean-energy-matrix/
Chile: Has the Center-Left Really Turned the Page?
By Stefano Palestini Céspedes*
By choosing to support Presidential candidate Alejandro Guillier, the Chilean Socialist Party is turning the page on its ideological platform. / Movilh Chile / Flickr / Creative Commons
The Chilean Socialist Party's rejection of former President and party standard-bearer Ricardo Lagos as its candidate in the Presidential election scheduled for November signals a break with the political program and leadership that it has offered since the end of the Pinochet dictatorship. But the center-left still has a lot to do to sustain its base going into the future. In a secret vote – a process that caused heated discussions and revealed deep divisions between factions of the party – the Central Committee decided to support political newcomer Senator Alejandro Guillier. Already the decision to choose the candidate through a closed-door voting by the leadership, instead of a general consultation as wanted by the party's constituency, prompted José Miguel Insulza (another historic party figure and former Secretary General of the OAS) to withdraw his own candidacy.
The preference for Guillier, a well-known journalist and non-militant of the Socialist Party (PS), has an obvious explanation: the polls. While Guillier ranks second in the polls just behind the center-right candidate – billionaire former President Sebastián Piñera – Lagos remained stuck beneath the threshold of 5 percent. The PS decision cannot be reduced to mere pragmatism, however. Lagos represented continuity with the generation that has represented the center-left since the restoration of democracy, based on market friendly policies with social redistribution. Much of its base has grown disillusioned by the pace of redistribution, however, and combined with dismay over signs of corruption –modest in scale by regional standards but politically embarrassing to the party and to incumbent President Michelle Bachelet – that disenchantment jeopardizes PS prospects moving forward. By following the polls and choosing Guillier, the PS is turning the page of the transition to democracy period.
But the PS may be abandoning its previous ideological platform without a clear idea of what is going to be the new one. The ideological and programmatic orientations behind Guillier's candidacy are unclear. To become the single candidate of the center-left, moreover, Guillier will probably need to compete in primary elections against the candidate of the Christian Democrats. Whoever emerges from that process will compete in November against two rather well defined ideological positions.
The right-wing candidate, Sebastián Piñera, offers a program oriented to undo the progressive reforms undertaken by the Bachelet government, such as reforms of the tax, pension, and education systems. Polls suggest that this program of "neoliberal restoration" may attract centrist voters who, skeptical of the political and social changes associated with those reforms, may prove receptive to Piñera's contention that they are the cause of a recent slowdown in economic growth and tightening of the labor market.
On the opposite end of the spectrum, the leftist coalition Frente Amplio strives to enhance and deepen the reforms; expand social rights and redistribution; and reduce the role of markets, particularly in the educational sector and retirement pensions. In a strategic move, Frente Amplio chose a charismatic journalist (and former radio colleague of Guillier), Beatriz Sánchez, as its candidate. According to polls, she is already attracting support from prospective voters who Guillier would need in order to become Chile's next President.
In selecting Guillier, the center-left is acknowledging the exhaustion of its base with the generation that led the Chilean transition to democracy. Disillusion is particularly deep among younger Chileans who must be a critical foundation for any enduring project of social reform. Party stalwarts like Lagos and Insulza represent precisely the wrong message in that context. But if the center-left is clearly trying to turn the page, to succeed it must define its post-transition programmatic platform — or risk being relegated for the first time since Allende's Unidad Popular to be the third political force after a united right and a united left.
* Stefano Palestini Céspedes is CLALS Research Fellow and Postdoctoral Fellow at the Department of Political and Social Sciences at the Freie Universität Berlin, where he specializes in international organizations and regional governance.
by clalsstaff on April 20, 2017 • Permalink
Tagged Elections, Politics
Posted by clalsstaff on April 20, 2017
https://aulablog.net/2017/04/20/chile-has-the-center-left-really-turned-the-page/
Chile: Between Stability and Uncertainty
By Eduardo Silva and Kenneth Roberts*
Students protest in Santiago, May 2016. A highly-mobilized Chilean civil society has beset Michelle Bachelet's second term as president. / Francisco Osorio / Flickr / Creative Commons
With national elections looming at the end of 2017, President Michelle Bachelet's startling reversal of fortune raises the question of whether the traditional parties' failure to win broad popular support could give rise to an anti-establishment populist leader. At the end of her first government in 2010, Bachelet was the most popular president in post-democratic transition Chile. This go-around, high-profile corruption scandals involving party financing and real estate deals implicating her family (along with both governing and opposition parties) have cut into her support. Irregularities in the electoral registry before the 2016 municipal elections, an ineffective response to devastating forest fires, concessions over major reforms, and a slowing economy have also hurt her approval ratings, which are hovering near 20 percent, the lowest of any president since 1990. Her administration has been beset by protests over education reform, labor relations reform, and the private pension system that the military government established in the 1980s. Tensions and violence flare up continuously over land rights in the south between Mapuche communities and extractive industries. All of this is occurring in a context of marked secular decline in voter participation and political party identification.
The trend of volatile approval ratings and a mobilized civil society now spans three administrations – Bachelet, Sebastián Piñera (2010-2014), and Bachelet again – from 2006 to 2017. Unlike in Brazil and Argentina, where "middle class" revolts demanding clean, efficient government and economic growth signified a rightward turn after prolonged center-left rule, most of the protests in Chile come from the left flank, rather than the right. Moreover, the mainstream parties appear seriously detached from the most active groups in civil society and, as seen in declining levels of party identification, from the citizenry at large. This raises questions about the future of Chile's party system, whether its center-left and center-right coalitions can hold together, and the chances for outsider populists.
All things considered, Chile has been a case of exceptional partisan and electoral stability in Latin America since 1990. The dominant parties and coalitions have won all the elections, without the rise of a major "outsider" populist or a major new "movement party." But the next elections may provide a sort of "in between" outcome. Ex-President Piñera, who has independent tendencies on the right, and a center-left alternative, Alejandro Guillier, are the current frontrunners in presidential primaries scheduled for July. Guillier is a type of insider, nominated by a small party in a large coalition, with outsider credentials who does not really belong to Chile's traditional casta política. At this early point, if Piñera and Guillier win their respective primaries, both would appear to have a shot at winning in November or in December's runoff – with neither outcome representing a breakdown of the system, nor a widespread electoral protest against mainstream parties. This suggests, for now, the continuation of a system that is on the surface highly stable in institutional terms, but in reality highly detached from society at large and in particular from youth and the more active, mobilized sectors of civil society. Neither political coalition shows many signs of significant internal renovation, although Guillier represents at least some change in leadership of the Nueva Mayoría. However, political systems have been known to limp along under these conditions in the absence of major economic meltdowns, and that may be the most likely outcome of the next electoral cycle in Chile.
Tagged Civil Society, Elections, Politics
https://aulablog.net/2017/02/13/chile-between-stability-and-uncertainty/
Structural Reforms in Chile: Moving Forward in Midst of Political Crisis
By Claudia Heiss*
Photo Credit: Chile Ayuda a Chile / Flickr / Creative Commons
Chilean President Michelle Bachelet has done well pushing her reform agenda despite a series of scandals regarding the illegal financing of political campaigns and abuse of power by her daughter-in-law. Bachelet started with 58 percent support and the highest electoral margin of victory since Chile's return to democracy in 1990. Her New Majority coalition incorporated the Communist Party and replaced the Concertación, the center-left coalition defeated in 2010 at the end of her first period, and after 20 years in power. Bachelet's current program reflected a left-turn and an intention to correct perceived flaws of a transition criticized for assuming too many features of the model imposed by the dictatorship. The program included a tax plan to finance education reform introducing free university in a commoditized market of superior education. This project was the offspring of massive student protests in 2011. Another proposal was to replace the dictatorship-era 1980 Constitution through an "institutional, democratic, and participatory" process.
The scandals have hurt Bachelet's popularity – she ended her first term in 2010 with 80 percent support and is now at historical lows below 30 percent – undermined the legitimacy of the political parties and Congress, and prompted a surge of social mobilizations. (Slower economic growth, owing to the low price of copper, has contributed to the government's unpopularity.) But the President has scored some big wins. In addition to the tax and education reforms she sought, the government has achieved important advances in the direction of its political program:
In 2015, a proportional system replaced the Binomial electoral system, which severely distorted popular will in the election of representatives and granted veto power in Congress to the political heirs of the dictatorship.
The campaign finance scandals led to the recent approval of a "Probity Agenda," including higher transparency, forbidding corporate donations to political campaigns, and establishing a new law to regulate political parties.
A bill to make the main regional authority, the Intendente, elective rather than appointed by the President – a major step toward decentralization – has passed the Senate.
The decriminalization of therapeutic abortion, currently punished in only five countries, was approved by the Chamber of Deputies.
Congress is in the final steps of approving a labor reform meant to increase the negotiating power of workers towards their employers.
A complex constitutional reform process was launched last year, and this month the government selected 216 "facilitators" to assist the process and initiated a series of local meetings to discuss constitutional principles, rights, duties, and institutions. The process, the first of its kind ever in Chile, will lead to a presidential proposal to be presented to Congress.
The road ahead will not be easy for President Bachelet and her allies. The political climate is pessimistic, and China's economic troubles suggest the commodity bubble is over – to the detriment of the Chilean economy. While rejected by conservatives, the changes appear as insufficient to those who want more radical reforms. The labor bill has been criticized by union leaders as not allowing enough collective bargaining, and the proposal for constitutional change falls short of a binding participatory process like a Constituent Assembly or a referendum would be. Bachelet, however, has deftly channeled anger about the scandals into the constructive reforms of the Probity Agenda, and she changed the perception of what is achievable in Chile in terms of progressive political and social transformations. While public opinion is currently harsh with the government and with political elites, her second term, which ends in 2018, could in the long run consolidate her legacy as an effective reformer even in the face of adversity.
*Claudia Heiss is Assistant Professor at Universidad de Chile's Instituto de Asuntos Públicos and researcher at the Centre for Social Conflict and Cohesion Studies, COES.
Tagged Accountability & Corruption, Elections, Politics
https://aulablog.net/2016/04/14/structural-reforms-in-chile-moving-forward-in-midst-of-political-crisis/
The Trans-Pacific Partnership: Early Reactions Mixed
By Luciano Melo*
Photo Credit: Bob Nichols (U.S. Department of Agriculture) / Flickr / Creative Commons
The Trans-Pacific Partnership (TPP) agreed to on October 5 is drawing both praise and criticism, but approval by legislatures in some signatory nations – particularly the United States – is not a foregone conclusion. Negotiators representing the 12 Pacific-rim countries involved – including Mexico, Chile, and Peru – hailed the agreement as historic. It is a far-reaching agreement that will expand countries' access to a combined market that represents about 40 percent of global GDP, with 800 million consumers. It seeks to reduce tariffs – including 18,000 on U.S. goods alone – and lower non-tariff trade barriers as well. The negotiators claim the accord also creates a fair compromise framework for protecting intellectual property rights; adopts the strongest-ever labor and environmental protections; and in a novel feature, establishes assistance for small- and medium-sized businesses to navigate the complex regulations and red tape involved in trade. Communist Vietnam is a party to the agreement.
Reactions in Latin America have been mixed:
El Comercio (Peru) wrote that the TPP will help companies to establish better partnerships with the U.S. and Canada, and to create value chains in which Peru will buy commodities from one country, process them, and sell the resulting product to another. How that long-sought and developmentally imperative objective would be achieved through TPP remains vague, however.
El Financiero (Mexico) similarly portrayed the agreement as a means to increase production and foster the specialization of economies. Other Mexican commentators, however, reminded readers that NAFTA and other agreements have not brought the expected results; previous accords have undoubtedly boosted Mexican integration into global and regional manufacturing networks but have actually hurt the agricultural sector – accelerating decades-long migration from the countryside to cities and to the U.S.
Mexican and Chilean experts on the pharmaceutical industry, along with Australian and Asian counterparts, claim that TPP provisions on intellectual property will hinder the generic medications sector. They are concerned the accord will allow large U.S. multinationals to expand into markets with products that cannot be replicated for extended periods time. Chile had negotiated aggressively against Washington's efforts to transplant its laws providing 12-year monopolies to manufacturers of biologic drugs – compromising on a five‑year period extendable under some conditions to eight. The Fundacion Equidad Chile warned that the agreement could cost its health sector about $540 million year more due to such provisions.
Details of the agreement will be made public in coming weeks. While criticism of the secrecy surrounding the accord will naturally fade, substantive debate on its provisions will almost certainly increase amid expensive campaigns by policy advocates on both sides pointing out flaws both real and imagined. But opposition seems relatively weak in the three signatory countries in Latin America, and ratification there appears likely. Chile has long been the region's champion of free trade, and Mexican technocrats appear convinced that trade is key to the country's eventual graduation to high-income status. With the commodity boom waning, Peru is counting on TPP to open avenues into a broader array of industries. In the U.S., however, the path seems rockier. Congress gave Obama "fast-track" authority, which will allow him to submit the agreement to an up or down vote without congressional amendments that would rip it apart, but criticism of TPP persists. Some argue that it strengthens ties with Asian countries with bad records in environment, human rights, and labor laws. An odd twist to the domestic landscape came from presidential aspirant Hillary Clinton, who added her voice to the opposition – putting her on the same side, albeit for different reasons, with Republican opponents who have called TPP a "bad deal." President Obama will have to work hard to sell this new trade agreement to Capitol Hill and the nation.
* Luciano Melo is a PhD candidate at American University's School of Public Affairs specializing in comparative politics.
Posted in Chile, Mexico, Peru
Tagged Trade
https://aulablog.net/2015/10/14/the-trans-pacific-partnership-early-reactions-mixed/
The Untold Story of Manuel Contreras and the CIA
By John Dinges*
The man who designed and executed the massive human rights crimes of Chile's military regime died last week. Manuel Contreras remained a general in Chile's Army even during the last 20 years in prison, with accumulated sentences of more than 500 years imposed by Chilean courts. In the United States, his murky relationship with the CIA and masterminding of a shocking terrorist attack in Washington, dominate perceptions of his record. Contreras, a nondescript, somewhat pudgy man who never tired of boasting about the effectiveness of his anti-subversive campaign, created a security police apparatus, DINA, independent of Chile's military hierarchy. He reported only to General Augusto Pinochet, with whom he met early each morning. DINA was responsible for about half of the 3,200 killed by the Chilean military, and virtually all of the cases of desaparecidos – people detained, tortured and killed in secret interrogation centers, whose bodies were then disposed of in secret graves or dumped into the sea.
Chile was not the most brutal military dictatorship – more than 10,000 Argentines and 200,000 Guatemalans died during that era – but Contreras and Pinochet became the international face of Latin American state terrorism of the 1970s, for various reasons, including their intimate relationship with the United States and in particular with the U.S. Central Intelligence Agency. It is not quite true that the CIA organized the military overthrow in 1973 of socialist president Salvador Allende, but the U.S. embrace of the violent coup was enough to create the widely accepted narrative that the United States brought Pinochet to power and made him a creature of its anti-communist foreign policy, whose global architect was Henry Kissinger. In addition to ruthlessly persecuting political opponents in Chile, DINA carried out a spectacular act of international terrorism in the heart of Washington, D.C. – the 1976 car bomb assassination of Allende's former foreign minister Orlando Letelier, in a blast that also killed an American woman, Ronni Moffitt, and wounded her husband Michael.
Some were quick to see the hand of the CIA in that horrendous crime, a charge that is repeated even today among some writers in Latin America. But these writers may not be aware that Contreras actually promoted the idea of CIA involvement in Chile as a way to mask DINA's crimes. Here, briefly, is what Contreras did to point the finger at the CIA:
Contreras was the first to reveal, in an interview, that the CIA had sent intelligence trainers to Chile to help in the formation of DINA, a fact belatedly confirmed by the CIA to a Congressional investigation.
As his chief international assassin, Contreras hired Michael Townley, a U.S. citizen who had tried to join the CIA as a clandestine agent – a fact unquestionably known to Contreras and now well established in U.S. declassified documents.
Contreras developed a close operational relationship with the CIA, agreeing to provide intelligence in exchange for payment. He is known to have traveled to the United States to consult with top CIA officials at least five times, including with CIA deputy director Vernon Walters in August 1975 – after which he went on to Caracas to lay out his plans for an international assassination alliance, Operation Condor. Whether Contreras briefed Walters on the assassination plans is buried in CIA secrecy.
Contreras used Operation Condor to obtain false documents for Townley and another DINA agent to use in the first phase of the Letelier assassination. With the plot under way, in July 1976, he visited Walters again. Whatever the nature of those conversations (the declassified record is vague), Contreras was again associating himself with the CIA in relation to the impending murder.
When charged with killing Letelier, Contreras pulled out this defense: that the CIA had infiltrated DINA to commit crimes for its own purposes, that Michael Townley was really taking his orders from the CIA, and that the CIA, not DINA, killed Letelier in Washington. That version of events is false, according to my investigations. Nonetheless, the charge of CIA involvement in Operation Condor and Letelier's murder has become a kind of dogma, both on the right and the left. It can be found in the writings of some U.S. academics and is extremely common in narratives of the period in Latin America. Although there is no direct evidence for the charge, the history of CIA intervention, complicity in human rights violations and defense of military dictatorships is enough to convince many people that it must be true. Few of those who believe it are aware they are making common cause with General Contreras, perhaps the most emblematic human rights criminal in Latin America.
*John Dinges teaches journalism at Columbia University. He sorts out the documented, fact-based truth about the U.S. role in "The Condor Years: How Pinochet and his Allies Brought Terrorism to Three Continents" (The New Press 2004).
by clalsstaff on August 12, 2015 • Permalink
Posted in Chile, United States
Tagged Dictatorship, Human Rights, Military
Posted by clalsstaff on August 12, 2015
https://aulablog.net/2015/08/12/the-untold-story-of-manuel-contreras-and-the-cia/
Corruption in Chile and Brazil
By Luciano Melo
Brazilian Pres. Rousseff (l) and Chilean Pres. Bachelet. Photo Credit: UN Women / Flickr / Creative Commons
A growing perception of corruption in Latin America, most recently in Brazil and Chile, is eroding confidence in two of the region's most dynamic presidents – Dilma Rousseff and Michelle Bachelet. The Chilean and Brazilian corruption cases are both serious, but differing perceptions and expectations in the two countries suggest the scandals will have different impacts.
Chile has long been the darling of economists and political scientists (and U.S. policymakers) in terms of democratic maturity, economic development, and transparency. The use of political influence to secure millions of dollars in sweetheart loans there has pulled the country down from its high perch, and since the issue directly touched President Michelle Bachelet's own family members, it has become a huge deal in and outside Chile.
Although among the six main economies in the world and alone among the BRIC countries in boasting a stable democratic system, Brazil, by contrast, has repeatedly been tainted by corruption scandals that would lead to the fall of most Scandinavian governments in a matter of days. Former President Lula's son became a millionaire while his father was in power, yet this fact hardly stained the ex-President's popularity. The scandals weighing down President Dilma Rousseff are different. Brazilian citizens customarily have thought of Petrobras, one of the few remaining state enterprises after the wave of privatizations under President Cardoso during the 1990s, as a great source of national pride, and this sentiment was encouraged by the PT government, never a fan of the neoliberal predilections of its predecessor. So when the scandal touched almost all of the party's leaders, in addition to the prized national oil company, even Brazilians inured to corruption felt pain. Moreover, Lula and Dilma's party, the PT, had promised to do politics in a different way. As a union leader and a woman who fought against the dictatorship, respectively, they represented the rise to power of leaders based entirely outside the traditional parties and their murky ways of doing business. Now, some of Dilma's disillusioned supporters are demanding her impeachment, and many famous artists who once endorsed the PT are feeling betrayed.
Latin American voters have long manifested contrasting expectations of their presidents – cynicism about their venal nature coincided, as Latin America specialist Guillermo O'Donnell once said, with hope that they be "acclaimed saviors." Within the codependent relationship between citizens and politicians, trust is impaired once betrayal surfaces, but the marriage normally continues. In some cases of rupture, as happened with impeached President Fernando Collor in 1992, it hasn't meant the end of the political affair. In the October 2014 elections Collor was reelected as Senator for the state of Alagoas. Dilma and Bachelet have already said they will not resign, and that they intend to implement a comprehensive cleanup. The road will be easier for Bachelet. The Chilean scandal is still small and remains manageable, and although the decline in commodity prices has already affected the country's economy, further taxing Bachelet's popularity, Chile has a sovereign reserve fund to cushion any blows. For Dilma the conjuncture is considerably bleaker. She was on the board of Petrobras while its executives were engaged in costly shenanigans, and it is now known that the fraudulent scheming also involved the Health Ministry and the state-owned bank Caixa Economica Federal. And in Brazil, in contrast to Chile, the fiscal situation is sufficiently tight as to constrain the president's room to maneuver as the commodity-driven economy stagnates. At this point both women appear likely to survive their challenges, but the road ahead looks a lot tougher for Dilma than for Bachelet.
Posted in Brazil, Chile
Tagged Accountability & Corruption
https://aulablog.net/2015/04/16/corruption-in-chile-and-brazil/
Chile Elections: Bachelet's Partial Victory
By Maribel Vasquez and Eric Hershberg
President Michelle Bachelet / Photo credit: Chile Ayuda a Chile / Flickr / CC-BY-NC-ND
Elections last Sunday didn't give former President Michelle Bachelet the strong mandate that she wanted but she appears well positioned to win the second round and the honor of serving a tough second four-year term. An underwhelming number of Chileans headed to the polls to cast their votes for the president of the republic, parliamentarians, and for the regional councilors. Polls had indicated that Bachelet would win convincingly in the first round but, with 46.7 percent of the ballots cast, she fell just short of the 50 percent needed to avoid a run-off election on December 15. Conservative Evelyn Matthei, from the governing right wing Alliance Party, received 25 percent of the vote in the first round and has little chance of winning the run-off: another 17 percent of Chileans voting in the first round opted for candidates running to the left of Bachelet, and observers predict they will either stay home in December or select the former president as a second best option.
A 2012 change in voting law appears to have hurt Bachelet's percentages. Under the new norm, Chileans for the first time were automatically registered to vote in presidential and congressional elections upon reaching 18 years of age, instantly expanding the electorate from eight to 13 million potential voters. But also for the first time, voting was not compulsory, and that proved consequential. In a country where public opinion polls have long shown high levels of alienation from the political system, particularly among younger segments of the population, abstention reached unprecedented heights. Fewer than seven million Chileans turned out to vote on Sunday, representing only around half of those eligible to do so. Turnout was undoubtedly suppressed by the stubborn persistence of Chile's binomial electoral system, a holdover from the Pinochet dictatorship's 1980 Constitution that gives the losing party a bloated presence in Congress (in order to receive both seats in any given district, the winning party or coalition must win double the percentage of the vote received by the runner-up, so frequently even a wide margin between the two top vote getters generates an equal allocation of seats). Bachelet's center-left coalition, the New Majority, has proposed amending the constitution to make the electoral system more reflective of public preferences. But the newly-elected Congress, selected according to the rules of the authoritarian regime, is unlikely to generate the super-majorities needed to achieve constitutional changes that would alter the system so as to democratize congressional representation.
Getting elected to a second four-year term as Chile's president might prove to be the easy part for Bachelet. Harder still will be pushing forward the ambitious policy reforms she has promised. An especially prominent issue in the campaign was the demand of a growing student movement to reform Chile's privatized education system, and Bachelet responded with a pledge to guarantee free, quality higher education to all Chileans, to be funded by a proposed increase in corporate tax rates and elimination of tax deferrals used widely by Chilean companies. Yet while Bachelet's bloc secured the simple majority needed to secure modest tax reform, it fell short of the super majorities needed to secure education reform or change the electoral system or constitution, and the rightist opposition is loath to cede ground on either of these issues, which are also legacies of the Pinochet constitution. To enact the key pillars of her agenda, Bachelet's second presidency will need to calibrate difficult negotiations with Congress with popular pressures to fulfill democratic aspirations for political representation and a more social democratic approach to public services than has been possible to achieve during the first 23 years of post-authoritarian rule.
by clalsstaff on November 22, 2013 • Permalink
Posted by clalsstaff on November 22, 2013
https://aulablog.net/2013/11/22/chile-elections-bachelets-partial-victory/
September 11 Coup in Chile: Global Ramifications
By Eric Hershberg
Chilean Grape export photo by Dick Howe Jr CC-BY-NC Flickr / Indictment of Pinochet, Photo by a-birdie CC-BY-NC Flickr
In Washington last week many events recalled the bloody coup of September 11, 1973, which overthrew the Popular Unity government of Chilean Socialist President Salvador Allende and ushered in a dictatorship that, even by South American standards of the time, stood out for its brutality. Discussion about "the other September 11" highlighted the human cost of the coup, the role of U.S. government agencies in undermining Chilean democracy and encouraging the military's actions, and the memories of the coup and dictatorship that remain deeply embedded in Chile today. These and similar gatherings around the world and in Chile featured demands for the full truth about the dictatorship's crimes – the fate of some thousand of the disappeared remains unknown today, according to the Human Rights Observatory of the Diego Portales University – and to hold those who committed them fully accountable.
The coup led by General Augusto Pinochet destroyed Latin America's longest standing democratic regime and ended a unique experiment testing the proposition that electoral democracy could catalyze a transition to socialism. In Chile, the coup initiated 17 years of military rule grounded in state-sponsored violence, but it also resonated far beyond that country's borders, marking a watershed in global affairs. To this day how people around the world conceive fundamental issues of political change, economic development and human rights is affected by September 11, 1973. These broader legacies were the focus of a panel discussion at American University, co-sponsored by the Center for Latin American Studies and the Washington College of Law, this week. (Click here for details.)
We can now see three large sets of consequences that the Chilean coup had far beyond its borders.
Political: Across Southern Europe, it reverberated powerfully, undermining the confidence of sectors of the Left that believed fervently a socialist transition could be effected through victory at the ballot box. After the coup, Eurocommunists in Italy and Spain came to believe that victory would require an alliance with Christian Democrats or other centrists, lest a coup coalition akin to that in Chile bring down democracy altogether. For much of the Latin American left, the Chilean experience would over time prove a wake-up call, alerting those aspiring to turn the world upside down that democracy was not a mere bourgeois luxury and suggesting that "second-best" options – more gradual change –were preferable to maximalist goals that would likely jeopardize democracy.
Economic: The coup paved the way for "neoliberal" policies that would shake the foundations of conventional thinking about development for nearly three decades. They were prescribed across Latin America. It would not be until the emergence of ALBA in the mid-2000's that the region would again witness a faith (however misguided), in the capacity of import-substitution and inward-oriented redistribution to achieve lasting economic advance in the region.
U.S. policy: Finally, the coup set in train levels of violence and human rights abuses so abhorrent that they drove major changes in U.S. human rights policy and international jurisprudence. In the United States, advocacy organizations, progressive majorities in Congress, and the Carter Administration introduced unprecedented legislation aimed at preserving democracy and curbing human rights abuses. Well beyond Washington, numerous international regimes put in place to combat impunity were motivated and influenced by what had taken place in Chile and the imperative of ensuring that it not happen again.
Just as the cataclysmic event that took place in the U.S. on 9/11/01 opened the door to extreme and ongoing changes felt around the world, so too did the Chilean tragedy that began on 9/11/73.
Tagged Democratic Governance, Dictatorship, Human Rights, Socialism
https://aulablog.net/2013/09/17/september-11-coup-in-chile-global-ramifications/

redpajama_set_name: RedPajamaCommonCrawl


Discussion in 'New Members Say Hello' started by danbar77, Apr 4, 2012.
Its about time i post a hello in here as afterall i am a newbie.
are you a newbie dan..
i thought you would be an oldie by now..
Hi Dan and welcome to this great hobby.
Looks like you are getting to know your way around here. Just don't forget to ask questions. Everyone here is always glad to help out.
And I hope you can get to our mini?
You will find lots of friendly people here that will be glad to help or answer any questions you may have.
OK .. fast forwarding to present day .. resume normal operations.
Oh Hello there Danbar, seems I missed this entry and didn't respond.


Delivering superior customer care and service is crucial to the overall subscriber experience. It's a key moment of truth for CSPs and is essential for building strong customer relationships and loyalty. Customers want to be helped quickly and with the minimum of fuss, without being passed between different agents. CSPs need to equip customer complaints handling teams with the resources to achieve this.
Polystar's Customer Insights solution provides the information customer complaints handling agents and support teams need to identify and isolate customer problems quickly and efficiently. The information is presented and visualised for every customer in the network, allowing agents to view the services used, as well as a customer experience index for every service.
A drill-down workflow enables problems to be isolated and the identification of actions to solve them. As a result, more issues can be solved during the first call, allowing increasing the number of issues that can be handled and reducing the frequency of escalations to second-line agents, saving time and money. This leads to more satisfied customers and a better experience.
Polystar's Customer Insights Solution helps CSPs to improve customer care efficiency, minimise costs and maximise individual subscriber experience.
Increase First Call Resolution by having the right information available for customer care agents, in real–time, presented in a clear and intuitive manner.
Quickly drill-down from service degradation to root cause analysis and pinpoint the location and time of the problem, allowing rapid escalation for resolution.
An end-to-end overview of all services in a single place, allowing degradation to be detected at a glance, and the ability to adapt workflows for each service.
By increasing the efficiency of identifying root causes, the time taken to handle individual issues by each agent is reduced.
First line Customer care agents need tools that help them focus on their customers. They need access to information from different sources so that agents can benefit from a complete, 360º view of subscribers. This is often achieved by the integration of several platforms into a single customer care system. Polystar's Customer Insights solution offers a number of industry-standard methods through which it can be integrated with customer care systems, adding vital information on service usage and customer issues.
The Customer Insights solution can also be deployed as a stand-alone platform, offering portals that are adapted to customer care workflows, with additional drill-down capabilities that unlock rich technical data in the form of reports, statistics, and real-time performance information for second and third-line agents.


In cash basis accounting, income and expenses are recorded as they are received or spent. In accrual basis accounting, income and expenses are charged to an account when they are incurred—in other words, when an order is made. The two types of accounting have different strengths, based on how you spend or receive money. For a business that has inventory, cash basis accounting is usually better. For a business that offers a service and receives payment on a monthly basis or bills for later payment of that service, accrual basis accounting is usually better.