var Site = {
	
	searchfield:Object,			// searchfield
	search_results:Object,		// searchresults
	search_init:Number,
	search_cache:Array,
	
	news_area:Object,
	news_areaheight:Number,
	news_int:Number,
	news_ypos:Number,
	
	largezoom:Object,

	init : function()
	{
		
	 	$(document).pngFix();
	
		$('#latvvideoclose').bind('click', Site.close_latv_overlay);
		
		if (!$.cookie('OSKD_country') && !$.cookie('OSKD_declined'))
		{
			// $('#close_militarybar').bind('click', Site.military_popup.close_bar);
			
			$('#military_popup_decline').live('click', Site.military_popup.decline);
			Site.military_popup.show();
		}
		else
		{
			// $('#militarybar').hide();
		}
		
		if ($('#videoplayer').size() || $('#latvvideobutton').size()) 
		{
			VideoJS.setupAllWhenReady({linksHiding: true});
			$('a.videolink').not('.vimeo').bind('click', Site.videos.launch);
		}
		
		if ($('a.youtube').size())  $('a.youtube').bind('click', Site.videos.youtube);
		if ($('a.vimeo').size())  $('a.vimeo').bind('click', Site.videos.vimeo);
		
		// site search
		Site.search_cache = [];
		Site.searchfield = $('#searchfield');
		Site.searchfield.bind('click',Site.search.onclick)
				.bind('focus',Site.search.onfocus)
				.bind('keydown', Site.search.onkeydown)
				.bind('keyup', Site.search.onkeyup);
		Site.search_results = $('#searchresults');
		
						
		// news feed
		Site.news_area = $('#newsarea');
		Site.news_areaheight = $('div.newsitem').size()*Site.news_area.height();
		Site.news_ypos = 0;
		Site.news_int = setInterval(Site.newsfeed.slide,5000);
		
		$('#options select').bind('change', Site.newsitems.update);
		$('#newskeyword').bind('focus', Site.newsitems.clearit)
						.bind('blur', Site.newsitems.update)
						.bind('keyup', Site.newsitems.search);
		if ($('#news').size() && document.location.hash) Site.newsitems.init();
		
		$('a.readmore').live('click', Site.newsitems.readmore);
		$('a.openclose').live('click', Site.toggle_openclose);
		
		$('#newssignup').bind('click', Site.newsitems.signup);
		
		// photoarea
		if ($('#photoarea').size()) 
		{
			Site.photoarea.init();
						
			$('a.placemark').bind('click', Site.photoarea.mark_click);
			Site.photoarea.timer = setInterval(Site.photoarea.update_photo,10000);
		}
		if ($('#rotatingbanner').size()) 
		{
			Site.photoarea.banner_timer = setInterval(Site.photoarea.update_banner,10000);
		}
		
		
		// forms
		Site.forms.init();
		$('select.trigger').bind('change', Site.forms.trigger);
		
		
		// gallery
		Site.largezoom = $('#largezoom');
		$('img.thumbzoom').bind('click', Site.thumbzoom.load_photo);
		
		
		// dropdown menus
		$('a.dropdownmenu').bind('click', Site.dropdowns.choose);
		$('a.basicdropdown').bind('click', Site.dropdowns.toggle_it);
		$('a.dropdownmainmenu').bind('mouseover', {a:true}, Site.menu_hover);
		$('.mainsubmenu').bind('mouseover', {a:false}, Site.menu_hover);
		$('a.dropdownmainmenu, .mainsubmenu').bind('mouseout', Site.menu_hover_off);
		
		$('a.submenu').bind('click', Site.dropdowns.submenu);
		
		
		// vehicle tiles
		Site.vehicletiles.sort_array = ($.cookie('OSKD_vehicletilefilter')) ? $.cookie('OSKD_vehicletilefilter').split('|') : [];
		Site.vehicletiles.init();
		$('div.vehicletile').bind('mouseover', Site.vehicletiles.show)
							.bind('mouseout', Site.vehicletiles.out);
		$('#sortingbar a.button.enabled').bind('click', Site.vehicletiles.sort);
		$('#sortingbar a.toggle.enabled').bind('click', Site.newsitems.filter);
		$('#removebranchfilter').bind('click', Site.vehicletiles.remove_branch_filter);
		
		
		// maps
		
		// if ($('#map').size()) 
		// 		{
		// 			Site.googlemaps.init();
		// 			$('a.googlemaplink').bind('click', Site.googlemaps.zoom);
		// 		}
		if(document.location.hash && document.location.hash.match(/(vid|lit|overview)/g))
		//if(document.location.href.match(/\/products\//g) && document.location.hash)
		{
			Site.switcheroo_it();
		}
		
		if (document.location.hash=='#autoplay' && $('a.vimeo').size()) $('a.vimeo:first').trigger('click');
		if (document.location.hash=='#youtube' && $('a.youtube').size()) $('a.youtube:first').trigger('click');
		if (document.location.hash=='#vimeo' && $('a.vimeo').size()) $('a.vimeo:first').trigger('click');

		// trademark superscript 4x4 6x6 8x8 small		
		// var html2 = $("body").html().replace(/6x6/gi, "6<span class='lowercase'>x</span>6");
		// $("body").html(html2);
		// var html4 = $("body").html().replace(/4x4/gi, "4<span class='lowercase'>x</span>4");
		// $("body").html(html4);
		// var html5 = $("body").html().replace(/8X8/gi, "8<span class='lowercase'>x</span>8");
		// $("body").html(html5);
		
		// email cloaking
		$('a[href^="mailto"]').bind('mouseover', Site.uncloak);
		
		
	},
	
	close_latv_overlay: function()
	{
		$('#latvvideooverlay').animate({bottom:'-60px'},500,'easeOutQuint',function(){ $(this).remove(); });
		return false;
	},
	
	
	toggle_openclose: function()
	{
		var a = $(this);
		
		var label = a.siblings('.instructions').html();
		a.siblings('.instructions').html((label=='Click to collapse')?'Click to expand':'Click to collapse');
		
		
		var id = a.attr('rel');
		window.log(id);
		if ($('#'+id).size()) 
		{
			$('#'+id).slideToggle();
			a.toggleClass('open').toggleClass('close');
		}
		return false;
	},
	
	uncloak: function()
	{
		var a = $(this);
		var href = a.attr('href').replace(/\[at\]/g, "@").replace(/\[dot\]/g, ".");
		a.attr('href',href);
	},
	
	switcheroo_it : function()
	{
		var hash = document.location.hash.replace('#','');
		if($('#'+hash).size())
		{
			$('div.copy:visible').hide();
			$('a.active').removeClass('active');
			
			$('a[rel="'+hash+'"]').addClass('active');
			$('#'+hash).show();
		
			$.scrollTo(0);
			
			if (hash=='vid') 
			{
				$('a.videolink:first').trigger('click');
			}
			
		}
	},
	
	switcheroo : function(a) 
	{ 
		var hash = $(a).attr('rel');
		window.location.hash = hash;
		
		
		$('div.copy:visible').hide();
		//alert($(a).attr('rel'));
		$('#'+$(a).attr('rel')).show();
		$('a.active').removeClass('active');
		$(a).addClass('active');
		return false;
	},
	
	mainmenuint:Number,
		
	menu_hover : function(e) 
	{
		//window.log('menu_hover');
		$('.menu').hide();
		
		if(Site.mainmenuint>0) clearTimeout(Site.mainmenuint);
		if(e.data && e.data.a) 
		{
			$('a.hover').removeClass('hover');
			$(this).addClass('hover');
			Site.show_menu($(this));
		}
		
		//$('a.active').removeClass('active');
		//$(a).addClass('active');
		// return false;
		
	},
	
	menu_hover_off : function()
	{
		//window.log('menu_hover_off');
		Site.mainmenuint = setTimeout(Site.hide_menu,250);
	},
	
	show_menu: function(a){
		$('.mainsubmenu').hide();
		var rel = a.attr('rel');
		$('#'+rel).show();

		//window.log(rel);
	},
		
	hide_menu: function(){
		$('a.hover').removeClass('hover');
		$('.mainsubmenu').hide();
	},
	
	expander : function(id)
	{
		$("#"+id).slideToggle();
		return false;
	},
	
	validate_form : function(form)
	{
		if(!form) form = document.forms[0];
		var submit_it = true;
		var email_pattern = new RegExp(/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i);

		$(form).find(".REQUIRED").each(function(req)
		{
			if(($(this).attr('type')!='checkbox' && this.value == '') || 
				($(this).attr('type')=='checkbox' && !this.checked) || 
				($(this).hasClass('email') && !email_pattern.test($(this).val()))) 
			{
				$(this).parents("div.form").addClass('error');
				submit_it = false;
			}
			else
			{
				$(this).parents("div.form").removeClass('error');
			}			
		});
		if( !submit_it ) 
		{
			$('#error_message').html('Please review the highlighted, required fields and resubmit.').fadeIn(250);
			$.scrollTo('#error_message', 800, {easing:'easeInOutCubic'});
		}
		return submit_it;
	},
	
	make_popup : function(content,id,opt)
	{
		
		var id = id || 'popup_box';
		var width = (opt && opt.width) ? opt.width : 600;
		window.log(width);
		
		if(!$('#overlay').size())
		{
			// var o = $$('div',
			// 						'',
			// 						{ className:'overlay', id:'overlay' });
			// 					
			// 			o.css({
			// 				height:$(document).height(),
			// 				width:'100%',
			// 				opacity:0.7
			// 			});
			
			var h = $(document).height();
			var w = '100%';
			var o = '<div class="overlay" id="overlay" style="height:'+h+'px; width:'+w+';"></div>';
			
			$('body').append(o);
			$('#overlay').css({opacity:0.7});
		}
		
		
		var box = '<div class="popupbox" id="'+id+'"><div class="inset">'+content+'</div><a href="#" class="close_button" id="'+id+'_close_button"><img src="/images/buttons/close.jpg" alt="close" /></a></div>';
		
		// var box = $$('div',
		// 					$$('div',content,{ className:'inset' }),
		// 					$$('a',
		// 						$$('img','',{ src:'/images/buttons/close.jpg', alt:'close' }),
		// 						{ className:'close_button', id:id+'_close_button' }),
		// 					{ className:'popupbox', id:id });
				
		
		// var top = 100+$(document).scrollTop()+($('.box').size()*10);
		$('body').append(box);
		
		var top = 50+($('.box').size()*10);
		$('#'+id).css({
			'width':width,
			'top':top,
			'left':($(window).width()*.5)-(width/2)
		});
		
		
		$('#'+id+'_close_button').bind('click', function()
		{ 
			$('#'+id).remove();
			if(!$('.box').size()) $('#overlay').remove();
			return false;
		});
		
		$.scrollTo('0px', 400, {easing:'easeInOutCubic'});
		
		return box;
		
	},
	
	kill_all : function()
	{
		$('#overlay, div.popupbox').fadeOut(200);
	}
	
};

// Site.videos = {};

Site.videos = {
	
	youtube: function()
	{
		var v = $(this).attr('rel');
		var params = {};
		params.v = v;
		
		$.post('/customajax/launch_youtube', params, function(data, textStatus, xhr) 
		{
			var options = {};
			options.width = 690;
			Site.make_popup(data,'vp',options);			
		});
		
		return false;
	},
	
	vimeo: function()
	{
		var v = $(this).attr('rel');
		var params = {};
		params.v = v;
		
		$.post('/customajax/launch_vimeo', params, function(data, textStatus, xhr) 
		{
			var options = {};
			options.width = 690;
			Site.make_popup(data,'vp',options);			
		});
		
		return false;
	},
	
	launch: function()
	{
		var id = $(this).attr('rel');
		var params = {};
		params.id = id;
		
		$.post('/customajax/launch_video', params, function(data, textStatus, xhr) 
		{
			var options = {};
			options.width = 690;
			Site.make_popup(data,'vp',options);
			VideoJS.setupAllWhenReady({linksHiding: true, playerFallbackOrder: ["html5", "flash", "links"]});
			/*
			$('.vjs-big-play-button').css('visibility','hidden');
			var watched = $('.vjs-spinner');
			var timer = setInterval(function()
			{
				if (watched.css('display')=='none')
				{
					$('.vjs-big-play-button').css('visibility','visible');
					clearInterval( timer );
				}
			},500);
			*/
			
		});
		Site.videos.launch = this;
		return false;
	},
	
	alertit: function()
	{
		alert('please');
	}
};

Site.forms = {
	
	init: function()
	{
		if ($('form').size()) 
		{
			// check datepickers
			$('input.datepicker').datepicker();
			
			// check triggers
			$('select.trigger').each(function(index) {
				var val = $(this).val();
				$('#'+val+'_field').show();
			});
		}
	},
	
	trigger: function()
	{
		$('div.optional.trigger').hide();
		
		var val = $(this).val();
		$('#'+val+'_field').show();
	}
	
};

Site.military_popup = {
	
	show: function()
	{
		
		var params = {};
		$.post('/customajax/military_preference', params, function(data, textStatus, xhr) 
		{
			
			var box = Site.make_popup(data,'militarypopup');
			$('a.military_popup_choice').bind('click', {menu:null, onComplete:Site.kill_all}, Site.dropdowns.change);
			
		});
		
	},
	
	close_bar: function()
	{
		$('#militarybar').slideUp();
		return false;
	},
	
	decline: function()
	{
		$.cookie('OSKD_declined',1,{ expires: 30, path: '/'});
		Site.kill_all();
		
		return false;
	}
	
};

Site.vehicletiles = {
	
	
	hide_int:Number,
	sort_array:Array,
	
	active:Array,
	dimmed:Array,
	all:Array,
	
	init: function()
	{
		Site.vehicletiles.all = $('div.vehicletile');
		Site.vehicletiles.reorder();
	},
	
	go: function()
	{
		window.log('going...');
	},
	
	remove_branch_filter: function()
	{
		$.cookie('OSKD_branch',null);
		document.location.reload();
	},

	show: function()
	{
		window.log($(this) );
		if(!$(this).hasClass('dim'))
		{
			clearTimeout(Site.vehicletiles.hide_int);
		
			var id = $(this).attr('id').split('_')[1];
			var div = $('#vehicle_'+id+':hidden');
			if (div.size()) 
			{
				$('div.vehicleinfo:visible').slideUp(100);
				div.slideDown(200).bind('mouseover', function(){ clearTimeout(Site.vehicletiles.hide_int); });
			}
		}
		
	},
	
	hide: function()
	{
		$('div.vehicleinfo:visible').slideUp(100);
	},
	
	out: function()
	{
		Site.vehicletiles.hide_int = setTimeout(Site.vehicletiles.hide,1000);
	},
	
	sort: function()
	{
		var lbl = $(this).attr('rel');
		$(this).toggleClass('selected');

		if(lbl)
			Site.vehicletiles.toggle_sort(lbl);
		else
		{
			Site.vehicletiles.sort_array = [];
			$.cookie('OSKD_vehicletilefilter',null,1,'/');
			$('a.button.selected').removeClass('selected');
		}
		
		// activate all vehicles button
		if(Site.vehicletiles.sort_array.length)
		{
			var friendly = {
				'tak4':'TAK-4&reg;', 
				'propulse':'ProPulse&reg;', 
				'commandzone':'Command Zone&trade;', 
				'terramax':'Terramax&trade;', 
				'manufacturing':'Flexible Integrated Manufacturing', 
				'shoptechsystem':'ShopTech&trade; System', 
				'remm':'REMM&trade;', 
				'lctv':'LCTV', 
				'obvp':'OBVP', 
				'heavyduty':'Heavy Tactical', 
				'mediumduty':'Medium Tactical', 
				'lightduty':'Light Tactical'
			};
			var nice = [];
			for (var i=0; i < Site.vehicletiles.sort_array.length; i++) {
				nice.push(friendly[Site.vehicletiles.sort_array[i]]);
			};
			window.log(nice);
			$('#currentfilter').html(nice.join(', '));
			
			$('a.button.allvehicles').addClass('active');
			$('div.vehicletile').addClass('dim');
			
			for (var i=0; i < Site.vehicletiles.sort_array.length; i++) {
				$('div.vehicletile.'+Site.vehicletiles.sort_array[i]).removeClass('dim');
			};
		}
		else
		{
			$('#currentfilter').html('All Products');
			$('a.button.allvehicles').removeClass('active');
			$('div.vehicletile').removeClass('dim');
		}
		
		Site.vehicletiles.reorder();
		// Site.vehicletiles.dimmed = $('div.vehicletile.dim');
		
		
		return false;
	},
	
	reorder: function()
	{
		Site.vehicletiles.all.prependTo($('#vehicletiles'));
		Site.vehicletiles.active = $('div.vehicletile').not('.dim');
		Site.vehicletiles.active.prependTo($('#vehicletiles'));
		var z = 1000;
		$('div.vehicletile').each(function(index) {
		  $(this).css({'z-index':z--});
		});
	},
	
	toggle_sort: function(lbl)
	{
		var j = -1;
		for (var i=0; i < Site.vehicletiles.sort_array.length; i++) 
		{
			if(Site.vehicletiles.sort_array[i] == lbl)
			{
				j = i;
				break;
			}
		};
		if (j>-1)
			Site.vehicletiles.sort_array.splice(j,1);
		else
			Site.vehicletiles.sort_array.push(lbl);
		$.cookie('OSKD_vehicletilefilter',Site.vehicletiles.sort_array.join('|'),2,'/');
		// window.log(Site.vehicletiles.sort_array);
	}
	
};

Site.newsitems = {
	
	num:Number,
	scope:String,
	order:String,
	branch:String,
	
	init: function()
	{
		window.log('Site.newsitems.init');
		
		var parts = document.location.hash.split('/');
		window.log(parts);
		$('#selectquantity').val(parts[1]);
		$('#selecttime').val(parts[2]);
		$('#selectorder').val(parts[3]);
		$('#selectsource').val((parts[4])?parts[4]:'all'+$('div.reloadableitems').attr('id'));
		if ($.cookie('news_branch')) 
		{
			$('#selectbranch').val($.cookie('news_branch'));
		}
		else
		{
			$('#selectbranch').val((parts[5])?parts[5]:$.cookie('OSKD_branch'));
		}
		$('a.toggle.enabled').removeClass('selected');
		
		Site.newsitems.update();
	},
	
	signup: function()
	{
		var e1 = $('#newsemail1').val();
		var e2 = $('#newsemail2').val();
		if(!e1.match(/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gi))
		{
			$('#newssignuperror').html("Your address is not valid.").show();
		}
		else if (e1!=e2) 
		{
			$('#newssignuperror').html("Your addresses don't match.").show();
		}
		else
		{
			var params = {};
			params.email = e1;
			$.post('/customajax/email_signup', params, function(data, textStatus, xhr) 
			{
				$('#emailform').html(data);
			});
		}
		
		return false;
	},
	
	clearit: function()
	{
		var f = $(this);
		f.select();
	},
	
	readmore: function()
	{
		var id = $(this).attr('rel');
		window.log(id);
		if(id=='')
			return true;
		$('#partialstory'+id).hide();
		$('#fullstory'+id).show();
		
		return false;	
	},
	
	search: function(e)
	{
		var key = e.charCode || e.keyCode || 0;
		if(key==13)
		{
			Site.newsitems.update();
		}
	},
	
	filter: function()
	{
		var source = $(this).attr('rel');
		
		$('#selectsource').val(source);
		
		$('a.toggle.enabled').removeClass('selected');
		$(this).addClass('selected');
			
		Site.newsitems.update();
		
		return false;
	},
	
	update: function()
	{
		window.log('Site.newsitems.update');
		$('#newsloader').show();
		
		var params 		= {};
		params.num 		= $('#selectquantity').val();
		params.scope	= $('#selecttime').val();
		params.order	= $('#selectorder').val();
		params.source	= ($.url.segment(0)=='archives') ? "feed" : $('#selectsource').val();
		params.branch	= $('#selectbranch').val();
		params.type		= $('div.reloadableitems').attr('id');
		params.keyword	= $('#newskeyword').val();
		params.year		= ($.url.segment(1)) ? $.url.segment(1) : null;
		
		window.log($.url.segment(1));
		
		$.cookie('news_branch',params.branch,{ expires: 7, path: '/'});
		
		$("a.toggle.enabled[rel='"+params.source+"']").addClass('selected');
		
		var hashstring = '#/'+params.num+'/'+params.scope+'/'+params.order+'/'+params.source+'/'+params.branch;
		
		$.post('/customajax/update_newsitems', params, function(data, textStatus, xhr) 
		{
			// alert(params.type);
			document.location.hash = hashstring;
			// $('div.reloadableitems').replaceWith(data);
			$('#ajaxwrap').html(data);
			
		});
	}
	
};

Site.photoarea = {
	
	current_thumb:Number = 0,
	thumb_array:Array,
	timer:Number,
	banner_timer:Number,
	y_pos:Number = 0,
	
	init: function(attribute)
	{
		Site.photoarea.thumb_array = [];
		$('#bigone img').each(function(index) 
		{
			Site.photoarea.thumb_array.push($(this).attr('id'));
		});
		// $('#thumbscolumn').css({'height':(Site.photoarea.thumb_array.length<3)?Site.photoarea.thumb_array.length*100:300+'px'});
		// if (Site.photoarea.thumb_array.length<=3) 
		{
			$('img.arrow').hide();
		}
	},
	
	update_banner: function()
	{
		$('#rotatingbanner a:first').hide().appendTo($('#rotatingbanner')).end().fadeIn(500);
	},
	
	arrow_click: function(e)
	{
		clearInterval(Site.photoarea.timer);
		Site.photoarea.slide_strip(e.data.direction);
		
		return false;
	},
	
	mark_click: function()
	{
		clearInterval(Site.photoarea.timer);
		$('a.placemark.active').removeClass('active');
		$(this).addClass('active');
		
		var id = $(this).attr('rel');
		Site.photoarea.change_big(id);
		
		return false;
	},
	
	thumb_click: function()
	{
		clearInterval(Site.photoarea.timer);
		var num = parseInt($(this).attr('rel'),10);
		Site.photoarea.current_thumb = num;
		var id = Site.photoarea.thumb_array[num];
		
		Site.photoarea.change_big(id);
		return false;
	},
	
	change_big: function(id)
	{
		// window.log(id);
		$photo = $('#'+id);
		if ($('#latvvideooverlay').size()) 
		{
			$photo.insertBefore($('#latvvideooverlay'));
		}
		else
		{
			$('#bigone').append($photo);
		}
		$photo.hide().removeClass('hide').fadeIn(1000,function()
		{
			$photo.siblings('img').each(function(index) {
				$(this).addClass('hide');
			});
		});
	},
	
	update_photo: function()
	{
		var num = ++Site.photoarea.current_thumb%Site.photoarea.thumb_array.length;
		var id = Site.photoarea.thumb_array[num];
		
		$('a.placemark.active').removeClass('active');
		$('#mark'+num).addClass('active');
		
		Site.photoarea.change_big(id);
	},
	
	next_y: function(direction)
	{
		if(Site.photoarea.thumb_array.length<=3) return 0;
		
		var strip 	= $('#strip');
		var thumb 	= $('#photoarea.home').size() ? 110 : 100;
		var height 	= thumb * $('a.thumb').size();
		var frame 	= thumb * 3;
		
		var top 	= 0;
		var bottom 	= -(Site.photoarea.thumb_array.length*thumb);
		
		if(Site.photoarea.y_pos == bottom && direction == 'next')
		{
			strip.css('top',top);
			Site.photoarea.y_pos = top;
		}
		else if(Site.photoarea.y_pos == top && direction=='previous')
		{
			strip.css('top',bottom);
			Site.photoarea.y_pos = bottom;
		}
		
		Site.photoarea.y_pos = (direction=='previous') ? Site.photoarea.y_pos+thumb : Site.photoarea.y_pos-thumb;
		
		return Site.photoarea.y_pos;
	}
	
};

Site.thumbzoom = {
	load_photo: function()
	{
		var prevht = Site.largezoom.height();
		var thumb = $(this);
		Site.largezoom.css({'height':prevht+'px'});
		var oldimg = Site.largezoom.children('img');
		// window.log(oldimg);
		
		if(oldimg.size())
		{
			// window.log('oldimg found');
			oldimg.fadeOut(100,switchphoto);
		}
		else
		{
			// window.log('oldimg not found');
			switchphoto();
		}
		
		function switchphoto()
		{
			// window.log('switchphoto');
			var filecode = thumb.attr('src').match(/([a-zA-Z0-9]{25})/g)[0];
		
			var imgPreloader = new Image();
			imgPreloader.onload = function()
			{
				var img = $$('img','',{src:'/foleyadmin/image/'+filecode});
				img.hide();
				Site.largezoom.html(img).css({'height':'auto'});
				img.fadeIn(1000);
			};
			imgPreloader.src = "/foleyadmin/image/"+filecode;
		}
	}
};

Site.search = {
	
	onclick: function(e)
	{
		$('a.keyable.selected').removeClass('selected');
		Site.search.onkeyup(e);
		
		
	},
	
	onfocus: function(e)
	{
		if(Site.searchfield.val()=='Enhanced Search') 
		{
			Site.searchfield.val('');
		}
		else
		{
			Site.search.onkeyup(e);
		}
	},
	
	onkeydown: function(e)
	{
		var key = e.charCode || e.keyCode || 0;

		// window.console.log('The key is: '+key);
		if(key==38 || key==40 || key==13)
		{
			return false;
		}
	},
	
	onkeyup: function(e)
	{
		var val = Site.searchfield.val().replace(/[^-_0-9a-z\. ]/gi, "");
		Site.searchfield.val(val);
		// window.console.log(val);
		
		var key = e.charCode || e.keyCode || 0;
		if(key!=38 && key!=40 && key!=13)
		{
			if(Site.search_init) clearTimeout(Site.search_init);
			Site.search_init = setTimeout(Site.search.get_results,100);
			$('#search_form').attr('action','/search/'+Site.searchfield.val());
		}
		else
		{
			if(Site.search_results.is(':visible'))
			{
				if(key==13)
				{
					var a = $('a.keyable.selected');
					if(a.size())
					{
						document.location.href = a.attr('href');
					}
					else
					{
						// if(window.console) window.console.log('going to the search page');
						document.location.href = '/search/'+val;
					}
					Site.search.hide_results();
					
					return false;
				}
				else if ($('a.keyable.selected').size()) 
				{
					if(key==40)
					{
						var keys = $('a.keyable');
						var num = 0;
						for(i=0;i<keys.length;i++)
						{
							if($(keys[i]).hasClass('selected'))
							{
								var a = keys[i];
								var num = i;
								break;
							}
						}
						var b = (num==keys.length-1) ? keys[0] : keys[num+1];
						$(a).removeClass('selected');
						$(b).addClass('selected');
						
						return false;
					}
					else if(key==38)
					{
						var keys = $('a.keyable');
						var num = 0;
						for(i=0;i<keys.length;i++)
						{
							if($(keys[i]).hasClass('selected'))
							{
								var a = keys[i];
								var num = i;
								break;
							}
						}
						var b = (!num) ? keys[keys.length-1] : keys[num-1];
						$(a).removeClass('selected');
						$(b).addClass('selected');
						
						return false;
					} 
				}
				else
				{
					// window.console.log('getting the first one');
					$('a.keyable:first').addClass('selected');
				}
			}
			
			return false;
		}
	},
	
	get_results: function()
	{
		if(Site.searchfield.val().length>2 && Site.searchfield.val()!='Enhanced Search')
		{
			var params = {};
			var val = Site.searchfield.val();
			params.keyword = val;
			if(Site.search_cache[val])
			{
				Site.search_results.html(Site.search_cache[val]).show();
			}
			else
			{
				$.post('/customajax/search_results', params, function(data, textStatus, xhr) 
				{
					Site.search_results.html(data).show();
					Site.search_cache[val] = data;
				});
			}
			$(document).bind('click',Site.search.hide_results);		
		}
		else
		{
			Site.search.hide_results();
		}
	},
	
	onblur: function()
	{
		Site.search_init = setTimeout(Site.search.hide_results,1000);
	},
	
	hide_results: function()
	{
		$(document).unbind('click',Site.search.hide_results);
		Site.search_results.hide();
	}
	
};

Site.newsfeed = {
	
	slide: function()
	{
		Site.news_ypos -= 40; 
		Site.news_area.animate({top:Site.news_ypos},1000,'easeInOutCubic',Site.newsfeed.reset);
	},
	
	reset: function()
	{
		if(-Site.news_areaheight+40==Site.news_ypos)
		{
			Site.news_ypos = 0;
			Site.news_area.css({top:Site.news_ypos});
		}
	}
	
};

Site.dropdowns = {
	
	submenu: function(){
		
		//window.log('Site.dropdowns.submenu');
		var id = $(this).attr('rel');
		
		$('a.has_sub.open').not($(this)).removeClass('open');
		$(this).toggleClass('open');
		
		$('div.submenudrop').not('#'+id).slideUp();
		$('#'+id).slideToggle().toggleClass('open');
		
		return false;
	},
	
	toggle_it: function(attribute)
	{
		var id = $(this).attr('rel');
		var menu = $('#'+id);
		menu.toggle();
		
		return false;
	},

	choose: function()
	// {
	// 			$('div.menu').hide();
	// 			var id = $(this).attr('rel');
	// 			var menu = $('#'+id);
	// 			var links = $('#'+id+' > a');
	// 			menu.show();
	// 			links.bind('click', Site.dropdowns.change);
	// 			$(document).one('click', function()
	// 			{
	// 				menu.hide();
	// 			});
	// 		},
	{
		$('div.menu').hide();
		var id = $(this).attr('rel');
		//window.log(id);
		var menu = $('#'+id);
		var links = menu.find('a');
		//window.log('There are '+links.size()+' aTags');
		menu.toggle();

		links.bind('click', {menu:menu}, Site.dropdowns.change);
		
		$(document).one('click', function()
		{
			menu.hide();
		});
		
		
		
		return false;
	},
	
	change: function(e)
	{
		if($(this).hasClass('external'))
		{
			return true;
		}
		else
		{
			var menu = e.data.menu;
			var parts = $(this).attr('rel').split('|');
			var country = parts[0];
			var language = parts[1];
			var branch = parts[2];
			var title = $(this).html();
			// var old = $.cookie('OSKD_);
		
			$.cookie('OSKD_country',country,{ expires: 7, path:'/' });
			$.cookie('OSKD_language',language,{ expires: 7, path:'/' });
			$.cookie('OSKD_branch',(branch)?branch:null,{ expires: 7, path:'/' });
		
			$('#selectedbranch').html(''+title).removeClass().addClass('flag_'+country);
			if(menu)
				menu.hide();
			
			if(e.data.onComplete)
				e.data.onComplete();
			
			document.location.reload();
		
			return ($(this).hasClass('external'));
		}
	}
};
		
window.log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments));}};

$(document).ready(function() {
	Site.init();
});

