var DNG_Site = new Class({
	
	Implements: Options,
	
	options : {
		news_object: null,
		work_object: null,
		about_object: null,
		proj_types: null,
		default_news_item: 3,
		default_work_item: 135, // needs to be changed...
		default_culture_item: 1,
		default_about_item: 1,
		default_campaign_projects: null,
		background_objects: null,
		news_page: 0
	},
	
	initialize: function(options) {
		this.setOptions(options);
		// This is supposed to make any rel="external" anchor tags have target="_blank"...
		// this.bindExternalLinks();
		
		this.fit(0);
		/*
		if (! window.location.hash)
		{
			this.fit(0);
			this.hide_site = true;
		}
		else
		{
			this.dismissTakeover();
		}
		*/
		
		this.eatHash.periodical(100, this);
		this.getBackground('default',1);
	},
	
	buildAccordions: function(nav_container) {
		nav_container.setStyle("display","");
		
		this.campaign_accordians = new Array();
		
		var campaign_containers = $$('.campaign-accordion');
		campaign_containers.each( function(item){
			var id = item.id.split('_')[1]; //client id
			campaign_accordians = new Accordion('div.campaign-toggler_'+id,'div.campaign-element_'+id,{
				opacity: true,
				onActive: function(toggler,element){
					toggler.addClass("nav_item_l3-selected");
					toggler.getParent().getParent().setStyle("height","auto");
				},
				onBackground: function(toggler, element){
					toggler.removeClass("nav_item_l3-selected");
					toggler.getParent().getParent().setStyle("height","auto");
				},
				
				
				transition: Fx.Transitions.Bounce.easeOut,
				duration: 1000,
				isNested: true,
				show: 0,
				alwaysHide: true		
			}, $('campaign-accordion_'+id));
		});
						
		this.work_accordion = new myAccordion('div.work-toggler', 'div.work-element', {
			opacity: true,
			onActive: function(toggler, element){
				toggler.addClass("nav_item_l2-selected");
			},

			onBackground: function(toggler, element){
				toggler.removeClass("nav_item_l2-selected");
			},
			transition: Fx.Transitions.Bounce.easeOut,
			duration: 1000,
			is_nested: true
		}, $('work-accordian'));
		
		this.about_accordion = new myAccordion('div.about-toggler', 'div.about-element', {
			opacity: false,
			onActive: function(toggler, element){
				toggler.addClass("nav_item_l2-selected");
			},

			onBackground: function(toggler, element){
				toggler.removeClass("nav_item_l2-selected");
			},
			
			onComplete: function() {
				
			},
			transition: Fx.Transitions.Bounce.easeOut,
			duration: 1000,
			is_nested: true
		}, $('about-accordian'));
		
		this.accordion = new myAccordion('div.top-toggler', 'div.top-element', {
			opacity: true,
			onActive: function(toggler, element){
				toggler.addClass("nav_item_l1-selected");
			},

			onBackground: function(toggler, element){
				toggler.setStyle('color', '#222');
				toggler.removeClass("nav_item_l1-selected");
				if (element.getStyle("height") === "auto")
				{
					element.setStyle("height",element.getScrollSize().y);
				}
			},
	
			transition: Fx.Transitions.Bounce.easeOut,
			duration: 1000,
			alwaysHide: true,
			show: -1
		}, nav_container);
		
		
		if (this.hide_site)
		{
			$('wrapper').setStyle("display","none");
		}
	},
	
	loadTooltips: function(elements) {
		tooltips = new myTips(elements,
					{
						className: 'tooltip_container',
						fixed:true,
						offsets:{'y':0,'x':3},
						onShow: function(toolTip) {
							this.tip.fade('in');
						},
						onHide: function(toolTip) {
							this.tip.fade('out');
						}
					});
	},
	
	// findInTree shortcut
	fit: function(heading,id,about_identifier) {
		switch (heading)
		{
			case 0:
			case '0':
			case 'home':
				if (id == 1) this.loadTemplate('home_2.tpl');
				else if (id == 2) this.loadTemplate('home_3.tpl');
				else this.loadTemplate('home.tpl');
			break;
			
			case 1:
			case '1':
			case 'news':
				this.accordion.display(0);
				var page_id = $('news-'+id).getParent().getProperty('id');
				
				this.newsPage(Number(page_id.substr(page_id.lastIndexOf('-')+1)));
				this.loadContentByID('news',id);
			break;
			
			case 2:
			case '2':
			case 'work':
				//find the index of the client that the item is in
				var saved_index;
				this.options.work_object.each(function(item,index) {
					if ($type(item.cats) == 'array') return;
					for (var key in item.cats)
					{
						if (item.cats[key].contains(id + ""))
						{
							saved_index = index;
						}
					}				
				});
				var w_accord = this.work_accordion;
				this.accordion.display(1).chain(function() {
					if (w_accord.container.getParent().getStyle("height") != "auto" || w_accord.container.getParent().getStyle("height") != '' )
						w_accord.container.getParent().setStyle("height", "auto");
					w_accord.display(saved_index);
				});
				this.loadContentByID('work',id);				
			break;
			
			case 3:
			case '3':
			case 'about':
				var ab_accord = this.about_accordion;
				this.accordion.display(2).chain(function() {
					if (ab_accord.container.getParent().getStyle("height") != "auto" || ab_accord.container.getParent().getStyle("height") != '' )
						ab_accord.container.getParent().setStyle("height", "auto");
					ab_accord.display(id);
				});

				this.loadContentByID('about',this.options.about_object[id].items[about_identifier]);
			break;
			
			case 4:
			case '4':
			case 'contact':
				this.accordion.display(3); // contact item
				this.loadContentByID('contact');
			break;
		}
	},
	
	getBackground: function(type,type_id)
	{
		switch (type)
		{
			case 'home':
				if (this.options.background_objects[type] && this.options.background_objects['home'][1])
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['home'][1]+')');
				else
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['default'][1]+')');
			break;
			
			case 'news':
				if (this.options.background_objects[type] && this.options.background_objects[type][type_id])
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects[type][type_id]+')');
				else
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['default'][1]+')');
			break;
			
			case 'work':
				var client_id;
					this.options.work_object.each(function(item,index) {
						if ($type(item.cats) == 'array') return;
						for (var key in item.cats)
						{
							if (item.cats[key].contains(type_id + "")) client_id = item['id'];
						}				
				});
				var campaign_id; //check campaigns
				this.options.work_object.each(function(item,index){
					if(item['id'] == client_id)
						for(var key in item.campaigns)
							if(item.campaigns[key].contains(type_id + "")) {campaign_id = key; break;}
				});
				if (this.options.background_objects['campaign'] && this.options.background_objects['campaign'][campaign_id])
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['campaign'][campaign_id]+')');
				else if (this.options.background_objects[type] && this.options.background_objects[type][client_id])
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects[type][client_id]+')');
				else
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['default'][1]+')');
			break;
			
			case 'about':
				var section_id;
					this.options.about_object.each(function(item,index){
							if(item.items.contains(type_id))
								section_id = item['id'];
						});
				if (this.options.background_objects['about'] && this.options.background_objects['about'][section_id])
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['about'][section_id]+')');
				else
					$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['default'][1]+')');
			break;
			
			default:
				$(document.body).setStyle('background-image','url(images/backgrounds/'+this.options.background_objects['default'][1]+')');
			break;
		}
		
	},
	
	loadContentByID: function(type,id,no_recalc)
	{
		//if (! id) id = selected_items[type];
		try {
			pageTracker._trackPageview(type+"_"+id);
		} catch(err) {}
		
		var container = $('content_container');
		
	    switch (type)
		{
			case 'home':
				if (id) this.fit(0,id);
				else this.fit(0);
				this.accordion.display(-1);
				if (id) this.current_hash = "#fit(0,"+id+")";
				else this.current_hash = "#fit(0)";
				window.location.hash = this.current_hash;
				this.getBackground(type,1);
			break;
			
			case 'news':
				if (! id) id = this.options.default_news_item;
				this.loadNewsTemplate(container,id);
				if (! no_recalc)
				{
					this.current_hash = "#fit(1,"+id+")";
					window.location.hash = this.current_hash;
				}
				this.getBackground(type,id);
			break;
			
			case 'work':
				if (! id) 
				{
					this.fit(2,this.options.default_work_item);
					id = this.options.default_work_item;
				}
				this.loadWorkTemplate(container,id);
				if (! no_recalc)
				{
					this.current_hash = "#fit(2,"+id+")";
					window.location.hash = this.current_hash;
				}
				this.getBackground(type,id);
			break;
			
			case 'culture':
				if (! id)
				{
					id = this.options.default_culture_item;
				}
				this.loadAboutTemplate(container,id);
				if (! no_recalc)
				{
					this.current_hash = "#fit(3,1,"+id+")";
					window.location.hash = this.current_hash;
				}
			break;
			
			case 'about':
				if (! id) id = this.options.default_about_item;
				this.loadAboutTemplate(container,id);
				var el = $('about_'+id);
				if(el)
				{
					el.getParent().getElements("div[class$=selected]").each(function(the_el){
						the_el.removeClass("nav_item_l2b-selected");
					});
					el.addClass("nav_item_l2b-selected");
				}
				
				if (! no_recalc)
				{
					var saved_index,about_identifier;
					this.options.about_object.each(function(about_item,index) {
						if (about_item.items.indexOf(id+'') != -1)
						{
							about_identifier = about_item.items.indexOf(id+'');
							saved_index = index;
						}
					});
					this.current_hash = "#fit(3,"+saved_index+","+about_identifier+")";
					window.location.hash = this.current_hash;
				}
				this.getBackground(type,id);
			break;
			
			case 'contact':
				this.loadTemplate('contact.tpl');
				if (! no_recalc)
				{
					this.current_hash = "#fit(4)";
					window.location.hash = this.current_hash;
				}
				this.getBackground('default',1);
			break;
		}
	},
	
	loadNewsTemplate: function(container,id) {
		$('logobar').className = "logobar-news";
		var this_class = this;
		var myFx = new Fx.Tween(container,{ property: 'opacity', link: 'cancel' });
		myFx.start(0).chain(function() {
			var req = new Request({
				url: 'news.php',
				data: { 'id' : id, 'headless' : 1 },
				//update: container,
				onComplete: function(responseText, responseXML) {
					container.empty().set('html',responseText);
					news_item_id = $("item_id").value;
					//selected_items.news = id;
				
					$$('.news-item').each(function(el){
						el.removeClass("nav_item_l2b-selected");
					})
					$("news-" + id).addClass("nav_item_l2b-selected");
					container.fade('in');
					
					this_class.bindExternalLinks();
				}
			}).get();
			
			if (! req) 
			{
		    	container.innerHTML = '<div class="tab-error">Unable to request data, check your browser settings!</div>';
		    }
		});
	},
	
	loadWorkTemplate: function(container, id) {
		$('logobar').className = "logobar-work";
		var myFx = new Fx.Tween(container,{ property: 'opacity',link: 'cancel'});
		myFx.start(0).chain(function() {
			var req = new Request({
				url: 'work.php',
				data: { 'id' : id, 'headless' : 1 },
				//update: container,
				onComplete: function(responseText, responseXML) {
					container.empty().set('html',responseText);
					//selected_items.work = id;
					$$('.work-item').each(function(el){
						el.removeClass("nav_cat_item-selected");
					});
					$("work-" + id).addClass("nav_cat_item-selected").removeProperty("style");
					container.fade('in');
					
					var build_swiff = false;
					var swf_width, swf_height;
					
					if (proj_types[id] == "graphic")
					{
						//handling this is the generic
						var sq_res = SqueezeBox.assign($$('a.remooz'), { overlayOpacity: 0.8 });
						//SqueezeBox.assign($$('a.iframe'), { handler:'iframe',size: {x:800,y:600} });
					}
					else if (proj_types[id] == "audio")
					{
						if (!Browser.Plugins.Flash.version >= 8)
						{
							$('flash_version').innerHTML = Browser.Plugins.Flash.version;
							return;
						}
						
						build_swiff = true;
						swf_width = 320;
						swf_height = 60;
						media_extension = ".mp3";
					}
					else if (proj_types[id] == "video")
					{
						if (!Browser.Plugins.Flash.version >= 9) 
						{
							$('flash_version').innerHTML = Browser.Plugins.Flash.version;
							return;
						}
						
						build_swiff = true;
						swf_width = 480;
						swf_height = 380;
						media_extension = ".flv";
					}
					
					if (build_swiff)
					{
						var my_swf = new Swiff('mediaplayer.swf',
							{
								id: 'flash-video',
								container: 'flv_video',
								width: swf_width,
								height: swf_height,
								params: { wmode: 'transparent',	bgcolor: '#ffffff' },
								vars: {	width: swf_width, height: swf_height ,file: media_root + "/" + id + media_extension,usefullscreen:'false', backcolor: '0xDAE4ED',lightcolor:'0x717172',autostart:true }
							});
					}
				}
			}).get();
			
			if (! req) container.innerHTML = '<div class="tab-error">Unable to request data, check your browser settings!</div>';
		});
	},
	
	loadAboutTemplate: function(container, id)
	{
		$('logobar').className = "logobar-news";
		var myFx = new Fx.Tween(container,{ property: 'opacity',link: 'cancel'});
		myFx.start(0).chain(function() {
			var req = new Request({
				url: 'about.php',
				data: { 'id' : id, 'headless' : 1 },
				//update: container,
				onComplete: function(responseText, responseXML) {
					container.empty().set('html',responseText);
					container.fade('in');
					attachSqueezeBox();
				}
			}).get();
			
			if (! req) container.innerHTML = '<div class="tab-error">Unable to request data, check your browser settings!</div>';
		});
		
	},
	
	loadTemplate: function(tpl_path) 
	{
		$('logobar').className = "logobar-news";
		var container = $('content_container');
		var myFx = new Fx.Tween(container,{ property:'opacity',link: 'cancel'});
		myFx.start(0).chain(function() {
		   	var req = new Request({
				url: 'ajax_receiver.php',
				data: { 'action' : 'loadContentByTPL', 'tpl' : tpl_path },
				//update: container,
				onComplete: function(responseText, responseXML)
				{
					container.empty().set('html',responseText);
					container.fade('in');
				}
			}).post();
	
			if (! req) 
			{
		        container.innerHTML = '<div class="tab-error">Unable to request data, check your browser settings!</div>';
		    }
		});
	},
	
	workHover: function(sender, out) {
		var myFx = new Fx.Tween(sender,{property:'background-color',duration: 500, onComplete: function() { (sender.className.contains('selected')) ? sender.removeProperty("style") : "" }});
		if (sender.className.contains('selected')) return;
		
		if (out) 
		{
			myFx.start('#FFFFFF');
		}
		else
		{
			myFx.set('#bdc0c2');
			sender.addEvent('mouseleave',function() { site_script.workHover(this,true); });
		}
	},
	
	eatHash: function() {
		if (window.location.hash != this.current_hash && window.location.hash)
		{
			this.current_hash = window.location.hash;
			eval("this." + this.current_hash.replace('#',''));
		}
		return;
	},
	
	gI: function(type,id,re_calc) {
		this.loadContentByID(type,id,!re_calc);
	},
	
	loadHome: function() {
		this.fit(0);
		this.accordion.display(-1);
	},
	
	doEffect: function(sender,type,end_value) 
	{
		switch (type)
		{
			case 'l1effect':
				if (sender.className.contains('selected') && ! end_value) return;				
				sender.set('tween',{ unit: 'px', link: 'cancel', duration: 'short' });
				if (! end_value)
				{
					sender.tween('padding-left',7);
					sender.addEvent('mouseleave',function() { site_script.doEffect(this,'l1effect',12); })
				}
				else
				{
					sender.tween('padding-left',3);
				}
			break;
		}
	},
	
	loadDefaultProject: function(client_id,campaign_id) {
		var ret_val;
		if(! campaign_id)
		{
			this.options.work_object.each(function(item){
				if ($type(item.cats) === 'array') return;
				if (item.id == client_id)
				{
					if (! ret_val)
					{
						ret_val = item.def_proj_id;
					}
				}
			});
			
		}
		else
		{
			this.options.default_campaign_projects.each(function(item){
				if (item.id == campaign_id)
				{
					if (! ret_val)
					{
						ret_val = item.default_proj_id;
					}
				}
			})

		}
		return this.loadContentByID('work',ret_val);
		
	},
	
	loadNewsItemPage: function(sender,page_number) 
	{
		sender = $(sender);
		if (sender.hasClass("page_cntrl_selected"))	return;
		
		$$('.page_cntrl').each(function(el){
			el.removeClass("page_cntrl_selected")
		});
		var container = $('news_article');
		var myFx = new Fx.Tween(container,{ property: 'opacity', link: 'cancel' });
		myFx.start(0).chain(function() {
			var req = new Request({
				url: 'ajax_receiver.php',
				data: { 'action' : 'loadNewsItemPage','id'  : news_item_id, 'page_num' : page_number },
				//update: container,
				onComplete: function(responseText, responseXML) {
					container.empty().set('html',responseText);
					container.fade('in');
				}
			}).get();

		    if (! req) {
		        container.innerHTML = '<div class="tab-error">Unable to request data, check your browser settings!</div>';
		    }
		});
		sender.addClass("page_cntrl_selected");
	},
	
	loadAboutItemPage: function(sender,about_item_id,page_number) 
	{
		sender = $(sender);
		if (sender.hasClass("page_cntrl_selected"))	return;
		
		$$('.page_cntrl').each(function(el){
			el.removeClass("page_cntrl_selected")
		});
		var container = $('news_article');
		var myFx = new Fx.Tween(container,{ property: 'opacity', link: 'cancel' });
		myFx.start(0).chain(function() {
			var req = new Request({
				url: 'ajax_receiver.php',
				data: { 'action' : 'loadAboutItemPage','id': about_item_id, 'page_num' : page_number },
				//update: container,
				onComplete: function(responseText, responseXML) {
					container.empty().set('html',responseText);
					container.fade('in');
					attachSqueezeBox();
				}
			}).get();

		    if (! req) {
		        container.innerHTML = '<div class="tab-error">Unable to request data, check your browser settings!</div>';
		    }
		});
		sender.addClass("page_cntrl_selected");
	},
	
	newsPage: function (direction)
	{
		if($('news_list_page-'+((this.options.news_page)+direction)))
		{
			var outdiv = $('news_list_page-'+this.options.news_page);
			var indiv = $('news_list_page-'+((this.options.news_page)+direction));
			this.options.news_page += direction;
			var myFx = new Fx.Tween(outdiv,{property: 'opacity'});
			myFx.start(0).chain(function() {
				outdiv.setStyle('display','none');
				indiv.setStyle('display','');
				indiv.fade('in');
			});
			if(! $('news_list_page-'+(this.options.news_page+1)))
			{
				$('news_next').setProperty('src','images/work_next_disabled.png');
			}
			else
			{
				$('news_next').setProperty('src','images/work_next.png');
			}
			if(! $('news_list_page-'+(this.options.news_page-1)))
			{
				$('news_prev').setProperty('src','images/work_prev_disabled.png');				
			}
			else
			{
				$('news_prev').setProperty('src','images/work_prev.png');
			}
		}

	},
	
	bindExternalLinks: function() {

		// otherwise, look for <a> tags, and list them in array var: "anchors"
		var anchors = $$('a[rel="external"]');
		
		anchors.each(function(this_el) {
			if (this_el.getProperty("href")) this_el.setProperty("target","_blank");
		});
	},
	
	dismissTakeover: function()
	{
		$("takeover").empty();
		$("wrapper").setStyle("display","block");
	}
	
	
});

SqueezeBox.parsers.flv = function(preset) {
	return (preset || this.url.test(/\.flv/)) ? this.url : false;
};
 
SqueezeBox.handlers.flv = function(url) {
	var size = this.options.size;
	return new Swiff('mediaplayer.swf', {
		id: 'sbox-swf',
		width: size.x,
		height: size.y,
		params: { wmode: 'transparent',	bgcolor: '#ffffff' },
		vars: {	width: size.x, height: size.y ,file: url,usefullscreen:'false', backcolor: '0xDAE4ED',lightcolor:'0x717172',autostart:true }
	});
};

function flashDone()
{
	site_script.dismissTakeover();
}

function attachSqueezeBox()
{
	var sq_res = $$('a.remooz');
	if(sq_res.length)
	{
		SqueezeBox.assign(sq_res, { overlayOpacity: 0.8, parse : 'rel' });
	}
}