$(document).ready(function() {
	w = $(document).width();
	h = $(document).height();
	ww = $(window).height();
	wh = $(window).height();
	
	$('#navigation li').each(function() {
		
		var p = $(this).parent();
		var men = p.parent();
		var pid = men.hasClass("menu");
		if ($("ul",this).length > 0 && pid) {
			
			var liw = 220;
			var opts = $(this).children("ul").children("li");
			var uls = opts.children("ul");
			var len = uls.length == 0 ? opts.length : uls.length;
			var wrapper_w = liw * (len);
			var wrapper_pos = (wrapper_w/2);
			var tw = $(this).width();
			$('a:first',this).next().wrap(
				'<div class="subnav_wrapper" style="width:'+wrapper_w+'px;left:-'+wrapper_pos+'px;"></div>'
			);
		}
		
		$(this).hover(function() {
			$(this).addClass('active');
			if ($("ul",this).length > 0) {
				$(".subnav_wrapper",this).show();
			};
		},
		function() {
			$(this).removeClass('active');
			$(".subnav_wrapper",this).hide();
		});
	});
	
	var hr = $('.wp-caption a:first').attr('href');
	$('.wp-caption a:first').attr({rel:hr,href:"#"});
	$('.wp-caption p').click(function() {
		showLightBox(this);
	});
	$('.wp-caption a:first').click(function() {
		showLightBox(this);
	});
	
	$('.ad_details').each(function() {
	  $('a:first',this).click(function() {
	    showLightBox(this);
	  });
	})
	
});

function showLightBox(elem) {
	// get window & document sizes
	var par = $(elem).parent();
	var a = $('a:first',par);
	var aw = $(a).width();
	var ah = $(a).height();
	var im = $("img:first",a);
	var imw = $(im).width();
	var imh = $(im).height();
	var as = $(a).attr('rel');
	var lm = Math.floor((w/2)-(imw/2));
	//var tm = Math.floor((h/2)-(imh/2));
	var tm = 30;

	//console.log(im);
	var nim = new Image();

	$(nim).load(function(){
		imw = nim.width;
		imh = nim.height;
		lm = Math.floor((w/2)-(imw/2));
		//tm = Math.floor((wh/2)-(imh/2));
		tm = 30;
		
		//console.log("img width: %s, image height: ",imw,imh);
		//console.log("window width: %s, doc height: ",w,wh);
		//console.log("Width diff: %s, height diff: %s", (w/imw),(wh/imh));
		//style='height:"+Math.floor((wh/imh)*100)+"%;'
		//console.log(Math.floor((wh/imh)*100));
		
		$('#lightbox').append("<img id='lightbox_image' src="+as+" alt="+$(im).attr('alt')+" title="+$(im).attr('title')+" />");
		$('#lightbox_wrapper').show();
		// call resize to adjust background color height
		resizeLightBox(h,imw,imh,lm,tm);
		// call resize to adjust background height on a window resize
		
		// use esc key to close lightbox
		$(document).keyup(function(event){
		    if (event.keyCode == 27) {
		        closeLightBox();
		    }
		});

	});
	nim.src = as;
	
	$(window).resize(function() {
		resizeLightBox();
	});
	
}

function resizeLightBox(h,imw,imh,lm,tm) {
	$('#lightbox_background').css({height:imh,opacity:'.3',paddingBottom:'60px'});
	$('#lightbox').css({width:imw,height:imh,left:lm,top:tm});
}

function closeLightBox() {
	$('#lightbox_wrapper').hide();
	$('#lightbox_image').remove();
}


