var msie = (/MSIE/.test(navigator.userAgent))
var useScroll = true;
var useScroll = true;
var spreadIndex = 0;
var curpageid = 0;
var overlayalpha = null;
//var zoomoverlay = null;
var pageRatio = null;
var hoverPopup = null;
var regionContainer = null;
var parentElement = null;
var adframe = null;
var corners = [];

document.oncontextmenu = function() {
	return false;
}

function initViewer(parent)
{
    unFocus.History.addEventListener('historyChange', changeByPageNumber);    
    
	parentElement = parent;
	pageRatio = data.spreads[spreadIndex].ratio;
	zoom = new ZoomLayer(viewWidth, viewHeight);
	
	if(data.config.pageflip)
	    createCorners();

	t = new Thumb(data.config.thumbwidth, data.config.thumbheight, data.spreads[spreadIndex].thumb);
	Element.hide(t.element);
	document.body.appendChild(t.element);
	t.setZoomLayer(zoom);
	t.preview.setSize(zoom.width, viewWidth, zoom.height, viewHeight);
	
	parentElement.appendChild(zoom.element);
	swapSpread();
	//	createOverlay();
}

function createCorners() {
    var tl = new Corner(Corner.TOPLEFT);
    corners[Corner.TOPLEFT] = tl;
    zoom.element.appendChild(tl.element);
    
    var tr = new Corner(Corner.TOPRIGHT);
    corners[Corner.TOPRIGHT] = tr;
    zoom.element.appendChild(tr.element);
    
    var bl = new Corner(Corner.BOTTOMLEFT);
    corners[Corner.BOTTOMLEFT] = bl;
    zoom.element.appendChild(bl.element);
    
    var br = new Corner(Corner.BOTTOMRIGHT);
    corners[Corner.BOTTOMRIGHT] = br;
    zoom.element.appendChild(br.element);
}

function Corner(type) {
    
    this.type = type;
    this.state = Corner.DEFAULTSTATE;
    
    this.element = document.createElement('div');
    this.element.className = 'corner';
    
    var img = document.createElement('img');
    this.makeImageUrl(img);
    
    switch(type) {
        case Corner.TOPLEFT:
            this.element.style.left = '0px';
            this.element.style.top = '0px';
            this.element.onclick = prev;
            break;
            
        case Corner.TOPRIGHT:
            this.element.style.right = '0px';
            this.element.style.top = '0px';   
            this.element.onclick = next;
            break;
            
        case Corner.BOTTOMLEFT:
            this.element.style.left = '0px';
            this.element.style.bottom = '0px';
            this.element.onmousedown = prev;
            break;
            
        case Corner.BOTTOMRIGHT:
            this.element.style.right = '0px';
            this.element.style.bottom = '0px';
            this.element.onmousedown = next;
            break;
    }
    
    this.element.appendChild(img);
    
    this.eventUp = this.up.bindAsEventListener(this);
    this.eventDown = this.down.bindAsEventListener(this);
    top.Event.observe(this.element, 'mouseover', this.eventUp);
    top.Event.observe(this.element, 'mouseout', this.eventDown);
}

Corner.TOPLEFT = 0;
Corner.TOPRIGHT = 1;
Corner.BOTTOMLEFT = 2;
Corner.BOTTOMRIGHT = 3;
Corner.DEFAULTSTATE = 0;
Corner.HOVERSTATE = 1;

Corner.prototype.up = function(event) {
    this.state = Corner.HOVERSTATE;
    try {this.element.style.cursor = 'pointer';}
	    catch(e){this.element.style.cursor = 'hand';}
    this.flip(event);
}

Corner.prototype.down = function(event) {
    this.state = Corner.DEFAULTSTATE;
    this.element.style.cursor = '';
    this.flip(event);
}

Corner.prototype.flip = function(event) {
    this.makeImageUrl(this.element.firstChild);
}

Corner.prototype.makeImageUrl = function(img) {
    var url = imageurl + 'corners/';
    var imgname = '';
    
    switch(this.type) {
        case Corner.TOPLEFT:
            imgname = (this.state == Corner.DEFAULTSTATE ? 'corner_tl.png' : 'corner_tl_hover.png');
            break;
            
        case Corner.TOPRIGHT:
            imgname = (this.state == Corner.DEFAULTSTATE ? 'corner_tr.png' : 'corner_tr_hover.png');
            break;
            
        case Corner.BOTTOMLEFT:
            imgname = (this.state == Corner.DEFAULTSTATE ? 'corner_bl.png' : 'corner_bl_hover.png');
            break;
            
        case Corner.BOTTOMRIGHT:
            imgname = (this.state == Corner.DEFAULTSTATE ? 'corner_br.png' : 'corner_br_hover.png');
            break;
    }
    
    url += imgname;
    
    if(!msie) {
        img.src = url;
    } else {
        img.src = imageurl + '/spacer.gif';
        img.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "')";
    }
}

Corner.prototype.setVisible = function(visible) {
    this.element.style.display = (visible ? 'block' : 'none');
}

// history listener, gets triggerd when the location's hash changes
function changeByPageNumber(pageNumber) {
    var i;
    if (pageNumber == '')
    {
        i = 0;
    }
    else
    {
        i=parseInt(pageNumber);
        i = getSpreadIndex(i);
    }
	if(i < data.spreads.length && i >= 0 && i != spreadIndex) {
		spreadIndex = i;
		swapSpread();
	}
}

function doZoom(e) {
	if(zoom && zoom.slider && zoom.slider.getValue() == 0) {
	
		var left = e.clientX - parentElement.offsetLeft;
		var top = e.clientY - parentElement.offsetTop;
		
		zoom.zoom(left, top, true);
	}
}

/*** ZoomLayer 'class' ***/
function ZoomLayer(width, height) {
	
	this.flashList = new Array();

	this.element = document.createElement('div');
	this.element.className = 'zoomdiv';
	this.element.obj = this;
	
	this.thumbNail = null;
	
	this.slider = new Slider($('sliderdiv'));
	this.slider.setMaximum(zoomLevels.length-1);
	this.slider.setHandle(sliderhandle);
	
	this.slider.parentObj = this;
	
	this.slider.onchange = function() {
		var p = this.parentObj;
		
		val = this.getValue();
		
		var oldWidth = this.parentObj.width;
		var oldHeight = this.parentObj.height;

		var scrollX = p.element.parentNode.scrollLeft;
		var scrollY = p.element.parentNode.scrollTop;
		
		if(adframe != null) {
			adframe.parentNode.removeChild(adframe);
			adframe = null;
		}
		if(val == 0) {
			showAdPage();
		}
		
		p.setSize(viewWidth * zoomLevels[val], val == 0 ? viewHeight : null);
		p.removeFlash();
		p.setFlash();
				
		scrollX = (scrollX * (p.width / oldWidth));
		scrollY = (scrollY * (p.height / oldHeight));
		
		p.setPosition(scrollX, scrollY);			
		
		createRegions();
		
		if(p.thumbNail){
			p.thumbNail.preview.setSize(p.width, viewWidth, p.height, viewHeight);
			if(!val) {
				Element.hide(p.thumbNail.element);
				p.thumbNail.preview.setPosition(0,0);
			}
			else {
				Element.show(p.thumbNail.element);
				p.thumbNail.preview.setPosition(this.parentObj.element.parentNode.scrollTop, this.parentObj.element.parentNode.scrollLeft);
			}
		}
		setButtons();
	}
	
	
	this.setSize(width, height);
	
	this.eventMouseDown = this.startDrag.bindAsEventListener(this);
	this.eventMouseUp = this.endDrag.bindAsEventListener(this);
	this.eventMouseMove = this.move.bindAsEventListener(this);	
	this.eventMouseOut = this.endDrag.bindAsEventListener(this);
	this.eventScrollWheel = this.wheelScroll.bindAsEventListener(this);
	
	top.Event.observe(this.element, "mousedown", this.eventMouseDown);
	top.Event.observe(document, "mouseup", this.eventMouseUp);
	top.Event.observe(document, "mousemove", this.eventMouseMove);
	top.Event.observe(this.element, "mouseout", this.eventMouseOut);
	
	var eventName = msie ? "mousewheel" : "DOMMouseScroll";
	top.Event.observe(this.element, eventName, this.eventScrollWheel);
}

ZoomLayer.prototype.wheelScroll = function(event) {
	this.updatePosition(0, event.wheelDelta || (event.detail * -40));
}

ZoomLayer.prototype.startDrag = function(event) {
	if(Event.isLeftClick(event)) {
		this.drag = true;
		this.tx = 0;
		this.ty = 0;
	}
}

ZoomLayer.prototype.move = function(event) {
	if(this.drag) {		
		var x = Event.pointerX(event);
		var y = Event.pointerY(event);
		
		if(this.tx == 0 || this.ty == 0) {
			this.tx = x;
			this.ty = y;
		}
		var changeX = x - this.tx;
		var changeY = y - this.ty;
		this.updatePosition(changeX*3, changeY*3);
		this.tx = x;
		this.ty = y;
	}
}

ZoomLayer.prototype.endDrag = function(event) {
	this.drag = false;
}

ZoomLayer.prototype.setSize = function(width, height) {

	if(this.slider.getValue() == 0 && (width * pageRatio) > viewHeight)
		width = Math.ceil(viewHeight / pageRatio);
				
	if(width % 2 == 1)
		width--;
		
	this.width = data.spreads[spreadIndex].isspread ? width : width/2;
	
	var left = 0;
	if(this.slider.getValue() == 0) {
		if(!data.spreads[spreadIndex].isspread && data.spreads[spreadIndex].inlinepagead.containsad) {
			if(data.spreads[spreadIndex].inlinepagead.side == 'left') {
				left = viewWidth/2;
			}
			else {
				left = (viewWidth - (this.width*2)) / 2;
			}
		}
		else {
			left = (viewWidth - this.width) / 2;
		}
	}
	
	this.element.style.width = this.width + 'px';
	this.element.style.left = left + 'px';
	
    var rat = data.spreads[spreadIndex].isspread ? pageRatio : pageRatio * 2;
	this.height = Math.ceil(this.width * rat);
	
	this.element.style.height = this.height + 'px';
		
	$('overlay').style.display = this.slider.getValue() == 0 ? 'block' : 'none';
}

ZoomLayer.prototype.setFlash = function() {
	var salign = data.spreads[spreadIndex].isspread ? 'TR' : 'T';
	var w = data.spreads[spreadIndex].isspread ? this.width/2 : this.width;
	var flash1 = new Flash(this.element, data.spreads[spreadIndex].left, 'zoomflash1', salign, w);
	this.flashList.push(flash1);
		
	if(data.spreads[spreadIndex].isspread){
		var flash2 = new Flash(this.element, data.spreads[spreadIndex].right, 'zoomflash2', 'TL', this.width/2);
		this.flashList.push(flash2);
	}
	
	//createOverlay();
}

ZoomLayer.prototype.removeFlash = function() {
	var len = this.flashList.length;
	var oldtitle = document.title; //WEIRD ie bug (see http://blog.ilikeu2.nl/2006/09/15/flash-hashes-and-ms-ie-bug/)
	for(var i = 0; i < len; i++) {
		this.element.removeChild(this.flashList[i].element);
	}
			
	this.flashList = new Array();
	document.title = oldtitle;
}

ZoomLayer.prototype.update = function() {
	var val = this.slider.getValue();
	
	this.setSize(viewWidth * zoomLevels[val], val == 0 ? viewHeight : null)
}

ZoomLayer.prototype.setThumbnail = function(t) {
	this.thumbNail = t;
}

ZoomLayer.prototype.updatePosition = function(x, y) {

	var sl = this.element.parentNode.scrollLeft - x;
	var st = this.element.parentNode.scrollTop - y;
	
	this.setPosition(sl, st);
	if(this.thumbNail)
		this.thumbNail.preview.setPosition(st, sl);
}

ZoomLayer.prototype.setPosition = function(x, y) {
	this.element.parentNode.scrollLeft = x;
	this.element.parentNode.scrollTop = y;
}

ZoomLayer.prototype.zoom = function(left, top, center) {
	var overflowX = (viewWidth-this.width)/2;
	var overflowY = (viewHeight-this.height)/2;	

	left -= (overflowX > 0 ? overflowX : 0);
	top -= (overflowY > 0 ? overflowY : 0);
	
	this.slider.setValue(DEFAULTLEVEL);	
	var ratio = Math.max(this.height/viewHeight, this.width/viewWidth);
	
	if(center) {
		this.setPosition((ratio * left) - (viewWidth/2), (ratio * top) - viewHeight/2);
	}
	else {
		this.setPosition((ratio * left), (ratio * top));
	}
	
	this.thumbNail.preview.setPosition(parentElement.scrollTop, parentElement.scrollLeft);
}
/*** end ZoomLayer ***/
function Flash(par, name, id, align, width, height)
{
	if(!height)
		height = '100%';

    this.element = document.createElement('span');
    this.element.id = id;
	this.element.className = 'loading';	
	par.appendChild(this.element);
		
	fo = new SWFObject(name, "page" + id, width, height, "6");
	fo.addParam("wmode", "transparent");
	fo.addParam("salign", align);
	fo.write(id);	
	
	//workaround for flash messing up the title bar..
	var hashPos = document.title.indexOf('#');
	if(hashPos > 0)
	    document.title = document.title.substring(0, hashPos)
}

/*** thumb 'class' ***/
function Thumb(width, height, img) {
	this.zoom = null;
	
	this.element = document.createElement('div');
	this.element.id = 'thumbbox';
	this.element.className = 'thumbbox';
	this.element.obj = this;
	
	this.setSize(width, height);
	
	this.image = new ThumbImage(img);
	this.element.appendChild(this.image.element);
	
	this.preview = new PreviewBox(this);
}

Thumb.prototype.setSize = function(width, height) {
	this.width = width;
	this.height = height;
	
	this.element.style.height = this.height + 'px';
	this.element.style.width = this.width + 'px';
}

Thumb.prototype.setZoomLayer = function(zooml) {
	this.zoom = zooml;
	zooml.setThumbnail(this);
}
/*** end thumb 'class' ***/	

/*** thumbimage 'class' ***/
function ThumbImage(img) {
	this.element = document.createElement('img');
	this.element.src = img;
	this.element.border = 0;
	this.element.style.height = '100%';
	this.element.style.width = '100%';
	
	this.element.onselectstart = function(){
		return false;
	}
}

ThumbImage.prototype.setImage = function(img) {
	this.element.src = img;
}
/*** end thumbimage 'class' ***/


/*** previewBox 'class' ***/
function PreviewBox(parent) {
	this.parent = parent;
	this.element = document.createElement('div');
	this.element.id = 'previewbox';
	this.element.className = 'previewbox';
	this.element.obj = this;
	parent.element.appendChild(this.element);
	
	this.element.appendChild(document.createElement('div'));

	this.active = false;
			
	this.eventMouseDown = this.startDrag.bindAsEventListener(this);
	this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
	this.eventMouseMove = this.update.bindAsEventListener(this);
	
	top.Event.observe(this.element, "mousedown", this.eventMouseDown);
    top.Event.observe(document, "mouseup", this.eventMouseUp);
    top.Event.observe(document, "mousemove", this.eventMouseMove);	
    top.Event.observe(this.parent.element, "mouseout", this.eventMouseUp);	
	
	this.element.onselectstart = function() {
		return false;
	}
}

PreviewBox.prototype.startDrag = function(event) {
	this.drag = true;

	this.tx = Event.pointerX(event) - parseInt(this.element.offsetLeft);
	this.ty = Event.pointerY(event) - parseInt(this.element.offsetTop);
}

PreviewBox.prototype.endDrag = function(event) {
	if(this.drag)
	{
		var x = Event.pointerX(event);
		var y = Event.pointerY(event);
						
		y = (y - this.ty);
		x = (x - this.tx);
						
		if(y < 0)
			y = 0;
		if(x < 0)
			x = 0;
		if(y > (this.parent.height - parseInt(this.element.style.height)))
			y = this.parent.height - parseInt(this.element.style.height);
		if(x > (this.parent.width - parseInt(this.element.style.width)))
			x = this.parent.width - parseInt(this.element.style.width);
		this.element.style.top = y + 'px';
		this.element.style.left = x + 'px';
		
		var tox = Math.floor((x / parseInt(this.parent.width)) * this.fullWidth);
		var toy = Math.floor((y / parseInt(this.parent.height)) * this.fullHeight);
		this.parent.zoom.setPosition(tox, toy);
	}
	this.drag = false;	
}

PreviewBox.prototype.update = function(event) {
	if(this.drag) {
		var x = Event.pointerX(event);
		var y = Event.pointerY(event);
						
		y = (y - this.ty);
		x = (x - this.tx);
		
		if(y < 0)
			y = 0;
		if(x < 0)
			x = 0;
		if(y > (this.parent.height - parseInt(this.element.style.height)))
			y = this.parent.height - parseInt(this.element.style.height);
		if(x > (this.parent.width - parseInt(this.element.style.width)))
			x = this.parent.width - parseInt(this.element.style.width);
		
		this.element.style.top = y + 'px';		
		this.element.style.left = x + 'px';
		
		var tox = Math.floor((x / parseInt(this.parent.width)) * this.fullWidth);
		var toy = Math.floor((y / parseInt(this.parent.height)) * this.fullHeight);
	}	
}

PreviewBox.prototype.dispose = function() {
    Event.stopObserving(this.element, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
}

PreviewBox.prototype.setSize = function(fullWidth, visibleWidth, fullHeight, visibleHeight) {
	this.fullWidth = fullWidth;
	this.fullHeight = fullHeight;

	this.element.style.width = (Math.floor(visibleWidth/fullWidth * this.parent.width) + 'px');
	this.element.style.height = (Math.floor(visibleHeight/fullHeight * this.parent.height) + 'px');
}
	
PreviewBox.prototype.setPosition = function(top, left) {

	this.top = Math.ceil((this.parent.height / this.fullHeight) * top);
	this.left = Math.ceil((this.parent.width / this.fullWidth) * left);
	
	if(this.top + this.element.offsetHeight > this.parent.height)
		this.top = this.parent.height - this.element.offsetHeight;
	if(this.top < 0)
		this.top = 0;
		
	if(this.left + this.element.offsetWidth > this.parent.width)
		this.left = this.parent.width - this.element.offsetWidth;
	if(this.left < 0)
		this.left = 0;
		
	if(this.element.offsetWidth > this.parent.width)
		this.element.style.width = this.parent.width;
		
	this.element.style.top = this.top + 'px';
	this.element.style.left = this.left + 'px';
}

/*** end previewBox 'class' ***/

function RegionContainer() {
	
	this.regionList = new Array();
	this.element = document.createElement('div');
	this.element.id = 'regioncontainer';
	
	this.element.obj = this;
	
	var span = document.createElement('span');
	span.style.width = '100%';
	span.style.height = '100%';
	
	this.element.appendChild(span);
	
	this.element.onmouseover = function() {
		var popup = hoverPopup;
		if(popup)
			popup.hide();
		
		var overlay = $('overlayalpha');
		if(overlay) {
			overlay.style.top = '-1000px';
			overlay.style.left = '-1000px';
		}
	
		var list = this.obj.regionList;
		for(var i = 0; i < list.length; i++){
			list[i].popuptimer = true;
			if(list[i].element && list[i].element.timeout)
				clearTimeout(list[i].element.timeout);
		}
	}
	
	this.element.onmousedown = function(e) {
		e = e || event;
		if(e.button == 2) 
		{
			// right button..
			if(zoom.slider.getValue() == 0)
				doZoom(e);
			else swapSpread();
		}
	}
}

RegionContainer.prototype.addRegion = function(region) {
	this.regionList.push(region);
	this.element.appendChild(region.element);	
}

RegionContainer.prototype.clear = function() {
	if(this.regionList != null && this.regionList.length > 0)
	{
		for(var i = 0; i < this.regionList.length; i++) {
			this.element.removeChild(this.regionList[i].element);
			this.regionList[i].element = null;
			delete this.regionList[i].element;
		}
		
		this.regionList = new Array();
	}
}

/*** Region 'class' ***/
function Region(id, l, t, r, b) {
	var ratio = zoom.width / 10000;

	this.left = l;
	this.top = t;
	this.right = r;
	this.bottom = b;
	
	this.title = '';
	this.summary = '';
	this.actions = [];
	this.popup = false;
	this.popuptimer = true;
	this.allowActions = true;
	
	this.element = document.createElement('div');
	this.element.id = 'region' + id;
	
	var offL = zoom.element.offsetLeft;
	var offT = zoom.element.offsetTop;
	
	this.screenwidth = Math.abs((this.right * ratio) - (this.left * ratio));
	this.screenheight =  Math.abs((this.bottom  * ratio) - (this.top * ratio));
	//this.screentop = this.top * ratio + offT;
	//this.screenleft = this.left * ratio + offL;
	this.screentop = this.top * ratio;
	this.screenleft = this.left * ratio;
	
	this.element.style.overflow = 'hidden';
	
	try {this.element.style.cursor = 'pointer';}
	catch(e){this.element.style.cursor = 'hand';}
	
	this.element.style.position = 'absolute';
	this.element.style.left = this.screenleft + 'px';
	this.element.style.top = this.screentop + 'px';
	this.element.style.width = this.screenwidth + 'px';
	this.element.style.height = this.screenheight + 'px';
	
	var span = document.createElement('span');
	span.style.width = '100%';
	span.style.height = '100%';
	this.element.appendChild(span);
	
	this.element.obj = this;
	
	this.element.onmouseover = function(e) {
		e = e || event;
		log('region mouseover');
	
		if(this.obj.allowActions) {
			var overlay = $('overlayalpha');
			
			overlay.style.width = this.obj.screenwidth + 'px';
			overlay.style.height = this.obj.screenheight + 'px';

			overlay.style.top = this.obj.screentop + 'px';
			overlay.style.left = this.obj.screenleft + 'px';
		}
		
		e.cancelBubble = true;
	}
	
	this.element.onmousemove = function(e) {
		e = e || event;
		
		if(this.obj.popup && this.obj.allowActions){
			clearTimeout(this.timeout);
			
			this.mouseX = e.clientX;
			this.mouseY = e.clientY;
			
			if(this.obj.popuptimer)
			{
				var self = this.obj;
				//self.showPopup();
				this.timeout = window.setTimeout(function() {
					self.showPopup();
				}, 200);
			}			
		}
		
		e.cancelBubble = true;
	}
}

Region.prototype.setTitle = function(title){
	if(title)
		this.title = title;
	this.popup = this.title.length > 0 || this.summary.length > 0 || this.actions.length > 0;
}

Region.prototype.setSummary = function(summary) {
	if(summary)
		this.summary = summary;
	this.popup = this.title.length > 0 || this.summary.length > 0 || this.actions.length > 0;
}

Region.prototype.setActions = function(actions) {
	if(actions)
		this.actions = actions;
	this.popup = this.title.length > 0 || this.summary.length > 0 || this.actions.length > 0;
}

Region.prototype.setInlineContent = function(inlinecontent) {
	if(inlinecontent) {
		this.element.innerHTML = '<iframe src="' + inlinecontent + '" width="100%" height="100%" scrolling="no" frameborder="0" border="0" allowtransparency="true" background-color="transparent"></iframe>';
		this.allowActions = false;
	}
}

Region.prototype.showPopup = function() {
	if(this.allowActions) {
		var popup = hoverPopup;
				
		popup.setTitle(this.title);
		popup.setSummary(this.summary);
		
		popup.clearActions();
		
		for(var i = 0; i < this.actions.length; i++) {
			popup.addAction(this.actions[i].action, this.actions[i].icon, this.actions[i].title);
		}
		
		if(this.element) {
			log(this.element.mouseX, this.element.mouseY);
			popup.show(this.element.mouseX, this.element.mouseY);
		}
		this.popuptimer = false;
	}
}

/*** end Region 'class' ***/

function Overlay() {
	this.element = document.createElement('div');
	this.element.id = 'overlayalpha';
	this.element.className = 'overlayalpha';
}

function HoverPopup(){
	this.element = $('info');
	this.titlediv = $('infoheadtext');
	this.summarydiv = $('infobody');
	this.actionsdiv = $('infoicons');
	
	this.element.obj = this;
	this.active = false;
	
	
	this.element.onmouseover = function(e) {
		e = e || event;
		this.obj.active = true;
		e.cancelBubble = true;
	}
	
	this.element.onmousemove = function(e) {
		e = e || event;
		e.cancelBubble = true;
	}
	
	this.element.onmouseout = function(e) {
		e = e || event;
		this.obj.active = false;
		e.cancelBubble = true;
	}
}

HoverPopup.prototype.show = function(x, y) {
	//log(x, y);
	if(!this.visible)
	{
		this.maxx = document.body.clientWidth - 6;
		this.maxy = document.body.clientHeight - 43;
		this.top = getOffsetTop(zoom.element);;
		this.left = parentElement.offsetLeft;
		this.width = this.element.offsetWidth;
		this.height = this.element.offsetHeight;
		this.visible = true;
	}
	var t = (y - this.top);
	var l = (x - this.left);

	if((x + this.width) > this.maxx)
		l -= this.width;
		
	if((t + this.height) > this.maxy)
		t -= this.height;

	this.actionsdiv.style.width = this.summarydiv.style.display == 'block' ? '27px' : '100%';
	this.actionsdiv.style.borderTopWidth = this.summarydiv.style.display == 'block' ? '1px' : '0px';
	
	if(this.summarydiv.style.display == 'block') {
		var actionw = this.actionsdiv.offsetHeight;
		var summw = this.summarydiv.offsetHeight;
		
		if(actionw > summw)
			this.summarydiv.style.height = actionw;
	}

	this.element.style.top = t + zoom.element.parentNode.scrollTop + 'px';
	this.element.style.left = l + zoom.element.parentNode.scrollLeft + 'px';
	
	log(this.element.style.top, this.element.style.left);
}

HoverPopup.prototype.hide = function(){
	this.element.style.top = '-1000px';
	this.element.style.left = '-1000px';
	this.visible = false;
}

HoverPopup.prototype.setTitle = function(text) {
	this.titlediv.parentNode.style.display = (text != '' ? 'block' : 'none');
	this.titlediv.innerHTML = text;
}

HoverPopup.prototype.setSummary = function(text) {
	this.summarydiv.style.display = (text != '' ? 'block' : 'none');
	this.summarydiv.innerHTML = text;
}

HoverPopup.prototype.clearActions = function() {
	this.actionsdiv.innerHTML = '';
}

HoverPopup.prototype.addAction = function(action, icon, title) {
	var anchor = document.createElement('a');
	anchor.href = 'javascript: ' +action;
	
	var img = document.createElement('img');
	img.src = icon;
	img.title = title;
	
	anchor.appendChild(img);
	
	if(this.summarydiv.style.display == 'none')
		anchor.appendChild(document.createTextNode(title));
	
	this.actionsdiv.appendChild(anchor);
}

function next() {
	if(spreadIndex < data.spreads.length-1) {
	    unFocus.History.addHistory(getPageOnNextSpread(spreadIndex));
	}
}

function prev() {
	if(spreadIndex > 0) {
		unFocus.History.addHistory(getPageOnPreviousSpread(spreadIndex));
	}
}

function last() {
	if(spreadIndex < data.spreads.length - 1){
		spreadIndex = data.spreads.length - 1;
		swapSpread();
	}
}

function first() {	
	if(spreadIndex > 0) {
		spreadIndex = 0;
		swapSpread();
	}
}

function zoomIn() {
	var val = zoom.slider.getValue() + 1;
	if(val < zoomLevels.length)
		zoom.slider.setValue(val);
}

function zoomOut() {
	var val = zoom.slider.getValue() - 1;	
	if(val >= 0)
		zoom.slider.setValue(val);
}

function swapSpread() {

	pageRatio = data.spreads[spreadIndex].ratio;
	if(zoom.slider) {
		zoom.slider.setValue(0);
		zoom.update();
		zoom.removeFlash();
		zoom.setFlash();
			
		if(t) 
		{
			t.setSize(data.spreads[spreadIndex].thumbwidth, data.spreads[spreadIndex].thumbheight);
			t.image.setImage(data.spreads[spreadIndex].thumb);
			t.preview.setSize(zoom.width, viewWidth, zoom.height, viewHeight);
		}

		$('pageName').innerHTML = data.spreads[spreadIndex].title;
		$('pagelog').innerHTML = '<img src="' + data.spreads[spreadIndex].pageurl + '" />';
		createRegions();
		createCookie("pageid", data.spreads[spreadIndex].id, 0);
		curpageid = data.spreads[spreadIndex].id;
		if (typeof(urchinTracker) != 'undefined')
		{
            _org_title = _ubd.title;
            _ubd.title = issueTitle + "/" + data.spreads[spreadIndex].title;
            urchinTracker('/republisher/pageviews/' + issueId  + "/" + curpageid);
		    _ubd.title = _org_title;
		}
		
		// make all pageflip corners visible
		for(var i = 0; i < corners.length; i++)
            corners[i].setVisible(true);

        // hide pageflip corners for non-spread pages.
        if(data.config.pageflip) {
	        if(!data.spreads[spreadIndex].isspread) {
	            if(spreadIndex == 0) {
	                corners[Corner.TOPLEFT].setVisible(false);
	                corners[Corner.BOTTOMLEFT].setVisible(false);
	            }		    
	            else if(spreadIndex == data.spreads.length-1) {
	                corners[Corner.TOPRIGHT].setVisible(false);
	                corners[Corner.BOTTOMRIGHT].setVisible(false);
	            }
	        }
        	
	        corners[Corner.TOPLEFT].setVisible(false);
	        corners[Corner.TOPRIGHT].setVisible(false);
	    }
		
		setButtons();
	}
	// ad page
	if(adframe) {
		adframe.parentNode.removeChild(adframe);
		adframe = null;
	}
	if(data.spreads[spreadIndex].inlinepagead.containsad &&
		!data.spreads[spreadIndex].isspread
		&& adframe == null) {
		var iframe = document.createElement('iframe');
		iframe.src = data.spreads[spreadIndex].inlinepagead.adpage;
		iframe.style.width = viewWidth/2 + 'px';
		iframe.style.height = viewHeight + 'px';
		iframe.style.position = 'absolute';
		iframe.style.top = '0px';
		if(data.spreads[spreadIndex].inlinepagead.side == 'left'){
			iframe.style.left = '0px';
		}
		else {
			iframe.style.left = (parentElement.offsetWidth/2) + 'px';
		}
		iframe.frameBorder = 'no';
		parentElement.appendChild(iframe);
		
		adframe = iframe;
	}
	showAdPage();
}

function showAdPage() {
	// ad page
	if(adframe) {
		adframe.parentNode.removeChild(adframe);
		adframe = null;
	}
	if(data.spreads[spreadIndex].inlinepagead.containsad &&
		!data.spreads[spreadIndex].isspread
		&& adframe == null) {
		var iframe = document.createElement('iframe');
		iframe.src = data.spreads[spreadIndex].inlinepagead.adpage;
		iframe.style.width = viewWidth/2 + 'px';
		iframe.style.height = viewHeight + 'px';
		iframe.style.position = 'absolute';
		iframe.style.top = '0px';
		if(data.spreads[spreadIndex].inlinepagead.side == 'left'){
			iframe.style.left = '0px';
		}
		else {
			iframe.style.left = (parentElement.offsetWidth/2) + 'px';
		}
		iframe.frameBorder = 'no';
		parentElement.appendChild(iframe);
		
		adframe = iframe;
	}
}

function createRegions() {
	if(regionContainer == null){
		regionContainer = new RegionContainer();
		//zoom.element.parentNode.appendChild(regionContainer.element);
		zoom.element.appendChild(regionContainer.element);
	}
	regionContainer.clear();
	
	if(overlayalpha == null){
		overlayalpha = new Overlay();
		regionContainer.element.appendChild(overlayalpha.element);
	}
	
	if(hoverPopup == null){
		hoverPopup = new HoverPopup();
		//regionContainer.element.appendChild(hoverPopup.element);
		parentElement.appendChild(hoverPopup.element);
	}
	else hoverPopup.hide();
	
	var regions = data.spreads[spreadIndex].regions;	
	for(var i = 0; i < regions.length; i++) {
		if(regions[i]){
			var reg = new Region(regions[i].id, regions[i].left, regions[i].top, regions[i].right, regions[i].bottom);
			reg.setTitle(regions[i].title);
			reg.setSummary(regions[i].summary);
			reg.setActions(regions[i].actions);
			reg.element.onclick = regions[i].click;
			
			reg.setInlineContent(regions[i].inlinecontent);
			
			regionContainer.addRegion(reg);
		}
	}
	//regionContainer.element.removeChild(hoverPopup.element);
	//regionContainer.element.appendChild(hoverPopup.element);
	parentElement.removeChild(hoverPopup.element);
	parentElement.appendChild(hoverPopup.element);
}

function getOffsetTop(obj){
	var tmp=0;
	while(obj.offsetParent!=null){
		tmp+=obj.offsetTop;
		obj=obj.offsetParent;
	}
	return tmp;
}

function getOffsetLeft(obj){
	var tmp=0;
	while(obj.offsetParent!=null){
		tmp+=obj.offsetLeft;
		obj=obj.offsetParent;
	}
	return tmp;
}

function log(a, b) {
	var log = $('log');
	log.innerHTML = 'x: ' + a + ' y: ' + b;
}

function setButtons() {
	navbuttons[0].setEnabled(spreadIndex != 0);
	navbuttons[1].setEnabled(spreadIndex != 0);
	navbuttons[2].setEnabled(spreadIndex != data.spreads.length-1);
	navbuttons[3].setEnabled(spreadIndex != data.spreads.length-1);
	
	if (spreadIndex == 0)
	{
	    navbuttons[0].setHref('');
	    navbuttons[1].setHref('');
	}
	else
	{
	    navbuttons[0].setHref(1);
	    navbuttons[1].setHref(getPageOnPreviousSpread(spreadIndex));
	}
	
	if (spreadIndex == data.spreads.length-1)
	{
	    navbuttons[3].setHref('');
	    navbuttons[2].setHref('');
	}
	else
	{
	    navbuttons[2].setHref(getPageOnNextSpread(spreadIndex));
	    navbuttons[3].setHref(pageNumbers.length -1);
	}
	
	if(zoom) {
		navbuttons[4].setEnabled(zoom.slider.getValue() > 0);
		navbuttons[5].setEnabled(zoom.slider.getValue() != zoomLevels.length-1);
	}
}

function resize() {
	setDimensions();
	swapSpread();
}

function setDimensions() {
	var nextprev = document.getElementById('nextprev');
	var npw = nextprev.parentNode.clientWidth;
	nextprev.style.left = ((npw/2) - (nextprev.clientWidth/2)) + 'px';
	
	var divpages = document.getElementById('divpages');
	
	viewWidth = document.body.clientWidth - 20;
	viewHeight = document.body.clientHeight - 43;
	
	divpages.style.height = viewHeight + 'px';
	divpages.style.width = viewWidth + 'px';
	
	var el = dynObj.getElemRef(obj1.id);
	if (el)
		el.style.height = viewHeight + 'px';
		
	if(t && zoom) {
		val = zoom.slider.getValue();
		if(val == 0)
			zoom.setSize(viewWidth, viewHeight);
		else
			zoom.setSize(viewWidth * zoomLevels[val]);
		t.preview.setSize(zoom.width, divpages.clientWidth, zoom.height, divpages.clientHeight);
	}
}

function doSlide() {
	if(obj1) {
		var speed = document.all ? 500 : 0;
		obj1.slideTo(6, null, speed, -1);
		slidestatus = 1;
	}
}

function doClose(e) {
	e = e || window.event;
	if(slidestatus == 1 && obj1) {
		if(e){
			Event.stop(e);
			e.cancelBubble = true;
		}
		slidestatus = 0;
		var speed = document.all ? 300 : 0;
		obj1.slideTo( -(obj1.w - obj1.xOff), null, speed, -1);
	}	
}

