var Main = new Object();

Main.initPhase = 0;

Main.init = function(data, borderManager) {
	dbg.add('<b>Enter Init()</b> - initPhase: ' + this.initPhase);
	
	if (this.initPhase == 0) {
		this.data = data;
		this.divs = new Object();
		//this.divMain = document.getElementById('main');
		this.divAreas = document.getElementById('pageRendererContainer');
		this.docData = new Object();
		this.album = new Album(this.data.album.descriptor + (this.data.album.inserts.length > 0 ? this.data.album.inserts.join('') : ''));
		this.state = new Object();
		this.state.currentPages = { even: 0, odd: 1 };
		this.state.selectedAlbumItem = { pageNumber: null, openingId: null };
		this.defaultBorder = this.data.defaultBorder;

		Main.showInitialization();

		oProgessBar.increment(10);

		var albumPageWidth = this.album.getInsertSize().width;
		var albumPageHeight = this.album.getInsertSize().height;

		this.data.album.workingPixelWidth = (albumPageWidth > albumPageHeight ? this.data.album.workingPixelSize : Math.round(this.data.album.workingPixelSize * (albumPageWidth / albumPageHeight)));
		this.data.album.workingPixelHeight = (albumPageWidth > albumPageHeight ? Math.round(this.data.album.workingPixelSize * (albumPageWidth / albumPageHeight)) : this.data.album.workingPixelSize);

		// Page dimensions in pixels
		this.data.album.maxPixelSize = (this.data.album.maxPixelSize * this.data.album.slideshowPixelScaleFactor);
		
		this.data.album.pixelWidth = (albumPageWidth > albumPageHeight ? this.data.album.maxPixelSize : Math.round(this.data.album.maxPixelSize * (albumPageWidth / albumPageHeight)));
		this.data.album.pixelHeight = (albumPageWidth > albumPageHeight ? Math.round(this.data.album.maxPixelSize / (albumPageWidth / albumPageHeight)) : this.data.album.maxPixelSize);

		this.unitConv = new UnitsConverter(this.data.album.pixelWidth / albumPageWidth);
		this.unitConvWork = new UnitsConverter(this.data.album.workingPixelWidth / albumPageWidth);
		// Fulfiller object. It handles all Album operations and deals with the page-to-insert conversions
		this.fulfiller = new Fulfiller(this.album, this.unitConv, this.unitConvWork, null, this.data.paths.servletImagesPisPath + this.data.filenames.insideCoverFirst, this.data.paths.servletImagesPisPath + this.data.filenames.insideCoverLast, this.data.paths.servletImagesPisPath + this.data.filenames.opening, this.data.paths.servletImagesPisPath + this.data.filenames.ghostPage, this.data.paths.borders, borderManager, this.data.useAnnotateExtendedForPIS, this.data.album.metricsDpi);
		this.fulfiller.setOptionsObject(this.data.album.operations);
		//data.paths.borders, borderManager
		
		oImageLauncher.setEventHandler('load', 'slideShowCreateInterval', this);

		oProgessBar.increment(10);
	}
	
	if (this.initPhase == 1) {
		var ghostUrl = this.data.PIS + '?' + this.fulfiller.getGhostPagePISCommand({ width: this.album.getInsertSize().width, height: this.album.getInsertSize().height });
		// Page renderer. Shows and hides album pages
		this.renderer = new Renderer(this.data.album.pixelWidth, this.data.album.pixelHeight, 82, document.getElementById('pageRendererContainer'), document.getElementById('pagePreviews'), null, ghostUrl, this.data);
		this.data.renderer.pairsX += Math.floor((802 - this.data.renderer.imageBorderThickness * 2 - this.data.album.pixelWidth * 2) / 2);	//** Warning! Hardcoded pages area width!
		this.divAreas.style.height = (this.data.album.pixelHeight + this.data.renderer.imageBorderThickness * 2) + 'px';

		this.createButtons();
		oProgessBar.increment(10);
	}

	if (this.initPhase == 2) {
		this.reflow();
		oProgessBar.increment(10);
	}

	if (this.initPhase == 3) {
		oProgessBar.increment(1);
		this.initialized = true;
		this.tmpDivCont.parentNode.removeChild(Main.tmpDivCont);
		this.tmpDiv = this.tmpDivCont = null;		
	}

	this.initPhase++;
	if (this.initPhase <= 3) {
		setTimeout('initMain()', 50);
	} else {
		oProgessBar.increment(10);
		this.bPlaySlideShow = true;
		this.btnBrowserPause.setVisibility(false)
		this.goAlbumPage(0);
	}
	dbg.add('<b>Exit Init()</b>', '');
}


Main.slideShowPlayAndStop = function(bValue) {
	this.bPlaySlideShow = !this.bPlaySlideShow;
	if (bValue != null) { this.bPlaySlideShow = bValue; }
	
	if (this.bPlaySlideShow == true) {
		
		var totalPages = this.fulfiller.getPageQuantity();
		if (this.state.currentPages.even >= totalPages || this.state.currentPages.odd >= totalPages) {
			this.goAlbumPage('first');
		}
		
		this.btnBrowserPlay.setVisibility(false);
		this.btnBrowserPause.setVisibility(true);
		this.slideShowCreateInterval();
	}
	else {
		this.btnBrowserPlay.setVisibility(true);
		this.btnBrowserPause.setVisibility(false);
		this.slideShowClearInterval();
		this.slideShowNextPageTime = -1;
		if (oImageLauncher.iImgProcess <= 0) { document.getElementById('divNextPageTime').innerHTML = ''; } 
	}
}

Main.slideShowCreateInterval = function() {
	if (this.bPlaySlideShow == false) { this.slideShowPlayAndStop(false); return; }
	if (oImageLauncher.iImgProcess > 0) { return; }
	if (this.slideShowNextPageTime > 0) { return; }

	if (this.slideShowInterval != null) { this.slideShowClearInterval(); }
	this.btnBrowserPlay.setVisibility(false);
	this.btnBrowserPause.setVisibility(true);

	this.slideShowNextPageTime = this.data.slideshowDelay; //document.getElementById('iDelay').options[document.getElementById('iDelay').selectedIndex].value;
	this.slideShowTimeRemaining();
	this.slideShowInterval =  window.setInterval("Main.slideShowTimeRemaining()", 1000);
}


Main.slideShowClearInterval = function() {
	if (this.slideShowInterval != null) {
		window.clearInterval(this.slideShowInterval); this.slideShowInterval = null;
	}
}

Main.slideShowTimeRemaining = function() {
	if (this.bPlaySlideShow == false) { this.slideShowPlayAndStop(false); return; }
	if (oImageLauncher.iImgProcess > 0) { document.getElementById('divNextPageTime').innerHTML = 'loading images...'; return; }
	
	var totalPages = this.fulfiller.getPageQuantity();
	/*if ((this.state.currentPages.even >= totalPages || this.state.currentPages.odd >= totalPages) && this.btnBrowserRepeat.checked == false) {
		this.slideShowPlayAndStop(false);
		return;
	}*/
	
	if (this.slideShowNextPageTime <= 0) {
		this.slideShowClearInterval();
		this.slideShowGoNextPage();
		return;
	}
	else {
		document.getElementById('divNextPageTime').innerHTML = ' ' + this.slideShowNextPageTime + ' seconds remaining.';
	}
	this.slideShowNextPageTime--;
}

Main.slideShowResetInterval = function() {
	//if (this.slideShowInterval != null) { this.slideShowClearInterval(); }
	this.slideShowPlayAndStop(false);
	this.slideShowPlayAndStop(true);
}

Main.slideShowGoNextPage = function() {
	var totalPages = this.fulfiller.getPageQuantity();
	/*if ((this.state.currentPages.even >= totalPages || this.state.currentPages.odd >= totalPages) && this.btnBrowserRepeat.checked == false) {
		this.slideShowPlayAndStop(false);
		return;
	}*/
	
	if (this.state.currentPages.even >= totalPages || this.state.currentPages.odd >= totalPages) {
		this.goAlbumPage('first');
		return;
	}
	this.goAlbumPage('next');
}

Main.handleWindowResize = function() {
	this.data.reloadSize();
	this.reflow();
}

// ************************************** //
// ** GUI-generated command processing ** //
// ************************************** //

Main.doCommand = function(e) {
	var command = e.target.userData[e.type];
	if (!command) {
		dbg.add('<b><i>' + command + ': </i>No command defined for element </b>"<i>' + e.target.name + '" (id: ' + e.target.id + ')</i><b></b>');
		return false;
	}
	if (!this[command]) {
		dbg.add('<b>No method implemented for command "</b><i>' + command + '</i><b>"</b>');
		return false;
	}

	if (e.type != 'mouseover' && e.type != 'mouseout' && e.type != 'load')
		dbg.add('<b>Command: ' + command + '</b> called from ' + command + '; event type: ' + e.type);

	if (command == 'goAlbumPage') {
		var page = e.target.userData.page;
		if (page == 'fromTextbox') page = this.docData.pageToGo.value;
		this.goAlbumPage(page);
	} else if (command == 'elementLoadErrorHandler') {
		this.elementLoadErrorHandler(e.target.userData.objectType, e.target);
	}
}

// ** Commands for visual elements ** //

Main.goAlbumPage = function(page) {
	var totalPages = this.fulfiller.getPageQuantity();
	
	if (page == 'play' || page == 'pause') { this.slideShowPlayAndStop(); return; }

	if (page == 'first') {
		page = 0;
	} else if (page == 'last') {
		page = totalPages;
	} else if (page == 'previous') {
		page = this.state.currentPages.even - 2;
	} else if (page == 'next') {
		page = this.state.currentPages.even + 2;
	} else if (isNaN(parseInt(page, 10))) {
		return;
	}

	page = parseInt(page, 10);
	if (page < 0) page = 0;
	else if (page > totalPages) page = totalPages;

	var pair = this.fulfiller.getPagePair(page);
	var isPano = pair.even.isPano();
	
	var bCreateNewImg = false;

	//dbg.add('Main.goAlbumPage - current even: ' + this.state.currentPages.even + ' - current odd: ' + this.state.currentPages.odd + ', param: ' + page, 'new even: ' + pair.even.getPageNumber() + ' - new odd: ' + pair.odd.getPageNumber());

	// If there is even page but not image
	if (pair.even && pair.even.isGhostPage() == true) {
		var ghostEven = true;	
	}	
	else if (pair.even && this.fulfiller.getUserDataForPage(pair.even.getPageNumber()) && this.fulfiller.getUserDataForPage(pair.even.getPageNumber()).id == null) {
		//dbg.add('Main.goAlbumPage - this.fulfiller.getUserDataForPage(pair.even.getPageNumber()): ' + this.fulfiller.getUserDataForPage(pair.even.getPageNumber()), 'this.fulfiller.getUserDataForPage(pair.even.getPageNumber()).id: ' + this.fulfiller.getUserDataForPage(pair.even.getPageNumber()).id);
		// Add the image for the even page
		var evenId = this.renderer.addPage();
		this.fulfiller.setUserDataForPage(pair.even.getPageNumber(), 'id', evenId);
		this.renderer.updatePage(evenId, this.data.PIS + '?' + this.fulfiller.getPISCommandForPage(pair.even.getPageNumber()));	//** create an ImageData object here
		bCreateNewImg = true;
		//dbg.add('Main.goAlbumPage - even img created; id = ' + evenId);
	} 
	
	// If there is odd page but not image
	if (pair.odd && pair.odd.isGhostPage() == true) {
		var ghostOdd = true;
	}
	else if (pair.odd && this.fulfiller.getUserDataForPage(pair.odd.getPageNumber()) && this.fulfiller.getUserDataForPage(pair.odd.getPageNumber()).id == null) {
		// Add the image for the odd page
		var oddId = this.renderer.addPage();
		this.fulfiller.setUserDataForPage(pair.odd.getPageNumber(), 'id', oddId);
		this.renderer.updatePage(oddId, this.data.PIS + '?' + this.fulfiller.getPISCommandForPage(pair.odd.getPageNumber()));	//** create an ImageData object here
		bCreateNewImg = true;
		//dbg.add('Main.goAlbumPage - odd img created; id = ' + oddId);
	}

//	dbg.add('pis even: ' + this.fulfiller.getPISCommandForPage(pair.even.getPageNumber()), 'pis odd: ' + this.fulfiller.getPISCommandForPage(pair.odd.getPageNumber()))
	this.state.currentPages.even = pair.even.getPageNumber();
	this.state.currentPages.odd = this.state.currentPages.even + 1;
	this.state.currentPages.totalPages = totalPages;

	this.renderer.showPagePairToSlideShow((pair.even ? (ghostEven ? -1 : this.fulfiller.getUserDataForPage(pair.even.getPageNumber()).id) : null), (pair.odd ? (ghostOdd ? -1 : this.fulfiller.getUserDataForPage(pair.odd.getPageNumber()).id) : null), isPano, this.state.currentPages);
	
	if (bCreateNewImg == false || oBrowserSniffer.isSafari == true) { this.slideShowCreateInterval(); }
	else { document.getElementById('divNextPageTime').innerHTML = 'loading images...'; }
}

// ** Commands for network operations ** //
Main.elementLoadErrorHandler = function(objectType, elementId) {
	if (objectType == 'matSnapshot') {
//		this.setMsg('The snapshot for mat ' + elementId.userData.matId + ' could not be loaded.', this.data.msgLevels.ERROR, 5);
//		this.matsPanel.thumbnailLoadErrorHandler(elementId);
	}
	dbg.add('Main.elementLoadErrorHandler() - objectType: ' + objectType + ' - elementId: ' + toHtml(elementId.userData));
	this.slideShowCreateInterval();
}

// ** Commands for editing operations ** //
Main.showInitialization = function() {
	if (!document.getElementById('initialization')) { return; }
	
	this.tmpDivCont = document.getElementById('initialization');
	this.tmpDivCont.style.width = this.data.viewport.w + 'px';
	this.tmpDivCont.style.height = this.data.viewport.h + 'px';
	this.tmpDivCont.style.zIndex = 65535;
	this.tmpDiv = document.getElementById('initializationText');
	var padding = 30
	this.tmpDiv.style.padding = padding + 'px';
	this.tmpDiv.style.width = Math.round(this.tmpDivCont.offsetWidth * .85) + 'px';
	this.tmpDiv.style.height = Math.round(this.tmpDivCont.offsetHeight * .85) + 'px';
	this.tmpDiv.style.left = Math.round(this.tmpDivCont.offsetWidth * .15 / 2 - padding) + 'px';
	this.tmpDiv.style.top = Math.round(this.tmpDivCont.offsetHeight * .15 / 2 - padding) + 'px';
	this.tmpDiv.style.zIndex = 10;
	if (oBrowserSniffer.isMsie == true) {
		var tmpIframe = document.createElement('iframe');
		tmpIframe.style.display = 'block';
		tmpIframe.style.width = this.tmpDivCont.style.width;
		tmpIframe.style.height = this.tmpDivCont.style.height;
		tmpIframe.style.zIndex = 1;
		tmpIframe.style.filter = 'alpha(opacity=0)';
		this.tmpDivCont.appendChild(tmpIframe);
	}
	oProgessBar.setPositionCenter();
}

//TODO: Move this method
Main.createButtons = function() {
	oColor = { 'up':'white', 'over':'white', 'down':'black', 'disabled':'gray' };

	//Browse
	this.aBtnBrowser = new Array();	
	for(var i = 0; i <= 5; i++){
		switch(i) {
			case 0: sCaption = ''; sDivContainer = 'browsingControlsFirst'; page = 'first'; sImg = 'nav_skip_back.png'; iWidth = 28; iHeight = 38; break;
			case 1: sCaption = ''; sDivContainer = 'browsingControlsPrevious'; page = 'previous'; sImg = 'nav_previous.png'; iWidth = 48; iHeight = 38; break;
			case 2: sCaption = ''; sDivContainer = 'browsingControlsPlay'; page = 'play'; sImg = 'nav_play.png'; iWidth = 77; iHeight = 38; break;
			case 3: sCaption = ''; sDivContainer = 'browsingControlsPlay'; page = 'pause'; sImg = 'nav_pause.png'; iWidth = 77; iHeight = 38; break;
			case 4: sCaption = ''; sDivContainer = 'browsingControlsNext'; page = 'next'; sImg = 'nav_next.png'; iWidth = 48; iHeight = 38; break;
			case 5: sCaption = ''; sDivContainer = 'browsingControlsLast'; page = 'last'; sImg = 'nav_skip_forward.png'; iWidth = 28; iHeight = 38; break;
		}
		this.aBtnBrowser[i] = new Button("Main.aBtnBrowser[" + i + "]", document.getElementById(sDivContainer), iWidth, iHeight, true);
		this.aBtnBrowser[i].setImage('/images/album_designer/' + sImg);
		this.aBtnBrowser[i].setFontSize(10);
		this.aBtnBrowser[i].setPositionType('relative');
		this.aBtnBrowser[i].setCss('color', oColor);
		this.aBtnBrowser[i].setCss('cursor', {'up': 'pointer'});
		this.aBtnBrowser[i].setState('up');
		if (sCaption != '') {
			this.aBtnBrowser[i].setCaption(sCaption);
			this.aBtnBrowser[i].setShadow();
		}
		
		this.aBtnBrowser[i].setEventHandlerData('click', 'goAlbumPage');
		this.aBtnBrowser[i].setEventHandlerData('page', page);
		this.aBtnBrowser[i].setEventHandler('click', handleCommand);
		
		if (i == 2) this.btnBrowserPlay = this.aBtnBrowser[i];
		else if (i == 3) this.btnBrowserPause = this.aBtnBrowser[i];
	}

	this.closeButton = new Button("Main.closeButton", document.getElementById('closeWindow'), 48, 13, true);
	this.closeButton.setImage('/images/album_designer/btn_close.png');
	this.closeButton.setPositionType('relative');
	this.closeButton.setState('up');
	this.closeButton.setEventHandler('click', new Function('', 'window.close()'));

	//this.btnBrowserRepeat.setBehavior('checkbox');
	//this.btnBrowserRepeat.setFontSize(9);
}

//TODO: Move this method
Main.reflow = function() {
	//document.getElementById('pageRendererContainer').style.left = (Math.round(this.data.viewport.w / 2 - this.data.album.pixelWidth)) + 'px';
}
