var site_map_open = true,
	sub_nav_open = -1,
	ajax_ready = true,
	ajax_timer = 0,
	active_product = 1,
	ie6 = false,
	ie7 = false,
	ie = false,
	animations = {},
	products = [],
	timeouts = [],
	nav_timeouts = {},
	href_to_go_to = '',
	plugin = false;

//required for opera
history.navigationMode = 'compatible';

//Create a boolean variable to check for a valid Internet Explorer instance.
var xmlhttp = false;
//Check if we are using IE.
try
{
	//If the Javascript version is greater than 5.
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
	//If not, then use the older active x object.
	try
	{
		//If we are using Internet Explorer.
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (E)
	{
		//Else we must be using a non-IE browser.
		xmlhttp = false;
	}
}

if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
	xmlhttp = new XMLHttpRequest();
}


if (window.location.href.indexOf('recruitment') != -1)
{
	plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
	
	if (plugin)
	{
		var newjs1=document.createElement('script');
		newjs1.type='text/javascript';
		newjs1.src=PATH+'js/swfupload.js';
		document.getElementsByTagName('head')[0].appendChild(newjs1);
		
		var newjs2=document.createElement('script');
		newjs2.type='text/javascript';
		newjs2.src=PATH+'js/fileprogress.js';
		document.getElementsByTagName('head')[0].appendChild(newjs2);
		
		var newjs3=document.createElement('script');
		newjs3.type='text/javascript';
		newjs3.src=PATH+'js/handlers.js';
		document.getElementsByTagName('head')[0].appendChild(newjs3);
	}
}

function $(obj_id){ return document.getElementById(obj_id); }

function make_request(server_page, obj_id, append)
{
	if (!append) append = false;
	if (!ajax_ready)
	{
		if (!ajax_timer) ajax_timer = time();
		else if (time() - ajax_timer > 5000)
		{
			ajax_ready = true;
			ajax_timer = 0;
		}
		setTimeout('make_request("'+server_page+'", "'+obj_id+'", "'+append+'")', 100);
	}
	else
	{
		ajax_ready = false;
		xmlhttp.open("GET", server_page);
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
			{
				var content = xmlhttp.responseText;
				if (null != $(obj_id))
				{
					if (append) $(obj_id).innerHTML += content;
					else $(obj_id).innerHTML = content;
					var ajaxScript = $(obj_id).getElementsByTagName("script");
					var l = ajaxScript.length;
					if(l)
					{
						for (x = 0; x < l; x++)
						{
							try
							{
								eval(ajaxScript[x].innerHTML);
							}
							catch(err)
							{
								log(err);
							}
						}
					}
				}
				xmlhttp.onreadystatechange = function(){};
				ajax_ready = true;
			}
		}
		xmlhttp.send(null);
	}
}

function log()
{
    if(typeof(console) != 'undefined')
    {
		for(var i = 0; i < arguments.length; i++)
		{
			console.log(arguments);
		}
    }
}

function preload_images(images)
{
	var d = document;
	if(d.images)
	{
		if(!d.imgs) d.imgs = new Array();
		num_images = d.imgs.length;
		for(i = 0; i < images.length; i++)
		{
			d.imgs[num_images] = new Image();
			d.imgs[num_images++].src = images[i];
		}
	}
}

function swap_image(img_id, src)
{
	var img_obj = $(img_id);
	if(img_obj) img_obj.src = src;
}

function focus_first_nav(nav_id)
{
	var nav_obj = $(nav_id);
	if(!nav_obj) return;
	log('focusing', nav_obj.childNodes[1].firstChild, nav_obj.focused);
	if(!nav_obj.focused)
	{
		nav_obj.childNodes[1].firstChild.focus();
		nav_obj.focused = true;
	}
	log('focused', nav_obj.focused);
}

function unfocus_first_nav(nav_id)
{
	var nav_obj = $(nav_id);
	if(!nav_obj) return;
	log('unfocusing', nav_obj.focused);
	if(nav_obj.focused)
	{
		nav_obj.childNodes[1].firstChild.blur();
		nav_obj.focused = false;
	}
}

function show_drop_nav(nav_id)
{
	if(nav_timeouts[nav_id]) clearTimeout(nav_timeouts[nav_id]);
	
	var nav_obj = $(nav_id);
	var nav_wrap_obj = $(nav_id.replace('nav', 'nav_wrap'));
	if(!nav_obj) return;
	
	nav_obj.style.display = 'block';
	
	if(ie7) return;
	
	nav_wrap_obj.style.zIndex = 1;
	
	var f = nav_obj.offsetHeight;
	
	if(!animations[nav_wrap_obj.id])
	{
		set_height_animation(nav_wrap_obj, 0, f);
	}
	animations[nav_wrap_obj.id].seekTo(1);
}

function set_hide_drop_nav_timeout(nav_id)
{
	nav_timeouts[nav_id] = setTimeout(function(){hide_drop_nav(nav_id);}, 250);
}

function hide_drop_nav(nav_id)
{
	clearTimeout(nav_timeouts[nav_id]);
	
	var nav_obj = $(nav_id);
	var nav_wrap_obj = $(nav_id.replace('nav', 'nav_wrap'));
	if(!nav_obj) return;
	
	//unfocus_first_nav(nav_id);
	
	if(ie7)
	{
		nav_obj.style.display = 'none';
		return;
	}
	
	nav_wrap_obj.style.zIndex = 0;
	
	animations[nav_wrap_obj.id].seekTo(0);
}

function toggle_site_map(path)
{
	var s;
	var f;
	var _site_map_title = $('site_map_title');
	var _site_map_content = $('site_map_content');
	var _site_map_content_inner = $('site_map_content_inner');
	
	if(ie6)
	{
		if(site_map_open) _site_map_content.style.display = 'none';
		else _site_map_content.style.display = 'block';
	}
	else
	{
		if(site_map_open)
		{
			_site_map_title.src = _site_map_title.src.replace('minus', 'plus');
			s = _site_map_content_inner.offsetHeight;
			f = 0;
		}
		else
		{
			_site_map_title.src = _site_map_title.src.replace('plus', 'minus');
			s = 0;
			f = _site_map_content_inner.offsetHeight;
		}
		if(!animations[_site_map_content.id])
		{
			set_height_animation(_site_map_content, s, f);
		}
		animations[_site_map_content.id].toggle();
	}
	
	site_map_open = !site_map_open;
	
	make_request(PATH + 'ajax/toggle_site_map.php?open=' + site_map_open);
}

function set_height_animation(obj, start, finish, duration)
{
	if(!duration) duration = 500;
	animations[obj.id] = new Animator({
		transition: Animator.makeEaseOut(1),
		duration: duration
	}).addSubject(new NumericalStyleSubject(obj, 'height', start, finish));
}

function equalise_heights(objs)
{
	var max_height = 0;
	var l = objs.length;
	for(var i = 0; i < l; i++)
	{
		objs[i] = $(objs[i]);
		if(objs[i] && objs[i].offsetHeight > max_height) max_height = objs[i].offsetHeight;
	}
	for(var i = 0; i < l; i++) objs[i].style.height = max_height + 'px';
}

function toggle_sub_nav(id)
{
	var s;
	var f;
	var prev_open = sub_nav_open;
	if(sub_nav_open > -1)
	{
		var to_close_wrap = $('sub_nav_wrap_' + sub_nav_open);
		f = 0;
		s = to_close_wrap.offsetHeight;
		if(ie6)
		{
			to_close_wrap.style.height = f + 'px';
		}
		else
		{
			if(!animations[to_close_wrap.id])
			{
				set_height_animation(to_close_wrap, s, f);
			}
			animations[to_close_wrap.id].toggle();
		}
		var sub_nav_toggle = $('sub_nav_toggle_' + sub_nav_open);
		sub_nav_toggle.firstChild.src = sub_nav_toggle.firstChild.src.replace('minus', 'plus');
		//var sub_nav_link = $('sub_nav_link_' + sub_nav_open);
		//if(sub_nav_link.className != 'act') sub_nav_link.innerHTML = sub_nav_link.innerHTML.replace('<strong>', '').replace('</strong>', '');
		sub_nav_open = -1;
	}
	if(id != prev_open)
	{
		var to_open_nav = $('sub_nav_' + id);
		var to_open_wrap = $('sub_nav_wrap_' + id);
		s = 0;
		f = to_open_nav.offsetHeight;
		if(ie6)
		{
			to_open_wrap.style.height = f + 'px';
		}
		else
		{
			if(!animations[to_open_wrap.id])
			{
				set_height_animation(to_open_wrap, s, f);
			}
			animations[to_open_wrap.id].toggle();
		}
		var sub_nav_toggle = $('sub_nav_toggle_' + id);
		sub_nav_toggle.firstChild.src = sub_nav_toggle.firstChild.src.replace('plus', 'minus');
		//var sub_nav_link = $('sub_nav_link_' + id);
		//if(sub_nav_link.className != 'act') sub_nav_link.innerHTML = '<strong>' + sub_nav_link.innerHTML + '</strong>';
		sub_nav_open = id;
	}
}

function trigger_slideshow(src)
{
	var _home_main_img = $('home_main_img');
	if(src == _home_main_img.firstChild.src) return;
	if(ie6)
	{
		continue_slideshow(src);
		return;
	}
	var options = {
		onComplete: function()
		{
			continue_slideshow(src);
		}
	};
	if(!animations[_home_main_img.id])
	{
		set_fade_down(_home_main_img, options);
	}
	else animations[_home_main_img.id].setOptions(options);
	animations[_home_main_img.id].seekTo(1);
}

function continue_slideshow(src)
{
	var _home_main_img = $('home_main_img');
	_home_main_img.firstChild.src = src;
	if(ie6) return;
	animations[_home_main_img.id].setOptions({onComplete: function(){}});
	animations[_home_main_img.id].seekTo(0);
}

function set_fade_down(obj, options)
{
	animations[obj.id] = new Animator(options).addSubject(new NumericalStyleSubject(obj, 'opacity', 1, 0));
}

function set_multi_fade_down(objs, options)
{
	animations[objs[0].id] = new Animator(options).addSubject(new NumericalStyleSubject(objs, 'opacity', 1, 0));
}

function set_fade_up(obj, options)
{
	animations[obj.id] = new Animator(options).addSubject(new NumericalStyleSubject(obj, 'opacity', 0, 1));
}

function set_multi_fade_up(objs, options)
{
	animations[objs[0].id] = new Animator(options).addSubject(new NumericalStyleSubject(objs, 'opacity', 0, 1));
}

function show_product(index)
{
	if(!products) return;
	if(!products[index-1]) return;
	if(ie6)
	{
		set_product_data(index);
		return;
	}
	var obj_sufxs = ['image', 'text_inner'];
	if(!ie) obj_sufxs.push('title');
	var objs = [];
	for(var i = 0; i < obj_sufxs.length; i++)
		objs.push($('products_detail_' + obj_sufxs[i]));
	var options = {
		onComplete: function()
		{
			set_product_data(index, objs[0].id);
		}
	};
	if(!animations[objs[0].id])
	{
		set_multi_fade_down(objs, options);
	}
	else animations[objs[0].id].setOptions(options);
	animations[objs[0].id].seekTo(1);
}

function set_product_data(index, animation_key)
{
	var p = products[index-1];
	var i = 1;
	var	_product_item_link = $('product_item_link_' + i);
	while(_product_item_link)
	{
		_product_item_link.className = '';
		i++;
		_product_item_link = $('product_item_link_' + i);
	}
	$('product_item_link_' + index).className = 'act';
	$('products_detail_image').src = p.image;
	$('products_detail_title').innerHTML = p.title;
	var title = document.title.split('/');
	title[0] = p.title+' ';
	title = title.join('/');
	document.title = title;
	if($('products_detail_count_index1')) $('products_detail_count_index1').innerHTML = index;
	if($('products_detail_count_index2')) $('products_detail_count_index2').innerHTML = index;
	$('products_detail_text_inner').innerHTML = p.text;
	
	active_product = (+index);
	window.location.hash = '#' + active_product;
	
	if(ie6) return;
	if(animations[animation_key])
	{
		animations[animation_key].setOptions({onComplete: function(){}});
		animations[animation_key].seekTo(0);
	}
}

function preload_product_images()
{
	if(!products) return;
	var products_length = products.length;
	var images = [];
	for(var i = 0; i < products_length; i++)
	{
		images.push(products[i].image);
	}
	preload_images(images);
}

function products_next()
{
	var next_product = active_product + 1;
	if(next_product > products.length)
	{
		next_product = 1;
	}
	show_product(next_product);
}

function products_previous()
{
	var previous_product = active_product - 1;
	if(previous_product < 1)
	{
		previous_product = products.length;
	}
	show_product(previous_product);
}

function scroll_products(step)
{
	var _products_detail_nav_content = $('products_detail_nav_content');
	var left = _products_detail_nav_content.offsetLeft + (94 * step);
	if(left > 0) left = 0;
	if(left < $('products_detail_nav_wrap').offsetWidth - _products_detail_nav_content.offsetWidth)
	{
		left = $('products_detail_nav_wrap').offsetWidth - _products_detail_nav_content.offsetWidth;
	}
	if(ie6)
	{
		_products_detail_nav_content.style.left = left  + 'px';
		return;
	}
	if(animations[_products_detail_nav_content.id]) return;
	var options = {
		onComplete: function()
		{
			animations[_products_detail_nav_content.id] = false;
		}
	};
	animations[_products_detail_nav_content.id] = new Animator(options).addSubject(new NumericalStyleSubject(_products_detail_nav_content, 'left', _products_detail_nav_content.offsetLeft, left));
	animations[_products_detail_nav_content.id].seekTo(1);
}

function register_link_actions()
{
	if(ie) return;
	var links = document.getElementsByTagName('A');
	var links_length = links.length;
	for(var l = 0; l < links_length; l++)
	{
		if(links[l].href.indexOf('#') > -1) continue;
		if(links[l].target && links[l].target == '_blank') continue;
		if(links[l].href.indexOf('mailto:') > -1) continue;
		links[l].onclick = function()
		{
			on_link_click(this);
			return false;
		};
	}
}

function on_link_click(obj)
{
	var _content = $('content');
	href_to_go_to = obj.href;
	var options = {
		onComplete: function()
		{
			go_to_link();
		}
	};
	var objs = [$('content'), $('site_map'), $('footer')];
	if(!animations[objs[0].id])
	{
		set_multi_fade_down(objs, options);
		animations[objs[0].id].seekTo(1);
	}
	else
	{
		animations[objs[0].id].setOptions(options);
		animations[objs[0].id].seekTo(0);
	}
}

function go_to_link(override)
{
	if(override)
	{
		href_to_go_to = override;
	}
	window.location = href_to_go_to;
}

function init()
{	
	if(ie) return;
	
	var objs = [$('content'), $('site_map'), $('footer')];
	if(!animations[objs[0].id])
	{
		set_multi_fade_up(objs);
		animations[objs[0].id].seekTo(1);
	}
	else
	{
		animations[objs[0].id].seekTo(0);
	}
}

function hide_content()
{
	if(ie) return;
	{
		var objs = [$('content'), $('site_map'), $('footer')];
		for(var i = 0; i < objs.length; i++)
		{
			objs[i].style.width = objs[i].offsetWidth + 'px';
			objs[i].style.opacity = 0;
			objs[i].style.filter = "alpha(opacity=0)";
		}
	}
}

function get_viewport_dimensions()
{
	return {
		width: self.innerWidth || (document.body.offsetWidth || document.documentElement.offsetWidth),
		height: self.innerHeight || (document.body.offsetHeight || document.documentElement.offsetHeight)
	};
}

function open_terms_page()
{
	window.open( PATH + 'terms.php', (new Date()).getTime(), [
	// array joining is faster than string concatenation
		['height=', 600].join(''),
		['width=', 972].join(''),
		'top=50',
		'left=50',
		'scollbars=yes',
		'resizeable=yes',
		'status=yes',
		'titlebar=yes',
		'toolbar=yes'
	].join(',') );
}

function get_jobs(u)
{
	var hash = window.location.hash.replace('#', '');
	make_request(PATH+'ajax/jobs.php?h='+hash+'&u='+u, 'recruitment');
}

function job_filter(filter_group, filter_item)
{
	var hash = window.location.hash.replace('#', '');
	if (hash)
	{
		var hashes = hash.split('/');
		for (var i in hashes)
		{
			if (hashes[i] == filter_item)
			{
				return false;
			}
		}
		
		var new_hash = '';
		var added = false;
		
		for (var j in hashes)
		{
			found = false;
			if (job_filters && job_filters[filter_group]) for (var i in job_filters[filter_group])
			{
				if (hashes[j] == job_filters[filter_group][i].url) found = true;
			}
			
			if (!found) new_hash += (new_hash ? '/' : '')+hashes[j];
			else if (filter_item)
			{
				new_hash += (new_hash ? '/' : '')+filter_item;
				added = true;
			}
		}
		if (!added && filter_item) new_hash = new_hash+(new_hash ? '/' : '')+filter_item;
		window.location.hash = new_hash;
	}
	else window.location.hash = filter_item;
	get_jobs(effective_nav);
	return false;
}

function start_slideshow()
{
	if(swfobject.ua.pv[0]) return false;
	
	var num_slides = 0;
	var first_slide = false;
	
	for(var i in slideshow_items)
	{
		if (!first_slide) first_slide = i;
		num_slides++;
	}
	
	var slide_timer = (60 / num_slides).toFixed(0) * 1000;
	var timer_offset = 5000;
	var slide_num = 0;
	
	for(var i in slideshow_items)
	{
		timeouts[timeouts.length] = setTimeout("slide_home("+i+");", (timer_offset + (slide_num * slide_timer)));
		slide_num++;
	}
	
	return false;
}

function slide_home(slide_id)
{
	if (!slide_id) return false;
	var slide = slideshow_items[slide_id];
	if (!slide) return false;
	var previous_slide_id = 0;
	var slide_num = 1;
	
	for(var i in slideshow_items)
	{
		if (slide != slideshow_items[i]) previous_slide_id = i;
		else break;
		slide_num++;
	}
	
	if ($('home_button_'+i).offsetLeft >= $('slideshow_buttons_outer').offsetWidth)
	{
		var move_to = ($('slideshow_buttons_outer').offsetWidth - $('home_button_'+i).offsetLeft - 52) +'px';
		$('slideshow_buttons_inner').style.left = move_to;
	}
	
	if (previous_slide_id)
	{
		$('button_cover_'+previous_slide_id).style.opacity = 0.5;
		$('button_cover_'+previous_slide_id).style.filter = "alpha(opacity=50)";
	}
	
	$('home_main_img').firstChild.src = PATH+'images/content/home/main/'+slide.image;
	$('caption_image').src = PATH+'images/content/home/text_image/'+slide.extra_image;
	
	$('button_cover_'+slide_id).style.opacity = 0;
	$('button_cover_'+slide_id).style.filter = "alpha(opacity=0)";
}

function slide_move(amount)
{
	var move_to = $('slideshow_buttons_inner').offsetLeft + amount;
	if (move_to <= 0 && $('slideshow_buttons_inner').offsetWidth + 52 + move_to >= $('slideshow_buttons_outer').offsetWidth)
		$('slideshow_buttons_inner').style.left = move_to + 'px'
	return false;
}

function clear_all_timeouts()
{
	if (!timeouts.length) return;
	for (var i in timeouts)
	{
		if (timeouts[i])
		{
			clearTimeout(timeouts[i]);
			timeouts[i] = false;
		}
	}
}

function change_home(slide_id)
{
	clear_all_timeouts();
	if (!slide_id) return false;
	var slide = slideshow_items[slide_id];
	if (!slide) return false;
	
	for(var i in slideshow_items)
	{
		if (i == slide_id) continue;
		$('button_cover_'+i).style.opacity = 0.5;
		$('button_cover_'+i).style.filter = "alpha(opacity=50)";
	}
	
	$('home_main_img').firstChild.src = PATH+'images/content/home/main/'+slide.image;
	$('caption_image').src = PATH+'images/content/home/text_image/'+slide.name+'.png';
	
	$('button_cover_'+slide_id).style.opacity = 0;
	$('button_cover_'+slide_id).style.filter = "alpha(opacity=0)";
	
	return false;
}
