package org.greenstone.atlas.client;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Frame;

public class TemporaryFrame
{
	protected static int _totalIndex = 0;
	
	protected Frame _frame = null;
	
	protected String _url = null;
	protected String _text = null;
	
	protected boolean _doneLoading = false;
	
	protected int _index = _totalIndex++;
	
	public TemporaryFrame(String url)
	{
		_frame = new Frame();
		_frame.setSize("0px", "0px");
		_frame.getElement().getStyle().setProperty("border", "0px");
		
		_url = url;
	}
	
	public void loadPage()
	{
		_frame.setUrl(_url);
		
		Timer loadTimer = new Timer()
		{
			int timerCount = 0;

			public void run()
			{
				if (timerCount++ > 10)
				{
					_doneLoading = true;
					this.cancel();
					return;
				}

				if (GS3MapLibrary.tempFrameGetElementById(_index, "banner") != null && GS3MapLibrary.tempFrameGetElementById(_index, "content") != null && GS3MapLibrary.tempFrameGetElementById(_index, "footer") != null)
				{
					this.cancel();

					JsArray<Element> divs = GS3MapLibrary.tempFrameGetElementsByTagName(_index, "div");

					Element documentTextDiv = null;
					for (int i = 0; i < divs.length(); i++)
					{
						if (divs.get(i).getAttribute("class").equals("documenttext"))
						{
							documentTextDiv = divs.get(i);
							break;
						}
					}

					if (documentTextDiv != null)
					{
						_text = documentTextDiv.getInnerText();
					}
					_doneLoading = true;
				}
			}
		};
		loadTimer.scheduleRepeating(1000);
	}
	
	public boolean isFinishedLoading()
	{
		return _doneLoading;
	}
	
	public static void setCurrentFrameIndex(int index)
	{
		_totalIndex = index;
	}
	
	public void removeFromParent()
	{
		_frame.getElement().getParentElement().removeChild(_frame.getElement());
	}
	
	public Frame getFrame()
	{
		return _frame;
	}
	
	public String getText()
	{
		return _text;
	}
}
