var Main = new Object();

Main.initPhase = 0;

Main.init = function(data, mats, matIndexes, borderManager) {
	dbg.add('<b>Enter Init()</b> - initPhase: ' + this.initPhase);
	
	if (this.initPhase == 0) {
		this.data = data;
		this.matsList = mats;
		this.matIndexes = matIndexes;
		this.divs = new Object();
		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;

		// Page dimensions in pixels
		this.data.album.maxPixelSize = (this.data.album.maxPixelSize * this.data.album.matBiewPixelScaleFactor);
		
		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);

		// Fulfiller object. It handles all Album operations and deals with the page-to-insert conversions
		this.fulfiller = new Fulfiller(this.album, this.unitConv, 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);
		//data.paths.borders, borderManager

		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.body, document.body, null, ghostUrl, this.data);
		oProgessBar.increment(10);
	}

	if (this.initPhase == 2) {
		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.showPageThumbnailView();
	}
	dbg.add('<b>Exit Init()</b>', '');
}

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

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

Main.doCommand = function(e) {
	var commandId = e.target.userData[e.type];
	var command = this.data.commands[commandId];
	if (!command) {
		dbg.add('<b><i>' + commandId + ': </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 ' + commandId + '; 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 == 'elementLoadHandler') {
		this.elementLoadHandler(e.target.userData.objectType, e.target);
	} else if (command == 'elementLoadErrorHandler') {
		this.elementLoadErrorHandler(e.target.userData.objectType, e.target);		
	} else if (command == 'xmlHttpLoadHandler') {
		this.xmlHttpLoadHandler(e.target);
	} else if (command == 'xmlHttpLoadErrorHandler') {
		this.xmlHttpLoadErrorHandler(e.target);
	} else if (command == 'windowPrint') {
		this.windowPrint();
	}
}

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

Main.goAlbumPage = function(page) {
	var totalPages = this.fulfiller.getPageQuantity();
	
	if (page == 'play') { 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;
}

// ** Commands for network operations ** //

Main.elementLoadHandler = function(objectType, elementId) {
	oImageLauncher.imgLoad(elementId, false);
}

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);
	} else if (objectType == 'albumSaveData') {
		this.setMsg('The album could not be saved. Please try again.', this.data.msgLevels.ERROR, 5);
		dbg.add('Main.elementLoadErrorHandler() - albumSaveData: album could not be saved');
	}
	dbg.add('Main.elementLoadErrorHandler() - objectType: ' + objectType + ' - elementId: ' + toHtml(elementId.userData));
	oImageLauncher.imgLoad(elementId, true);
}

Main.xmlHttpLoadHandler = function(elementId) {
	oImageLauncher.getCookUrl(elementId, false);
}

Main.windowPrint = function() {
	window.print();
}

// ** 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();
}


Main.showPageThumbnailView = function() {
	this.setImgsToPageThumbnailView();
	
	this.btnPrint = new Button('Main.btnPrint', document.body, 40, 20, true);
	this.btnPrint.setImage('/images/album_designer/btn40x20.gif');
	this.btnPrint.setPositionType('relative');
	this.btnPrint.setCaption('Print');
	this.btnPrint.setShadow();
	
	this.btnPrint.html.div.style.margin = '10px auto';
	this.btnPrint.html.div.className = 'no-print';

	this.btnPrint.setEventHandlerData('click', 'windowPrint');
	this.btnPrint.setEventHandler('click', handleCommand);
}

Main.setImgsToPageThumbnailView = function() {
	var aPagesPairs = this.fulfiller.getPagePairs();
	
	//dbg.add('<b>aPagesPairs.length: </b>' + aPagesPairs.length);	
	for (var i = 0; i < aPagesPairs.length; i++) {
		var pair = aPagesPairs[i];
		var isPano = pair.even.isPano();
		this.goAlbumPage(pair.even.getPageNumber());

		if (!pair.even.isGhostPage()) {
			imgEven = this.renderer.getImage(pair.even.getUserData().id);
			if (imgEven.userData == null) { imgEven.userData = new Object(); }
			imgEven.userData.templateId = oMatsId[this.fulfiller.getTemplateID(pair.even.getPageNumber())];
			pair.even.getUserData().targetId = pair.even.getUserData().id;
		}

		if (!isPano && !pair.odd.isGhostPage()) {
			imgOdd = this.renderer.getImage(pair.odd.getUserData().id);
			if (imgOdd.userData == null) { imgOdd.userData = new Object(); }
			imgOdd.userData.templateId = oMatsId[this.fulfiller.getTemplateID(pair.odd.getPageNumber())];
			pair.odd.getUserData().targetId = pair.odd.getUserData().id;
		}
	}
	this.renderer.showPageThumbnailView(document.body, aPagesPairs, false);
}
