/*
 * Start the init() function using the jquery ready() callback.
 */
$(document).ready(function() {
	init();
});

/**
 * Starts the initialization. Function can be overriden or extended in sub-projects.
 * Javascript functions can be extended this way:
 * (see http://dataerror.blogspot.com/2005/08/javascript-function-overriding-part-1.html)
 * <pre>
 * var superInit = init;
 * init = function() {
 * ...
 * superInit();
 * ...
 * }
 * </pre>
 * To override a function without calling the base function, just redefine the
 * method once more:
 * <pre>
 * function init() {
 * ...
 * }
 * </pre> 
 */
function init() {
	$('#StartBox').css("visibility", "visible");
	
	// HoverAccordion
	initHoverAccordion();


	// UI-Tabs
	//$("#tabpanel > ul").tabs({ fxFade: true, fxSpeed: 'fast' });


	// Zoom
	initLensButton();
	initZoomStandardButton();
	initZoomDecreaseButton();
	initZoomIncreaseButton();
	initZoomMaximizeButton();

	// Colorpicker
	initColorButtons();
	
	initializeModules();
	
	executeImageFading();	
}

function initHoverAccordion() {
	$('#accordion').hoverAccordion({
		activateitem: '1',
		speed: 'slow'
	});
}

function initLensButton() {
	$('a#lensButton').click(function() {
		startLens();
		initializeImagePos();
    });
}

function initZoomStandardButton() {
	$('a#zoomStandard').click(function() {
		minimize();
        initializeImagePos();
	});
}

function initZoomDecreaseButton() {
	$('a#zoomDecrease').click(function() {	
		zoomOut();
        initializeImagePos();
	});
}

function initZoomIncreaseButton() {
	$('a#zoomIncrease').click(function() {
		zoomIn();
        initializeImagePos();
	});
}

function initZoomMaximizeButton() {
	$('a#zoomMaximize').click(function() {
		maximize();
		$('#ImageBox').children('a').css("position", 'absolute');
		$('#ImageBox').children('a').css("left",  0);
	});
}

function initColorButtons() {
	$('#ColorSelectorNeutral').addColorPicker({
		clickCallback: function(c) {
			//$('#fragment-4').hide();
			$('#fragment-4').css("visibility", "hidden");
			$('.idTabsNav>a').removeClass('selected');
			onColorPicker(c);
		},
		/*titles: [
			'Schwarz', 'Weiss'
			],*/
		colors: [
			'#3F3E3C', '#F5FDFF'
			]
	});

	$('#ColorSelectorAlpina').addColorPicker({
		clickCallback: function(c) {
			//$('#fragment-1').hide();
			$('#fragment-1').css("visibility", "hidden");
			$('.idTabsNav>a').removeClass('selected');
			onColorPicker(c);
		},
		/*titles: [
			'Life','Move','Dance','Pulse','Joy','Cover',
			'Change','Passion','Step','Fun','Flower','Break',
			'Expo','Drop','Look','Energy','Sweet','Spirit'
			],*/
		colors: [
			'#FFDF8C','#CABD4D','#EBD9D9','#573F4D','#F3E4BB','#F8EDDB',
			'#E3E8A8','#8D3B41','#7683A5','#F99056','#FDEAB2','#FFD497',
			'#837062','#9FC1CA','#FFB963','#AB4536','#FCE5C3','#DCE6E8'
			]
	});

	$('#ColorSelectorDulux1').addColorPicker({
		clickCallback: function(c) {
			//$('#fragment-2').hide();
			$('#fragment-2').css("visibility", "hidden");
			$('.idTabsNav>a').removeClass('selected');
			onColorPicker(c);
		},
		/*titles: [
			'Grimsey','Sunset','Formosa','Tahiti','Kashmir','Metropol.',
			'N..Bast','Belvedere','Isabella','Polarw.','Sansibar','BoaVista',
			'N.Leinen','Moroni','Java','Maurit.','Soledad','Vulcano'
			],*/
		colors: [
			'#DBDBD3','#FCE5BC','#F0D05F','#F5D7B3','#DA744C','#BCD4E0',
			'#EEDDC9','#FDDAA4','#EEC051','#F3F0E1','#F59A54','#ABD8D3',
			'#F0E4CE','#CEC2B2','#F7D284','#E9E9DF','#EDAA80','#A94239'
			]
	});

	$('#ColorSelectorDulux2').addColorPicker({
		clickCallback: function(c) {
			//$('#fragment-3').hide();
			$('#fragment-3').css("visibility", "hidden");
			$('.idTabsNav>a').removeClass('selected');
			onColorPicker(c);
		},
		/*titles: [
			'N.Bambus','N.Sand','G.Gate','KapVerde','Montego','Niagara',
			'Jamaica','N.Weide','Elysee','Bonaire','Broadw.','Barbad.',
			'Cabana','Tobago','Grenada','Andros','Orkney','Tinos'
			],*/
		colors: [
			'#F8E9CC','#E8DCCE','#FDC87C','#D9DDCC','#E1A084','#5282B2',
			'#FAE9CD','#F3DFC4','#FAD8BF','#D4E1C7','#D2D7D1','#98B5D3',
			'#F0E2BD','#F6E5C7','#F3BD9B','#D0DD8E','#B5C6CD','#6A9FC7'
			]
	});
}


//// functions that need to be called several times


/*
 * In einzelne Funktionen ausgelagerte Initialisierungen,
 * die zur Re-Initialisierung bestimmter Module wiederholt
 * aufgerufen werden müssen.  
 */
function initializeModules() {
	initializeCarousel();
	initializeLightbox();
}
	   
function initializeCarousel() {
	// JCarousel
	$('#carousel').jcarousel({
		// Configuration goes here
	});   
}

function initializeLightbox() {
	// Lightbox	
	$('a.lightbox').each(function(){
		$(this).mousedown(function(e){
			// do nothing if this is not the left mouse button
			if(e.which != 1) return false;
			initializeZoom();
			this.href=$('#ImageBox>a>img').attr('src');
			
			// instead of setting the title of the <a> tag which is then
			// used in the lightbox as title, we set the #caption box
			// manually so that the <a> title is not displayed as tooltip
			$('#caption').html(getLightboxDetails()).show();
			//this.title=getLightboxDetails();
		});
	});
}

/**
 * Returns the HTML which is to be displayed as title in the Lightbox.
 * May be overridden by sub-projects.
 */
function getLightboxDetails() {
	title='<table cellpadding="1" cellspacing="0" border="0"><tr>' +
				'<td>' + $('#currentProductImage').html() + '</td>' +
				'<td align="top">' + $('#currentProductKey').text() + '<br>' +
					$('#currentProductDescription').text() +
				'</td></tr>' +
				'</table>';
	return title;
}

/**
 * Variation of the getLightboxDetails() function that supports multiple items.
 * May be used by sub-projects to change the fading effect. Do this
 * by redefining the getLightboxDetails function:
 * <pre>
 * function getLightboxDetails() {
 *	return getLightboxDetailsMultiItems();
 * }
 * </pre>
 */
function getLightboxDetailsMultiItems() {
	if($('#currentProductKey1').length>0)
		title='<table cellpadding="1" cellspacing="0" border="0"><tr>' +
		'<td>' + $('#currentProductImage0').html() + '</td>' +
		'<td align="top">' + $('#currentProductKey0').text() + '<br>' +
			$('#currentProductDescription0').text() +
		'</td></tr>' +
		'<tr><td>' + $('#currentProductImage1').html() + '</td>' +
		'<td align="top">' + $('#currentProductKey1').text() + '<br>' +
			$('#currentProductDescription1').text() +
		'</td></tr>' +
		'</table>';
	else
		title='<table cellpadding="1" cellspacing="0" border="0"><tr>' +
			'<td>' + $('#currentProductImage0').html() + '</td>' +
			'<td align="top">' + $('#currentProductKey0').text() + '<br>' +
				$('#currentProductDescription0').text() +
			'</td></tr>' +
			'</table>';
	return title;
}


var execID=0;
var execState=0;
var fadingTime=500;
var currentImage=null;
var newImage=null;
var newImageSource;
var additionalRequests=0;

/**
 * Prepare for image fading and start interval for level-based execution.
 */
function executeImageFading() {
	if (execID > 0) {
		// it is possible that executeImageFading is invoke again while there
		// currently is an active image exchange. This may happen in case the
		// user changes the room or installs new items while the last request
		// is still active. We need to prevent parallel execution, however,
		// we need to record this change as the img nodes have been exchanged
		// already.
		// Do have a correct image fading cycle including calls to preImageFading()
		// and postImageFading, we delay the further execution of executeImageFading()
		// until the first cycle has been fully completed
		additionalRequests++;
		return;
	}

	// Prepare image fading by keeping the older image visible and
	// placing the new image at second position.
	// Note: ImageBox may not exist yet due to the way IE parses the
	// HTML files: when it detects a JavaScript command, it executes it
	// at once and not when the HTML parsing has been completed. So the
	// ImageBox may not have been created when the script is run for the
	// first time. That's the reason why we need to invoke executeImageFading
	// once more in init()
	if($('#ImageBox').html()) {
		preImageFading();

		newImage=$('#ImageBox').html();
		newImageSource=$('#ImageBox>a>img').attr('src');
		if(currentImage!=null) {
			$('#ImageBox').html(currentImage+newImage);
		}

		execState=0;
		execID = setInterval("periodicExecution()", 10);
	}
}

/**
 * Function that is called before the image fading starts.
 * Default implementation does nothing.
 */
function preImageFading() {
}

/**
 * Function that is called when the image fading is completed.
 * Default implementation does nothing.
 */
function postImageFading() {
}

/**
 * Do all steps required for image fading after page (re-)loading.
 * <p>
 * This method is called within a timer every 10ms
 */
function periodicExecution() {
    // state 0: Start of loading phase
    // Append 'wait'-icon to symbolize loading.    
    if (execState==0) {
    	execState=01; // begin to process this state, make sure that it is not invoked again
        
    	$('#ImageBox').append('<div id="WaitBox" style="position:relative; left:'+(($('#ImageBox').width()/2)-16)+'px; top:'+(($('#ImageBox').height()/2)-16)+'px; width:32px; height:32px;z-index:1;"><img src="images/ajax-loader.gif" border="0" style="width:32px;height:32px;"></div>');
        
    	execState=10;
    }
    
    // state 1_0: Loading phase
    // new image is being loaded. We are waiting until loading is completed.
    else if (execState==10) {
    	execState=11; // begin to process this state, make sure that it is not invoked again
    	
        preloader = new Image();
         preloader.onload=function(){
            execState=20; // done, state transition to next phase
        }
        preloader.src = newImageSource;
    }
    
    // state 2_0: Loading complete
    // image is completely loaded, recalculate image position
    else if (execState==20) {
    	execState=21; // begin to process this state, make sure that it is not invoked again
	    
    	if (isCentered()) {
	        var imageBoxWidth = $('#ImageBox').width();
	        setImagePosX(((imageBoxWidth-preloader.width)/2)+imagePosLeft);
	    }
	    else {
	        setImagePosX(imagePosLeft+imageBorder);
	    }
	    setImagePosY(imagePosTop+imageBorder);
        initializeImagePos();
        
        execState=30; // done, state transition to next phase
    }
    
    // state 3_0: Fading phase
    // image position ok, do fading and remove 'wait'-icon
    else if (execState==30) {
    	execState=31; // begin to process this state, make sure that it is not invoked again
    	
        $('#ImageBox').children('a:last').fadeIn(fadingTime, function() {
            if ($('#ImageBox').children('a').size() > 1) {
                $('#ImageBox').children('a:first').remove();
            }
            $('#WaitBox').remove(); 
            execState=40; // done, state transition to next phase
        });
    }
    
    // state 4_0: Fading completed
    // store image as current image and inform other modules about image change 
    else if (execState==40) {
    	execState=41; // begin to process this state, make sure that it is not invoked again
    	
    	currentImage=$('#ImageBox').html().trim();
	    setNewImageLoaded();
	    // instead of setting the title of the <a> tag which is then
	    // used in the lightbox as title, we set the #caption box
	    // manually so that the <a> title is not displayed as tooltip
	    $(".lightbox").lightbox({displayTitle: false}); //Lightbox.initialize();
	    initializeLightbox();
	    
	    execState=90; // done, state transition to next phase
    }
    
    // state 9_0: Cleanup phase
    // stop execution interval and reset execID
    else if (execState==90) {
    	execState=91; // begin to process this state, make sure that it is not invoked again
    	
        clearInterval(execID);
        execID=0;
        
        postImageFading();
        
        // in case requests to the executeImageFading() function were rejected,
        // just invoke it again here (see executeImageFading())
        if(additionalRequests>0) {
        	additionalRequests--;
        	executeImageFading();
        }
    }
}


/*
 * Re-Initializes the room image position when activating toolbar functions
 * like minimize, maximize, lens and so on.
 * Furthermore called during onload action added to body tag by dyn-script. 
 */
function initializeImagePos() {
	$('#ImageBox').children('a:last').css("position", 'absolute');
	$('#ImageBox').children('a:last').css("left", getImagePosX()-imageBorder);
}


/**
 * Returns true or false depending on desired image position.
 */
function isCentered() {
    return true;
}


/*
 * Helper function
 */
String.prototype.trim = function () {
	return this.replace(/^\s*|\s*$/, "");
}


function openPrintPreview() {
	var parameter = "width=865px,scrollbars=yes,menubar=no,toolbar=no,status=no,resizable=no";
	printPreview = window.open('print.do', '_blank', parameter);
	printPreview.document.close();
}
