/**
* Setting .mac class on bodytag if on mac
* - We can then use the .mac selector in CSS to make speciel mac exceptions...
* 
* @param none
* @return Void
*/
function prepare_for_mac()
{
	if(navigator.platform.indexOf("Mac") != -1 || navigator.userAgent.indexOf("Safari") != -1)
	{
		document.body.className = ( navigator.userAgent.indexOf("Safari") != -1 ? 'mac saf' : 'mac ff' );
	}
}

/**
* Submits form if valid form input
* 
* @param Object form_el The form to submit
* @param String default_name Default values for form elements
* @return Boolean
*/
function newsmail_signup(form_el,default_name)
{
	if(form_el)
	{
		var errors	= '';
		if(form_el.name.value == '' || form_el.name.value.toLowerCase() == default_name.toLowerCase())
		{
			errors	+= 'Husk at udfylde dit navn\n';
		}
		if(valid_email(form_el.email.value) === false)
		{
			errors	+= 'Dette er ikke en korrekt e-mail adresse\n';
		}
		if(errors != '')
		{
			alert(errors);
		}
		else
		{
			form_el.submit();
		}
	}
	return false;
}

var globalDir			= 'left';

/**
* Tweens in the case data
* 
* @param String doTween 'true' or 'false' if we may start autotween
* @return Void
*/
function show_case(doTween)
{
	JSTweener.addTween($('tweencase').style,
	{
		time: 1,
		transition: 'easeOutExpo',
		top: 25,
		suffix: {
			top: 'px'
		}/*,
		onComplete: function()
		{
			if(doTween == 'true')
			{
				intervalID	= setTimeout(function() { tween_image(globalDir);	},4000);
			}
		}*/
	});
}

/**
* Clears autotween and tweens the image
* 
* @param String dir The direction to tween ('left' or 'right')
* @return Void
*/
function tween_image_handler(dir)
{
	if(isTweening == false)
	{
		clearTimeout(intervalID);
		tween_image(dir);
	}
	else
	{
		tween_queue.push({ dir: dir, amount: 1 });
	}
}

/**
* Tweens "imagetweener-div" in specific direction
* - Updates the arrow display onComplete
* - Sets interval to start autotween
* 
* @param String dir The direction to tween ('left' or 'right')
* @return Void
*/
var isMouseOver			= false; // Register if we have mouseover, so we can show/hide the arrows on autotween
var isTweening			= false; // Since we don't have the isTweening() method like the actionscript version
var globalImageCount	= 0;
var intervalID;
var nextImage;
var tween_queue = [];

function tween_to_image(to)
{
	if(isTweening === false)
	{
		clearTimeout(intervalID);
		if (to < globalImageCount) 
		{
			globalDir = 'right';
		}
		else 
		{
			globalDir = 'left';
		}
		amount = Math.abs(globalImageCount-to);
		tween_image(globalDir, amount);
	}
	else
	{
		if (tween_queue.length > 0)
			tween_queue = [];

		tween_queue.push({ type: 'to', to: to });
	}
}

function tween_image(dir, amount)
{
	if(isTweening === false)
	{
		isTweening = true; // Lock

		var speed		= 1;
		var transition	= 'easeOutExpo';
		var imagewidth	= 648;
		var arrowleft	= getElementsByClassName('arrowleft')[0];
		var arrowright	= getElementsByClassName('arrowright')[0];
		var arr_image	= getElementsByClassName('image','div',$('imagetweener'));
		var total		= arr_image.length;
		
		var globalDir 	= dir;
		if (!amount) amount = 1;
		var cur_image	= ( globalImageCount + 1 >= total ? arr_image[total-1] : arr_image[globalImageCount] );
		
		// Find new position
		if(dir == 'left')
		{
			var new_pos		= -(imagewidth);
			var next_image	= ( globalImageCount + amount >= total ? arr_image[0] : arr_image[globalImageCount+amount] );
			next_image		= ( globalImageCount == 0 ? arr_image[amount] : next_image );
			next_image.style.left	= imagewidth + 'px';
		}
		else if(dir == 'right')
		{
			var new_pos		= imagewidth;
			var next_image	= ( globalImageCount - amount < 0 ? arr_image[total-1] : arr_image[globalImageCount-amount] );
			next_image.style.left	= -(imagewidth) + 'px';
		}
		
		if (tween_queue.length > 0)
		{
			speed = 0.5;
			transition: 'linear';
		}
		
		JSTweener.addTween(next_image.style,
		{
			time: speed,
			transition: transition,
			left: 0,
			suffix: {
				left: 'px'
			}
		});

		var changeActive = activeChanged = false;
		JSTweener.addTween(cur_image.style,
		{
			time: speed,
			transition: transition,
			left: new_pos,
			suffix: {
				left: 'px'
			},
			onUpdate: function()
			{
				//next_image.style.left	= ( dir == 'left' ? parseInt(cur_image.style.left) - imagewidth : parseInt(cur_image.style.left) + imagewidth ) + 'px';
				
				if (dir == 'left')
				{
					if (parseInt(next_image.style.left)>10)
						changeActive = true;
				}
				else
				{
					if (parseInt(next_image.style.left)<-10)
						changeActive = true;
				}
				if (changeActive && !activeChanged)
				{
					globalImageCount	= ( dir == 'left' ? globalImageCount + amount : globalImageCount - amount );
					globalImageCount	= ( globalImageCount >= total ? 0 : globalImageCount );
					globalImageCount	= ( globalImageCount < 0 ? total - 1 : globalImageCount );

					jQuery('.thumbnail .casehover:visible').css('display','none');
					jQuery('#thumbnail_' + globalImageCount).css('display','block');			
					activeChanged = true;
				}
			},
			onComplete: function()
			{
				isTweening = false; // Unlock
				if(isMouseOver === true)
				{
					//toggle_arrows('show'); // Toggle arrows
				}
				if (tween_queue.length > 0)
				{
					var c = tween_queue.shift();
					if (c.type == 'to')
					{
						tween_to_image(c.to);
					}
					else
					{
						tween_image(c.dir, c.amount);
					}
				}

				// Start autotween
				//intervalID	= setTimeout(function() { tween_image(dir);	},4000); // IE can't understand arguments passed on as the 3rd param to setInterval()
			}
		});
	}
}

/**
* Toggles the display of the arrows used to tween the 'imagetweener-div'
* - Called on mouseover/out from the 'imagetweener-div' and onComplete() from each tween in the tween_image() function
* 
* @param String doaction 'show' or 'hide')
* @return Void
*/
function toggle_arrows(doaction,side)
{
	isMouseOver	= ( doaction == 'show' ? true : false );

	var total = getElementsByClassName('image','div',$('imagetweener')).length;
	if(total > 1)
	{
		if (side=='right')
		{
			var arrowright	= getElementsByClassName('arrowright')[0];
			arrowright.style.display	= ( doaction == 'show' ? 'block' : 'none' );
		}
		else
		{
			var arrowleft	= getElementsByClassName('arrowleft')[0];
			arrowleft.style.display		= ( doaction == 'show' ? 'block' : 'none' );
		}
	}
}

/**
* Tween all the frontpage projects
* - Recursive call on(each)Complete. Initial call from the frontpage pagetype
* 
* @param Number num The number of project to tween
* @return Void
*/
function tween_projects(num)
{
	var arr_project	= getElementsByClassName('project','div',$('latestprojects'));
	var arr_image	= getElementsByClassName('image','div',$('latestprojects'));
	var arr_text	= getElementsByClassName('text','div',$('latestprojects'));

	var total		= arr_project.length;
	var num			= ( num >= total || !num ? 0 : num ); // Find the next or start over
	var opacity		= ( arr_image[num].className == 'image imhidden' ? 0.99 : 0 ); // Since IE doesn't understand opacity, we use a dummy class

	arr_project[num].style.zIndex	= ( opacity == 0 ? 300 : 400 ); // Otherwise the links won't work

	JSTweener.addTween(arr_image[num].style,
	{
		time: 0.7,
		transition: 'linear',
		opacity: opacity,
		onUpdate: function()
		{
			// Make it work in IE
			if(document.all)
			{
				arr_image[num].style.filter='alpha(opacity='+Math.round(this.target.opacity*100)+')';
			}
		},
		onComplete: function()
		{
			// Let it stand for a while if we have just shown it (opacity is the value before the tween)
			if(opacity >= 0.99)
			{
				arr_image[num].style.opacity	= 1;
				if(document.all)
				{
					arr_image[num].style.filter='alpha(opacity=100)';
				}
				arr_image[num].className		= 'image imvisible';

				// Show text
				for(var i=0; i<arr_text.length; i++)
				{
					arr_text[i].style.opacity	= ( i == num ? 1 : 0 );
					if(document.all)
					{
						arr_text[i].style.filter	= ( i == num ? 'alpha(opacity=100)' : 'alpha(opacity=0)' );
					}
					arr_text[i].className		= ( i == num ? 'text imvisible' : 'text imhidden' );
				}

				setTimeout(function(){tween_projects(num); },4500);
			}
			else // show the next image immediately
			{
				arr_image[num].className	= 'image imhidden';
				arr_text[num].className		= 'text imhidden';
				num++;
				tween_projects(num);
			}
		}
	});
}

/**
* Sets up mousefollow event for the frontpage button
* - Initial call from the frontpage_kampagne pagetype
* 
* @param Event e Event
* @return Void
*/
function follow_mouse(e)
{
	if(!e) e = window.event;
	var offsetX	= 50;
	var offsetY	= 15;
	var scrollY	= ( document.all ? document.documentElement.scrollTop : window.pageYOffset );
	var minY	= 228; //210 + $('frontpage_btn').offsetHeight
	var maxY	= document.body.offsetHeight - $('frontpage_btn').offsetHeight;
	var maxX	= document.body.clientWidth - $('frontpage_btn').offsetWidth;
	var width	= $('frontpage_btn').offsetWidth;
	var height	= $('frontpage_btn').offsetHeight;

	// left position
	$('frontpage_btn').style.left	= ( e.clientX < offsetX ? 0 : e.clientX - offsetX ) + 'px'; // Border left
	$('frontpage_btn').style.left	= ( parseInt($('frontpage_btn').style.left)+width > document.body.clientWidth ? maxX : parseInt($('frontpage_btn').style.left) ) + 'px';

	// Top position
	if( (e.clientY + scrollY) < minY )
	{
		$('frontpage_btn').style.display	= 'none';
		//$('frontpage_btn').style.top 		= (minY - $('frontpage_btn').offsetHeight) + 'px';
	}
	else if( (e.clientY + scrollY)  > document.body.offsetHeight )
	{
		$('frontpage_btn').style.display	= 'block';
		$('frontpage_btn').style.top 		= maxY + 'px';
	}
	else
	{
		$('frontpage_btn').style.display	= 'block';
		$('frontpage_btn').style.top 		= (e.clientY + scrollY - offsetY) + 'px';
	}
}

/**
* Toggles case hovering, setting display style on element
* 
* @param String el Reference to the case element to display
* @return Void
*/
function case_hover(el)
{
	if ('thumbnail_' + globalImageCount != el) $(el).style.display = ( $(el).style.display == 'none' || $(el).style.display == '' ? 'block' : 'none' );
}

// Add "onLoad events"
jQuery(document).ready(prepare_for_mac);

jQuery(document).ready(function ()
{
	jQuery('#page #articlepage.cases .column').mouseover(function ()
	{
		jQuery(this).addClass('column_hover');//find('.casehover').css('display','block');
		jQuery(this).find(".cc-sifr-replacement").find("object").get(0).doHover();
	});
	jQuery('#page #articlepage.cases .column').mouseout(function ()
	{
		jQuery(this).removeClass('column_hover');//jQuery(this).find('.casehover').css('display','none');
		jQuery(this).find(".cc-sifr-replacement").find("object").get(0).removeHover();
	});
	jQuery('#page #articlepage.cases .column').click(function ()
	{
		window.location = jQuery(this).find('.casehover').attr('href');
	});
});