var i = 0;
var imageLoader = new Image();
var im = new Array();
im[i] = 'images/nav/subMenuBG.png'; i++;
im[i] = 'images/nav/pageTabActive.png'; i++;
im[i] = 'images/nav/scroll_hover.png'; i++;
im[i] = 'images/nav/cancel.png'; i++;
im[i] = 'images/nav/subMenuBottom.png'; i++;

for(var n=0; n < i; n++) 
{
	imageLoader.src =im[n];
}

var animSpeed = 150;
var loadTimer;
var fullSwitched = false;
var bgWidth = 0;
var bgHeight = 0;
var bgAspect = 0;

$(document).ready(function(){
	
//	if ( navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) )
	if (navigator.userAgent.indexOf('Chrome') > -1 || navigator.userAgent.indexOf('Firefox') > -1 || navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Safari') > -1 || navigator.userAgent.indexOf('Opera') > -1|| navigator.userAgent.indexOf('Gecko') > -1)
	{		
		//background image prep
		bgWidth = $('#bgimg').attr('width');
		bgHeight = $('#bgimg').attr('height');
		bgAspect = bgWidth / bgHeight;	
		wDim = getWindowSize();
		setBgDim(wDim.width,wDim.height);
		$('#bgimg').animate({opacity:1},500)
//		setTimeout("$('#bgimg').animate({opacity:1},700)",50);
		$(window).resize(function(){
			wDim = getWindowSize();
			setBgDim(wDim.width,wDim.height);
		});
	}
	if (location.hash != "" && /[0-9+]/.test(location.hash.substr(1)))
	{
		fullView(location.hash.substr(1));
	}
	setTimeout('window.focus()',250);
	$(document).keyup(function(e) {
		var KEYCODE_ESCAPE = 27;
		if (e.keyCode == KEYCODE_ESCAPE)
			fullClose()
	});
	$('.thumb,.medium').click(viewContent);
	$('#featuredThumbs > .thumb').mouseover(function(){
		pos = $(this).attr('pos');
		$('#active').css('left',((pos - 1) * 147 - 3) + 'px');
		$('#featured > div').hide();
		$('#featured > div[pos=' + pos + ']').show();
		if ($(this).parent().parent().hasClass('rightSection'))
		{
			$('.thumb.active').removeClass('active');
			$(this).addClass('active');
		}
	});
	$('.contentTable tbody tr').click(function(e){
		//if we didn't click on the checbox itself, then check the row's checkbox
		if (e.target.name != "content[]" && e.target.tagName != "A" && e.target.tagName != "DIV")
		{
			id = $(this).attr('cid');
			fullView(id)
/*			rowCheckbox = $('#check' + id);
			if (rowCheckbox.attr('checked'))
			{
				rowCheckbox.attr('checked',false);
			}
			else
			{
				rowCheckbox.attr('checked',true);
			}*/
		}
	});
	$('.contentTable tbody tr').mouseover(function(){
		$('.contentTable tr.active').removeClass('active');
		$(this).addClass('active');
		id = $(this).attr('cid');
		$('.contentInfo > div').hide();
		$('#ci' + id).show();		
	});
	$('.gallery .thumb').hover(function(){$(this).children('.ti').animate({height:'50px'},animSpeed);},function(){$(this).children('.ti').animate({height:'20px'},animSpeed);});
	$("#commentScroll").click(function() {
		commentOffset = $('#commentStart').offset().top;
		$('html,body').animate({scrollTop: commentOffset}, 500);
	});
	$('#captchaSubmit').click(function() {
		$('#captchaForm').show(); 
	});
	$('#captchaCancel').click(function() { $('#captchaForm').hide(); });
	$('#mapToggle').click(function() {
		if ($(this).text() == 'Show Interactive Map') {		
			$('#streetMap').stop(false,true).slideUp(animSpeed);
			$('#mapToggle').text('Show Basic Map');
		} else {
			$('#streetMap').stop(false,true).slideDown(animSpeed);
			$('#mapToggle').text('Show Interactive Map');
		}
	});
	$('#toTop').click(function() {$('html,body').animate({scrollTop: 0}, 500);});
	$('#previous').click(function()
	{
		pos = parseInt($.cookie('pos'));
		if (!pos || pos < 0)
			pos = 0;
		if (pos > maxPos)
			pos = maxPos;
		pos -= 1;
		if (pos < minPos)
		{
			previousLink = $('#previousLink').attr('href');
			if (previousLink)
			{
				$.cookie('galleryNav','previous',{expires:365});
				window.location = previousLink;	
				return true;
			}			
			else
				pos = maxPos;
		}
		contentID = $('.thumbnailHolder[pos=' + pos + ']').attr('contentID');
		if (contentID)
		{
			$.cookie('pos',pos,{expires:365});
			view(contentID,false);
			loadLeft = true;
		}		
	});
	$('#next').click(function()
	{
		pos = parseInt($.cookie('pos'));
		if (!pos || pos < 0)
			pos = 0;
		if (pos > maxPos)
			pos = maxPos;
		pos += 1;
		if (pos > maxPos)
		{
			nextLink = $('#nextLink').attr('href');
			if (nextLink)
			{
				$.cookie('galleryNav','next',{expires:365});
				window.location = nextLink;
				return true;
			}
			else
				pos = minPos;
		}
		contentID = $('.thumbnailHolder[pos=' + pos + ']').attr('contentID');
		if (contentID)
		{
			$.cookie('pos',pos,{expires:365});
			view(contentID,false);
		}
	});
	$('#comment').click(function(){
		contentID = $.cookie('contentID');
		if (contentID)
			window.location = '/comments&contentID=' + contentID;
 	});
	$('.nh > div[id]').hover(menuOver,menuOut);
	$('#upload').change(uploadInput);
	$('.tags > div').click(tag);

//needs work
	$('#editLarge').click(function(){
		contentID = $(this).parent('contentID');
		if (contentID)
			window.location = '/members/content&contentID=' + contentID;
 	});
});

//////////////////Functions
function setBgDim(width,height)
{
	bgWidth = $('#bgimg').attr('width');
	bgHeight = $('#bgimg').attr('height');
	bgAspect = bgWidth / bgHeight;	
	
	windowAspect = width / height;	
	if (bgAspect < windowAspect)
	{
		newHeight = (width / bgAspect);
		heightOffset = (height - newHeight) / 2;
		$('#bgimg').css({'width':(width + 'px'),'height':(newHeight + 'px'),'top': (heightOffset + 'px'),'left':'0px'});
	}
	else if (bgAspect > windowAspect)
	{
		newWidth = (height * bgAspect);
		widthOffset = (width - newWidth) / 2;
		$('#bgimg').css({'width':(newWidth + 'px'),'height':(height + 'px'),'top':'0px','left':(widthOffset + 'px')});
	}
	else
	{
		$('#bgimg').css({'width':width,'height':height,'top':'0px','left':'0px'});
	}
}
function getWindowSize()
{
	if (window.innerWidth && window.innerHeight)
	{ 
		width = window.innerWidth; 
		height = window.innerHeight; 
	} 
	//IE Mozilla 
	if (document.body.clientWidth && document.body.clientHeight)
	{ 
		width = document.body.clientWidth; 
		height = document.body.clientHeight; 
	}
	return {width: width,height: height};
}
function download(contentID)
{
	window.location = '/download/' + contentID;
}
function getCheckedValue(radioObj)
{
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++)
	{
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
function getSelectedValue(selectObj)
{
	return selectObj[selectObj.selectedIndex].value;
}
function limitText(field, limitNum)
{
	if (field.value.length > limitNum)
		field.value = field.value.substring(0, limitNum);
}
//this code is duplicated in the contentManager and should be simply included
function tag()
{
	tagID = $(this).attr('id').substring(3);
	tagsInputValue = $('#contentTagString').attr('value');
	tagLoc = tagsInputValue.search(',' + tagID + ',');
	//if we found the tag in the input box, then substring it out
	if (tagLoc > -1)
	{
		tagLength = tagID.length + 1;
		tagsInputValue = tagsInputValue.substring(0,tagLoc) + tagsInputValue.substring(tagLoc + tagLength);
		$('#tag' + tagID).removeClass('wordListActive');
	}
	//otherwise add it in
	else
	{
		tagsInputValue = tagsInputValue + tagID + ',';
		$('#tag' + tagID).addClass('wordListActive');
	}
	$('#contentTagString').attr('value',tagsInputValue);
	if ($(this).parent().is('div'))
	{
		remove = ['contentTagString'];
		request = String($.cookie('lastSearch'));
		if (request == undefined)
			request = '';
		else
			request = requestRemove(remove,request);
		if (tagsInputValue.length > 2)
			request += '&contentTagString=' + tagsInputValue;
		loadGallery(request);
	}
}		
function fileExtension(filename)
{
	filename = filename.toLowerCase();
	ext = filename.split(".");
	ext = ext[ext.length - 1];
	if (ext == 'jpeg')
		ext = 'jpg';
	return ext;
}
function fileBase(filename)
{
//	filename = filename.toLowerCase();
	base = filename.split(".");
	//everything before the file extension
	base = base[base.length-2];
	base = base.split("\\");
	//everything after the last slash
	base = base[base.length-1];
	return base;
}
function uploadInput()
{
	fileValue = $(this).attr('value');		
	extension = fileExtension(fileValue);
	fileValue = fileBase(fileValue);
	$('#fakeFile').attr('value', fileValue + '.' + extension);		
//just for the blogger page
	$('#tags').show();
//just for the content page
	if ($('#contentName').attr('value') == "")
		$('#contentName').attr('value', fileValue);
	if (extension == 'jpg' && fileValue != '')
	{
		$('#rollover').show();
		$('#thumbnail').hide();
	}
	else
	{
		$('#thumbnail').show();
		$('#rollover').hide();
	}
}
function submitForm(formName) { document.forms[formName].submit(); }
function menuOver() {
	name = "#" + $(this).attr('id');
	$(name + 'Sub').stop(false,true).slideDown(animSpeed);
}
function menuOut() {
	name = "#" + $(this).attr('id');
	$(name + 'Sub').stop(false,true).slideUp(animSpeed);
}

function viewContent()
{
	if (!$(this).parent().is('a'))
	{
		contentID = $(this).attr('contentID');
		fullView(contentID);
	}
	else
	{
		href = $(this).parent().attr('href');
		if (href)
			window.location = href;
	}
}
function fullView(cID)
{
	location.hash = cID
	fullSwitched = false;
	$('#fullHolder').stop(false,true).fadeIn(animSpeed);

	wDim = getWindowSize();
	aspectRatio = screen.height / screen.width;
	height = Math.floor(Math.min(wDim.width * aspectRatio-64,wDim.height));
	data = 'cID=' + cID + '&sWidth=' + wDim.width + '&sHeight=' + wDim.height;
	$.ajax({
		type: "POST",
		url: "/_viewer.php",
		data: data,
		success: function(html){
			$('#fullHolder').html(html);
			fullSwitched = true;
		}
	});
}
function fullClose()
{
	location.hash = '';
	$('#fullHolder').fadeOut(animSpeed).empty();
	$('#fullHolder').unbind('click');
}
function fullLoaded()
{
	//sometimes, only in chrome, the viewer is loaded before the dom is switched in. it's just that fast I guess
	if (!fullSwitched)
	{
		setTimeout('fullLoaded()',20);
		return false;
	}
	$('#fullViewer').stop(false,true).fadeIn(animSpeed);	
}
var suggestionSelection = 0;
var oldValue = '';
function suggest(type,field,e,extraField)
{
	if (extraField)
	{
		extraFieldObj = $('#' + extraField);
		if (extraFieldObj.length < 1)
			extraField = false;
	}
	code = (e.keyCode ? e.keyCode : e.which);
	suggestionPrefix = '#' + field.name;
	suggestionBox = field.name + 'Suggest';
	if (code == 13 && $('#' + suggestionBox).css('display') == 'block')
	{
		if (extraField)
			extraFieldObj.attr('value',$(suggestionPrefix + suggestionSelection).attr(extraField));
		$('#' + suggestionBox).stop(false,true).fadeOut('fast').empty();
	}
	//pressing down
	else if (code == 40)
	{			
		if ($(suggestionPrefix + (suggestionSelection + 1)).length > 0)
		{
			if (extraField)
				extraFieldObj.attr('value',$(suggestionPrefix + suggestionSelection).attr(extraField));
			suggestionSelection++;
			$(suggestionPrefix + suggestionSelection).addClass("sugActive");
			field.value = $(suggestionPrefix + suggestionSelection).text();
			oldValue = field.value;
			$(suggestionPrefix + (suggestionSelection - 1)).removeClass("sugActive");
		}
	}
	//pressing up
	else if (code == 38)
	{
		if ($(suggestionPrefix + (suggestionSelection - 1)).length > 0)
		{
			if (extraField)
				extraFieldObj.attr('value',$(suggestionPrefix + suggestionSelection).attr(extraField));
			suggestionSelection--;
			$(suggestionPrefix + suggestionSelection).addClass("sugActive");
			field.value = $(suggestionPrefix + suggestionSelection).text();
			oldValue = field.value;
			$(suggestionPrefix + (suggestionSelection + 1)).removeClass("sugActive");
		}
	}
	//we have something new in the field
	else if (field.value.length > 0)
	{
		if (field.value != oldValue)
		{
			oldValue = field.value;
			page = '_' + type + 'Suggest.php';
			data = 'name=' + field.value;
			if (extraField)
				data = data + '&extraField=' + extraField;
			$.ajax({
				type: "POST",
				url: page,
				data: data,
				success: function(html){
					suggestionSelection = 0;
					if (html.length > 0)
					{
						if ($('#' + suggestionBox).css('display') == 'none')
							$('#' + suggestionBox).stop(false,true).fadeIn('fast');
						$('#' + suggestionBox).empty().append(html);			
					}
					else
					{
						$('#' + suggestionBox).empty().stop(false,true).fadeOut('fast').empty();
					}
				}
			});
		}
	}
	//there's nothing and the box is showing
	else if ($('#' + suggestionBox).css('display') == 'block')
	{
		$('#' + suggestionBox).stop(false,true).fadeOut('fast').empty();		
	}
}
function suggestionClick()
{
	field = $(this).attr('field');
	extraField = $(this).attr('extraField');
	$('#' + field).attr('value',$(this).text());
	if (extraField)
	 $('#' + extraField).attr('value',$(this).attr(extraField));
}
function suggestionHover(){
	field = $(this).attr('field');
	$('#' + field + 'Suggest > div').each(function(){$(this).removeClass("sugActive");});
	$(this).addClass("sugActive");
}
function suggestionHoverOut() { $(this).removeClass("sugActive"); }
var	suggestionsClear = true;
function noSuggestions()
{
	noSug = true;
	$('.suggestionBox').each(function(){
		if ($(this).css('display') == 'block')
		{
			noSug = false;
			return false;
		}
	});
	return noSug;
}
