var imageViewer = new photoBrowser();

var RESIZE_MOTION_STEP = 10; //the amount of pixels to step each frame when resizing the window - higher is faster;
var RESIZE_MOTION_SPEED = 10; //the time between each frame of the resize motion tween - lower is faster
var LOADING_GIF = "../images/loading.gif"; //gif to display when loading an image..
var CLOSE_IMAGE = "../images/closePopupIcon.jpg";
var LEFT_ARROW_IMAGE = "../images/arrowLeft.jpg";
var RIGHT_ARROW_IMAGE = "../images/arrowRight.jpg";

var EXCESS_HEIGHT = 120;
var EXCESS_WIDTH = 20;

var MINIMUM_WIDTH = 300;
var MINIMUM_HEIGHT = 200;

function photoBrowser() {

	var mySelf = this;

	this.popupDiv = null;

	this.errorContainer = null;
	this.imageContainer = null;
	this.titleContainer = null;
	this.commentContainer = null;
	this.nextContainer = null;
	this.previousContainer = null;
	this.imageElement = null;
	this.loadingElement = null;

	this.imageID;
	this.nextImageIndex = "";
	this.previousImageIndex = "";
	this.currentImageIndex = '1'; //init as imageIndex 1

	this.targetWidth = 0;
	this.targetHeight = 0;
	this.imageLoaded = false;
	this.atWDestination = false;
	this.atVDestination = false;

	//public functions
	//----------------------------------
	this.popupBrowser = popupBrowser;
	this.nextPhoto = nextPhoto;
	this.previousPhoto = previousPhoto;
	this.closeBrowser = closeBrowser;
	//----------------------------------

	//popup the image browser, showing the image and comments related to 'photoId'
	function popupBrowser(photoId, photoIndex) {
		mySelf.imageID = photoId; //the photo id is the same for the set of photos for this product
		mySelf.currentImageIndex = photoIndex;
	    if (mySelf.popupDiv == null) {
	        mySelf.popupDiv = createPopupDiv(document.body.offsetWidth/2 - 250, 150, 500, 500);
	        document.body.appendChild(mySelf.popupDiv);

			var closeButton = document.createElement('img');
			var closeButtonAnchor = document.createElement('a');
			closeButton.src = CLOSE_IMAGE;
			closeButton.style.position = "absolute";
			closeButton.style.right = "2px";
			closeButton.style.top = "2px";
			closeButton.style.border = "0px";
			closeButtonAnchor.onclick = closeBrowser;
			closeButtonAnchor.href = "#";
			closeButtonAnchor.title = "Close";
			closeButtonAnchor.appendChild(closeButton);

			var table = document.createElement('table');
			table.style.width = "100%";
			table.style.border = "0px";
			table.setAttribute('cellPadding', '0');
			table.setAttribute('cellSpacing', '0');

			objRow = table.insertRow(table.rows.length);
			mySelf.titleContainer = objRow.insertCell(objRow.cells.length);
			mySelf.titleContainer.style.width = "100%";
			mySelf.titleContainer.setAttribute("align", "center");
			mySelf.titleContainer.colSpan = 2;
			objRow = table.insertRow(table.rows.length);


			var objRow = table.insertRow(table.rows.length);
			mySelf.imageContainer = objRow.insertCell(objRow.cells.length);
			mySelf.imageContainer.style.width = "100%";
			mySelf.imageContainer.setAttribute("align", "center");
			mySelf.imageContainer.setAttribute("valign", "center");
			mySelf.imageContainer.colSpan = 2;

			objRow = table.insertRow(table.rows.length);
			mySelf.commentContainer = objRow.insertCell(objRow.cells.length);
			mySelf.commentContainer.style.width = "100%";
			mySelf.commentContainer.setAttribute("align", "center");
			mySelf.commentContainer.colSpan = 2;
			objRow = table.insertRow(table.rows.length);

			//previous and next image buttons
			mySelf.previousContainer = objRow.insertCell(objRow.cells.length);
			mySelf.previousContainer.style.width = "50%";
			mySelf.previousContainer.setAttribute("align", "left");

			var previousArrowImage = document.createElement('img');
			previousArrowImage.style.border = "0px";
			previousArrowImage.onclick = previousPhoto;
			previousArrowImage.src = LEFT_ARROW_IMAGE;
			previousArrowImage.title = "Previous";
			var previousAnchor = document.createElement('a');
			previousAnchor.href = "#";
			previousAnchor.appendChild(previousArrowImage);
			mySelf.previousContainer.appendChild(previousAnchor);


			mySelf.nextContainer = objRow.insertCell(objRow.cells.length);
			mySelf.nextContainer.style.width = "50%";
			mySelf.nextContainer.setAttribute("align", "right");

			var nextArrowImage = document.createElement('img');
			nextArrowImage.style.border = "0px";
			nextArrowImage.onclick = nextPhoto;
			nextArrowImage.src = RIGHT_ARROW_IMAGE;
			nextArrowImage.title = "Next";
			var nextAnchor = document.createElement('a');
			nextAnchor.href = "#";
			nextAnchor.appendChild(nextArrowImage);
			mySelf.nextContainer.appendChild(nextAnchor);


			//put elements in a table
			objRow = table.insertRow(table.rows.length);
			mySelf.errorContainer = objRow.insertCell(objRow.cells.length);
			mySelf.errorContainer.style.width = "100%";
			mySelf.errorContainer.setAttribute("align", "center");
			mySelf.errorContainer.colSpan = 2;

			mySelf.loadingElement = document.createElement('img');
			mySelf.loadingElement.src = LOADING_GIF;
			mySelf.loadingElement.border = "0";

			mySelf.imageElement = document.createElement('img');
			mySelf.imageElement.border = "0";
			mySelf.imageElement.style.display = "none";

			mySelf.imageContainer.appendChild(mySelf.loadingElement);
			mySelf.imageContainer.appendChild(mySelf.imageElement);

			//mySelf.imageElement.style.border = "1px solid #000000";

			mySelf.popupDiv.appendChild(table);
			mySelf.popupDiv.appendChild(closeButtonAnchor);
			mySelf.popupDiv.appendChild(closeButtonAnchor);
	    }

		fadePageOn();
		getCurrentImage();
	}


	function closeBrowser() {
	    if (mySelf.popupDiv != null) {
		while (mySelf.popupDiv.childNodes.length > 0)
			mySelf.popupDiv.removeChild(mySelf.popupDiv.childNodes[0]);

	        document.body.removeChild(mySelf.popupDiv);
	        mySelf.popupDiv = null;
	        fadePageOff();
	    }
	}


	//private functions

	//get the image, image size, comments, postedAt, and next and previous imageIds for photoid, and draw them to the popup div.
	function getCurrentImage() {
		hideNavigationPanel();
		mySelf.imageElement.style.display = "none";
		mySelf.loadingElement.style.display = "";

		var xmlHttp = createRequestObject();
		xmlHttp.open('post', '../items/image_viewer.php', true);
		var poststr = 'id=' + encodeURI(mySelf.imageID) + '&index=' + encodeURI(mySelf.currentImageIndex);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", poststr.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState==4) {
				var data = xmlHttp.responseText.split('\n');
				if (data[0] == 'error') {
					mySelf.loadingElement.style.display = "none";
					mySelf.imageElement.style.display = "none";
					mySelf.errorContainer.innerHTML = data[1];
				}
				else {
					mySelf.errorContainer.innerHTML = "";
					var tempImage = new Image();
					tempImage.onload = function() {
						mySelf.imageElement.src = this.src;
						mySelf.imageLoaded = true;
						if (mySelf.atVDestination && mySelf.atWDestination) {
							showImage();
						}
					}
					tempImage.onerror = function() {
						mySelf.loadingElement.style.display = "none";
						mySelf.errorContainer.innerHTML = "Image not found - " + this.src;
						showNavigationPanel();
					}

					mySelf.imageLoaded = false;
					tempImage.src = data[0]; //image Url
					mySelf.targetWidth = Math.max(parseInt(data[1]) + EXCESS_WIDTH, MINIMUM_WIDTH); //image width
					mySelf.targetHeight = Math.max(parseInt(data[2]) + EXCESS_HEIGHT, MINIMUM_HEIGHT); //image height
					if (data[3] != undefined)
						mySelf.titleContainer.innerHTML = "<br>" + data[3]; //title

					if (data[4] != undefined)
						mySelf.commentContainer.innerHTML = "<br>" + data[4]; //comments
					mySelf.previousImageIndex = data[5]; //previous ImageId
					mySelf.nextImageIndex = data[6]; //next ImageId
					resizeDiv(); //begin the motion tween
				}
				xmlHttp = null;
			}
		};
		xmlHttp.send(poststr);
	}

	//fetch the next photo
	function nextPhoto(event) {
		mySelf.currentImageIndex = mySelf.nextImageIndex;
		getCurrentImage();
	}

	//fetch the previous photo
	function previousPhoto() {
		mySelf.currentImageIndex = mySelf.previousImageIndex;
		getCurrentImage();
	}


	//resize the div smoothly to the given width and height
	function resizeDiv() {
		if (!isNaN(mySelf.targetHeight) && (!isNaN(mySelf.targetWidth))) {

			var divWidth = mySelf.popupDiv.style.width;
			divWidth = parseInt(divWidth.substring(0, divWidth.indexOf('px')));

			var divHeight = mySelf.popupDiv.style.height;
			divHeight = parseInt(divHeight.substring(0, divHeight.indexOf('px')));


			heightStep = Math.min(RESIZE_MOTION_STEP, Math.abs(divHeight, mySelf.targetHeight));
			var top = mySelf.popupDiv.style.top;
			top = parseInt(top.substring(0, top.indexOf('px')));

			//check if we are close to our destination...
			if (Math.abs(divHeight - mySelf.targetHeight) < heightStep) {
				mySelf.popupDiv.style.height = mySelf.targetHeight + "px";
				mySelf.atVDestination = true;
			}
			else if (divHeight < mySelf.targetHeight) { //we are increasing our height
				mySelf.popupDiv.style.height = (divHeight + heightStep) + "px";
				top -= (heightStep/2);
				if (top < 0)
					top = 0;
				mySelf.popupDiv.style.top = top + "px";
				mySelf.atVDestination = false;
			}
			else { //we are decreasing our height
				mySelf.popupDiv.style.height = (divHeight - heightStep) + "px";
				top += (heightStep/2);
				mySelf.popupDiv.style.top = top + "px";
				mySelf.atVDestination = false;
			}

			widthStep = Math.min(RESIZE_MOTION_STEP, Math.abs(divWidth, mySelf.targetWidth));
			var left = mySelf.popupDiv.style.left;
			left = parseInt(left.substring(0, left.indexOf('px')));

			//check for width
			if (Math.abs(divWidth - mySelf.targetWidth) <= widthStep) {
				mySelf.popupDiv.style.width = mySelf.targetWidth + "px";
				mySelf.atWDestination = true;
			}
			else if (divWidth < mySelf.targetWidth) { //we are increasing our width
				mySelf.popupDiv.style.width = (divWidth + widthStep) + "px";
				left -= (widthStep/2);
				if (left < 0)
					left = 0;
				mySelf.popupDiv.style.left = left + "px";
				mySelf.atWDestination = false;
			}
			else { //we are decreasing our width
				mySelf.popupDiv.style.width = (divWidth - widthStep) + "px";
				left += (widthStep/2);
				mySelf.popupDiv.style.left = left + "px";
				mySelf.atWDestination = false;
			}

			if (!(mySelf.atWDestination && mySelf.atVDestination)) {
				setTimeout(resizeDiv, RESIZE_MOTION_SPEED);
			}
			else if (mySelf.imageLoaded) {
				showImage();
			}

		}
	}
	//Shows the image when it has been loaded - called from resizeDiv
	function showImage() {
		mySelf.loadingElement.style.display = "none";
		mySelf.imageElement.style.opacity = 0;
		mySelf.imageElement.style.display = "";
		showNavigationPanel();
		fadeImageOn();
	}

	//self calling fade that makes the image softly fade onto the page. Called by showImage
	function fadeImageOn() {
		mySelf.imageElement.style.opacity = parseFloat(mySelf.imageElement.style.opacity) + 0.1;
		if (mySelf.imageElement.style.opacity != 1)
			setTimeout(fadeImageOn, RESIZE_MOTION_SPEED);
	}

	function createPopupDiv(left, top, width, height) {
		var newDiv = document.createElement('div');
		newDiv.style.position = 'absolute';
		newDiv.style.width = width+'px';
		newDiv.style.height = height+'px';
		newDiv.style.left = left + 'px';
		newDiv.style.top = top + 'px';
		newDiv.style.zIndex = '1000';
		newDiv.id = 'popupDiv';

		newDiv.style.backgroundColor = '#ffffff';
		newDiv.style.border = 'solid 1px #000000';
		newDiv.style.padding = '10px';

		return newDiv;
	}

	function fadePageOn() {
		var div = document.getElementById('fadediv');
		var madeNewDiv = (div == null);

		if (madeNewDiv)
			div = document.createElement('DIV');

		div.style.position = 'absolute';
		div.style.width = document.body.offsetWidth+'px';
		div.style.height = document.body.offsetHeight+'px';
		div.style.left = '0px';
		div.style.top = '0px';
		div.style.zIndex = '999';
		div.style.background = '#555555';
		div.style.opacity = '.75';
		div.style.filter = 'alpha(opacity=75)';

		div.id = 'fadediv';
		if (madeNewDiv)
			document.body.appendChild(div);
		else
			div.style.display = '';
	}

	function fadePageOff() {
		div = document.getElementById('fadediv');
		if (div != null)
			div.style.display = 'none';
	}

	///show the navigation buttons if there is a next/previous image available
	function showNavigationPanel() {

		if (mySelf.nextImageIndex != "")
			mySelf.nextContainer.style.display = "";

		if (mySelf.previousImageIndex != "")
			mySelf.previousContainer.style.display = "";

		mySelf.titleContainer.style.display = "";
		mySelf.commentContainer.style.display = "";
	}

	function hideNavigationPanel() {
		mySelf.titleContainer.style.display = "none";
		mySelf.commentContainer.style.display = "none";
		mySelf.nextContainer.style.display = "none";
		mySelf.previousContainer.style.display = "none";
	}

}

