/*

console.log(imageData[0][3][0][1]);

imageData	[x:row
				[	0:category
					1:Name
					2:Thumb
					3:images
					[x:row
						[	0:src
							1:description
						]
					]
				]
			]	


*/

var viewport_dimentions;

///////////////////////////////////////////////////////////////////////////////////
//
//  HTML-blocks
//
///////////////////////////////////////////////////////////////////////////////////

var htmlSubjectLoader = 	'<object id="subject-loader" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="32" height="32" id="loader" align="middle">';
htmlSubjectLoader +=			'<param name="allowScriptAccess" value="sameDomain" />';
htmlSubjectLoader +=			'<param name="allowFullScreen" value="false" />';
htmlSubjectLoader +=			'<param name="movie" value="swf/loader.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#1a1a1a" />	<embed src="swf/loader.swf" quality="high" wmode="transparent" bgcolor="#1a1a1a" width="32" height="32" name="loader" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
htmlSubjectLoader +=		'</object>';

var VIMEO_VIDEO_WIDTH = 770;
var VIMEO_VIDEO_HEIGHT = 429;

///////////////////////////////////////////////////////////////////////////////////
//
//  Window
//
///////////////////////////////////////////////////////////////////////////////////

/**
 * Called in the event of window resize
 * @param  none
 * @return void
 **/
function window_resize(){
	//Update viewport dimentions
	viewport_dimentions = document.viewport.getDimensions();	
	//Re-calculate the range of the slider
	var range_max = overview.container_obj.getWidth() - overview.images_obj.getWidth();
	if(range_max < 0){ range_max = 0 };
	if (typeof overwiewSlider != 'undefined')
		overviewSilder.range = $R(0,range_max);
}

/**
 * Called when the window is loaded
 * @param  
 * @return void
 **/
function window_onload(){
	//-->Debug console.log('-->Window loaded.');
	_init();
}

/**
 * Attach eventlisteners to the window object
 **/
Event.observe(window, 'load',window_onload);
Event.observe(window, 'resize',window_resize);

///////////////////////////////////////////////////////////////////////////////////
//
//  Div
//
///////////////////////////////////////////////////////////////////////////////////
function centerInWindow(id){
	var object = $(id);
	var id_dimentions = object.getDimensions();
	
	object.setStyle({ 
		left: (((viewport_dimentions.width / 2) - (id_dimentions.width/2))+'px'),
		top: (((viewport_dimentions.height / 2) - (id_dimentions.height/2))+'px')
	});
}

///////////////////////////////////////////////////////////////////////////////////
//
//  Naivation
//
///////////////////////////////////////////////////////////////////////////////////

/**
 * Change the list of images that is loaded 
 * @return void
 **/
function nav_filterimages(selObj){
	overview_zap();
	overview_tip_kill();
  	overview_load(selObj.options[selObj.selectedIndex].value);
}

///////////////////////////////////////////////////////////////////////////////////
//
//  Init
//
///////////////////////////////////////////////////////////////////////////////////

//Define global vars
var overview;
var overviewSilder;
var imageData;

function _init(){

	viewport_dimentions = document.viewport.getDimensions();
	
	
	// Create a var for to hold all needed information about the properties of the navigation
	overview = {
		container_id: 		'overview-container',
		container_obj: 		$('overview-container'),
		images_id: 			'overview-images',
		images_obj: 		$('overview-images'),
		duration: 			1,
		mode: 				'absolute',
		sliderCurrentValue: 0,
		sliderIncrement: 	1,
		sliderStep: 		200,
		ieBug: 				true
	}
	
	subject = {
		current_row: 	0,
		current_image: 	0
	}
	
	//Load all images. The prarmeter is for filter, setting this to 'none' loads all images
	overview_load('commercial');
	
	if (Prototype.Browser.IE)
		$$('body')[0].setStyle({ overflow : 'hidden' });
}

///////////////////////////////////////////////////////////////////////////////////
//
//  Overview
//
///////////////////////////////////////////////////////////////////////////////////

/**
 * Show the loading icon in the overview
 * @return void
 **/
function overview_loader_show(){
	/*
	toggleIEBug();
	$$('body')[0].insert({top:'<div id="subject-background"><div id="overview-loader" >'+htmlSubjectLoader+'</div></div>'});
	*/
}

function overview_loader_hide(){
	/*
	toggleIEBug();
	$('subject-background').remove();
	*/
}

/**
 * Clear all content from the overview
 * @return void
 **/
function overview_zap(){
	overview.container_obj.update('');
}

/**
 * Loads the the list of images from a JSON-file, inits the image-loading and inits the slider
 * @param  
 * @return void
 **/
function overview_load(filter){
	new Ajax.Request('image-database.php?filter='+filter,
		{
			onCreate: function(){
				//On request made, display the loading image
				overview_loader_show();
			},
			onSuccess: function(transport){
				//Remove any code that is currently in the overview
				overview_zap();
				//Evaluate the data recived as JSON 
				imageData = transport.responseText.evalJSON();
				//Call function to start inserting the images on the page
				overview_display_images();
				//Call function to give the slider correct information about the images loaded
				overview_setSlider();			
			},
			parameters: {
				ajax: 'true',
				filter: 'none'
			}
		}
	);
}

/**
 * Loops the image-data array and inserts the image-tags.
 * @param  
 * @return void
 **/
function overview_display_images(){
	// Loop the imagedata and insert the images
	for(i=0; i<imageData.length;i++){
		//console.log(imageData[0][3][0][1]);
		//overview.container_obj.insert({bottom:'<div class="overview-image"><img class="pointer" id="image-'+i+'" style="display:none;" onload="overview_show_image(\'image-'+i+'\')" onclick="subject_init('+i+');" src="'+imageData[i][2]+'" width="180" height="120" alt=""></div>'});
		overview.container_obj.insert({bottom:'<div class="overview-image"><img class="pointer" id="image-'+i+'" onclick="subject_init('+i+');" src="'+imageData[i][2]+'" width="180" height="120" alt=""></div>'});

		//Attach a tootip to each image
		$('image-'+i).observe('mouseover', overview_tip_display);
		$('image-'+i).observe('mouseout', overview_tip_kill);
		$('image-'+i).observe('load', overview_show_image);
		
		//I tried to make a onload listener for the when the images, but the object refrenced in this event is viewport so for some reason a can't get the id if the image. 		
		
		//Attach a listener to the last image loded to remove the loadingicon
		if((imageData.length-1) == i){
			//$('image-'+i).observe('load', overview_loader_hide);
		}
	}
	
	//Calculate how many images we get in each row
	/* DELETED REFLECTIONS Jan 2011
	var reflection = (Math.ceil(imageData.length/3))*2;
	overview.container_obj.insert('<div class="overview-imagerow-clear"></div>');
	*/
	
	//Loop the last row of images to insert the reflections
	/* DELETED REFLECTIONS Jan 2011
	for(r=reflection;r<imageData.length;r++){
		var reflection_html = '<div class="overview-image"><object type="application/x-shockwave-flash" data="swf/image-rotate.swf?img='+imageData[r][2]+'" width="180" height="40"><param name="bgcolor" value="#1A1A1A" /><param name="movie" value="swf/image-rotate.swf?img='+imageData[r][2]+'" /></object></div>';
		overview.container_obj.insert(reflection_html);
	}
	*/
}

/**
 * Attach a tooltip to the image
 * @param  none
 * @return void
 **/
function overview_tip_display(event){
	var element = event.element();
	var id = element.readAttribute('id');
		
	$$('body')[0].insert({top:'<div id="tip" style="display:none;">'+imageData[id.sub('image-','')][1]+' #'+imageData[id.sub('image-','')][3].length+'</div>'});
	$('tip').setStyle({ top:(Event.pointerY(event)+5)+'px' ,left:(Event.pointerX(event)+5)+'px' });
	new Effect.Appear('tip',{duration:0.5});
	
	Event.observe(document, 'mousemove', overview_tip_update);
}

function overview_tip_kill(event){
	if($('tip') != null){
		$('tip').remove();
		Event.stopObserving(document, 'mousemove',overview_tip_update);
	};
}

function overview_tip_update(event){
	$('tip').setStyle({ top:(Event.pointerY(event)+5)+'px' ,left:(Event.pointerX(event)+5)+'px' });
}

/**
 * Fades inn a image
 * @param  
 * @return void
 **/
function overview_show_image(id){
	new Effect.Appear(id);
}

///////////////////////////////////////////////////////////////////////////////////
//
//  Subject
//
///////////////////////////////////////////////////////////////////////////////////

/**
 * Inits the overlay for the images
 * @param  
 * @return void
 **/
function subject_init(id){
	//Set the current image to display
	subject.current_row = id;
	//Kill tip if it is open
	overview_tip_kill();
	//Id the browser is IE we need to toggle any formobjects
	toggleIEBug();
	//Create the overlay background
	$$('body')[0].insert({top:'<div style="display:none;" id="subject-background"></div>'});
	//Fade inn the overlay, once done call the image
	new Effect.Appear('subject-background',{duration:0.5, afterFinish:subject_show});
}

/**
 * Kills the subject window. Fades the subject-object out and removes the tag
 * @param  none
 * @return void
 **/
function subject_kill(){
	new Effect.Fade('subject-background',{
		afterFinish: function(){
			$('subject-background').remove();
		},
		duration:0.5
	});
	toggleIEBug();
};

/**
 * Shows the loading icon
 * @param  none
 * @return void
 **/
function subject_loading_show(){
	$('subject-background').insert('<div id="subject-holder" style="width:42px; height:42px;">'+htmlSubjectLoader+'</div>');
	$('subject-holder').setStyle({ 
		left: (((viewport_dimentions.width / 2) - (21))+'px'),
		top: (((viewport_dimentions.height / 2) - (21))+'px')
	});
}

/**
 * Removes the loadingicon
 * @param  none
 * @return void
 **/
function subject_loading_hide(){
	$('subject-holder').remove();
}

/**
 * Displays the selected image
 * @param  none
 * @return void
 **/
function subject_show(){
	subject_loading_show();
	
	//Create a new image to hold the subjectimage
	var subject_image = new Image();
	var image = imageData[subject.current_row][3][subject.current_image];
	if (image[2]) {
		subject_loading_hide();
		$('subject-background').insert('<div id="subject-holder"><img class="pointer" id="prev" onclick="subject_prev()" src="images/framework/slider-btn-left-trans.png" width="31" height="39" alt="Forrige" title="Forrige">' + image[2] + '<img class="pointer" id="subject-close" src="images/framework/subject-close-trans.png" width="58" height="58" alt="Lukk" title="Lukk"><img class="pointer" id="next" onclick="subject_next()" src="images/framework/slider-btn-right-trans.png" width="31" height="39" alt="Neste" title="Neste"></div>');
		$('subject-close').observe('click',subject_kill);
		$('subject-holder').setStyle({ 
			width: 	(VIMEO_VIDEO_WIDTH+'px'),
			height: (VIMEO_VIDEO_HEIGHT+50+'px'),
			left: 	(((viewport_dimentions.width / 2) - (VIMEO_VIDEO_WIDTH/2))+'px'),
			top: 	(((viewport_dimentions.height / 2) - (VIMEO_VIDEO_HEIGHT/2))+'px'),
			display:'none'
		});
		new Effect.Appear('subject-holder', {
			duration: 0.5, 
			afterFinish: 
				function () {
					if (typeof IE7 != 'undefined')
						IE7.recalc();
				}
			});
		return;
	}
		
	subject_image.onload = function(){

		// console.log('Loading is done');
		//Remove the loading image
		subject_loading_hide();
		
		//Insert the subjectimage image
		$('subject-background').insert('<div id="subject-holder"><img class="pointer" id="prev" onclick="subject_prev()" src="images/framework/slider-btn-left-trans.png" width="31" height="39" alt="Forrige" title="Forrige"><img id="current-subject" src="'+subject_image.src+'" height="'+subject_image.height+'" width="'+subject_image.width+'" /><img class="pointer" id="subject-close" src="images/framework/subject-close-trans.png" width="58" height="58" alt="Lukk" title="Lukk"><img class="pointer" id="next" onclick="subject_next()" src="images/framework/slider-btn-right-trans.png" width="31" height="39" alt="Neste" title="Neste"><div id="subject-detail">'+imageData[subject.current_row][3][subject.current_image][1]+'</div></div>');
		$('subject-close').observe('click',subject_kill);
		
		
		$('subject-holder').setStyle({ 
			width: 	(subject_image.width+'px'),
			height: (subject_image.height+50+'px'),
			left: 	(((viewport_dimentions.width / 2) - (subject_image.width/2))+'px'),
			top: 	(((viewport_dimentions.height / 2) - (subject_image.height/2))+'px'),
			display:'none'
		});
		
		new Effect.Appear('subject-holder', {
			duration: 0.5, 
			afterFinish: 
				function () {
					if (typeof IE7 != 'undefined')
						IE7.recalc();
				}
			});
	}

	subject_image.onerror = function(){
		//-->Debug console.log('-->Subject image was not found!');
		//Remove the loading image
		subject_loading_hide();
		//Insert the subjectimage image
		$('subject-background').insert('<div id="subject-holder"><img onclick="subject_kill()" src="images/framework/error-message.gif" height="148" width="450"></div>');

		$('subject-holder').setStyle({ 
			width: 	'450px',
			height: '148px',
			left: 	(((viewport_dimentions.width / 2) - (450/2))+'px'),
			top: 	(((viewport_dimentions.height / 2) - (148/2))+'px'),
			display:'none'
		});
		
		new Effect.Appear('subject-holder', {
			duration: 0.5, 
			afterFinish: 
				function () {
					if (typeof IE7 != 'undefined')
						IE7.recalc();
				}
			});
		
	}
	
	subject_image.src = imageData[subject.current_row][3][subject.current_image][0];
}

/**
 * Remove the image
 * @param  
 * @return void
 **/
function subject_reload(){
	new Effect.Fade('subject-holder',{
		afterFinish: function(){
			$('subject-holder').remove();
			subject_show();
		},
		duration:0.5
	});
}

/**
 * Show next image, if the last image is selected it loops back to the first image
 * @param  none
 * @return void
 **/
function subject_prev(){
	subject.current_image = subject.current_image-1;
	
	if(subject.current_image <= 0){
		subject.current_image = 0;
		subject.current_row = subject.current_row-1;
	}	
	if(subject.current_row < 0){ subject.current_row = imageData.length-1; }	
	
	subject_reload();
}

/**
 * Show prev image, if the first image is selected it loops to the last image and works backwards
 * @param  none
 * @return void
 **/
function subject_next(){
	subject.current_image = subject.current_image+1;
	
	if(subject.current_image == (imageData[subject.current_row][3].length)){
		subject.current_image = 0;
		subject.current_row = subject.current_row+1;
	}
	if(subject.current_row > (imageData.length-1)){ subject.current_row = 0; }
	
	subject_reload();
}

/*
If the browser is IE6 all form elements will appear above the dialog window. Only way to fix this is to hide all these elements. 
This function toggles the visbility for all formelements on a page.
*/
var formVisibility = true;

/**
 * Hide/show all form-elements on a page
 * @param  none
 * @return void
 **/
function toggelForms(){
	if(navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0  && (navigator.appVersion.indexOf("Win") != -1)){
		if(formVisibility){
			for(var i = 0; i < document.getElementsByTagName('form').length; i++){
				document.forms[i].style.visibility = 'hidden';
			};
			$('filter').hide();
			formVisibility = false;
		} else {
			for(var i = 0; i < document.getElementsByTagName('form').length; i++){
				document.forms[i].style.visibility = 'visible';
			};
			$('filter').show();
			formVisibility = true;
		};
	};
};


function toggleIEBug(){
	if(navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0  && (navigator.appVersion.indexOf("Win") != -1)){
		if(overview.ieBug){
			$$('form').each(function(element) {
				$(element).hide();
			});
			$$('object').each(function(element) {
				$(element).hide();
			});
			$('filter').hide();
			overview.ieBug = false;
		} else {
			$$('form').each(function(element) {
				$(element).show();
			});
			$$('object').each(function(element) {
				$(element).show();
			});
			$('filter').show();
			overview.ieBug = true;
		}
	}
}

///////////////////////////////////////////////////////////////////////////////////
//
//  Slider
//
///////////////////////////////////////////////////////////////////////////////////

/**
 * Move the slider to a specific location
 * @param  value:Number - a positive number that is convertet to a negative position in px
 * @return void
 **/
function overviewSlideTo(value){
	//new Effect.Move(overview.container_id,{ x:-(value), y:0, mode:overview.mode, duration:overview.duration, transition:Effect.Transitions.linear });
	overview.container_obj.setStyle({ 
		left: ('-'+(Math.round(value)+'px')),
		position: 'relative'
	});
}

/**
 * Move the slider one step right
 * @return void
 **/
function overviewSlideRight(){
	overview.sliderCurrentValue += overview.sliderStep;
	overviewSilder.setValue(overview.sliderCurrentValue);
}

/**
 * Move the slider one step left
 * @return void
 **/
function overviewSlideLeft(){
	overview.sliderCurrentValue -= overview.sliderStep;
	overviewSilder.setValue(overview.sliderCurrentValue);
}

function overview_setSlider(){
	//Set the width of the overviewcontainer
	var width = ((Math.ceil(imageData.length/3))*200)+20+'px';
	overview.container_obj.setStyle({ width: width });
	//-->console.log('-->Window width: ' + document.viewport.getWidth());
	//-->console.log('-->Overview width is:'+width+'px, ');	
	
	if(overviewSilder == undefined){
		//console.log('-->Slider not found. Initing slider.');
		overview_initSlider();
	} else {
		//console.log('-->Updating slider parameters');
		overview_updateSlider();
	}
	
	if(((Math.ceil(imageData.length/3))*200)+20 < document.viewport.getWidth()){
		$('overview-navigation').hide();
		overview.container_obj.setStyle({ marginLeft: 'auto', marginRight: 'auto'});
		//console.log('-->Hide slider');
	} else {
		$('overview-navigation').show();
		overview.container_obj.setStyle({ marginLeft: '20px', marginRight: '20px'});
		//console.log('-->Show slider');
	}
	
}

/**
 * Inits the slider
 * @param  
 * @return void
 **/
function overview_initSlider(){
	//Init the slider
	overviewSilder = new Control.Slider('overview-slider-handle','overview-slider-track',{increment:overview.sliderIncrement, range:$R(0,overview.container_obj.getWidth() - overview.images_obj.getWidth())});
	//-->console.log('-->Slider-range default to : '+overviewSilder.range.max());
	
	//Create a onChange listener for the slider
	overviewSilder.options.onChange = function(value){
		overviewSlideTo(value);
		overview.sliderCurrentValue = value;
	};

	//Create a onSlide listener for the slider
	overviewSilder.options.onSlide = function(value){
		overviewSlideTo(value);
	}
}

function overview_updateSlider(){
	//Re-calculate the range of the slider
	var range_max = overview.container_obj.getWidth() - overview.images_obj.getWidth();
	if(range_max < 0){ range_max = 0 };
	overviewSilder.range = $R(0,range_max);
	
	//-->Debug console.log('-->overview.container_obj - width: ' + overview.container_obj.getWidth());
	//-->Debug console.log('-->overview.images_obj - width: ' + overview.images_obj.getWidth());
	
	//Re-position the handle to the correct position
	overviewSilder.setValue(0);
	//-->console.log('-->Slider-range reset to : '+overviewSilder.range.max());
}

///////////////////////////////////////////////////////////////////////////////////
//
//  Contact view
//
///////////////////////////////////////////////////////////////////////////////////

/**
 * Show contact info lescaps
 * @param  
 * @return void
 **/
function lenscap_show(id,x,y){
 	$('contact-'+id).setStyle({left:x+'px',top:y+'px'});
	new Effect.Scale('contact-'+id,100, Object.extend({
		beforeStart:function(effect){
			$(effect.element).style.display = 'block';
			$(effect.element).setOpacity(0);
			$$('#contact-'+id+' p').each(function(p){p.hide()});
		},
		afterUpdate:function(effect){
			$(effect.element).setOpacity(effect.position);
		},
		scaleFrom:0,
		scaleFromCenter:true,
		afterFinish:function(effect){
			$$('#contact-'+id+' p').each(function(p){
				new Effect.Appear(p,{duration:0.4});
			});
		}
	}, arguments[3] || {}));
}

function contact_show(){
	lenscap_show('info',250,200);
	lenscap_show('logo',650,120);
}

function contact_hide(){
	$('contact-info').hide();
	$('contact-logo').hide();
}
