var currentId = 0;
var imageSizes = {};
var imageTexts = {};
var pickedImages = [];
var imageIds = [];
var endText = '';
var begText = '';
var alreadyCalled = false;
var currentUrl = '';
var lastReload = Math.round(new Date().getTime() / 1000);
var lastReloadRight = Math.round(new Date().getTime() / 1000);
var lastReloadVideo = Math.round(new Date().getTime() / 1000);
var lastReloadRest  = Math.round(new Date().getTime() / 1000);
var mediaReloads = 0;
var fromReferrer = '';
var intervalId = 0;
var lockNavigation = false;
var isNavigating = false;

function grabUrlChanges () {
	if (String (window.location) != currentUrl) {
		if (fromReferrer.length>0 && !isNavigating) {
			window.location = fromReferrer;
			isNavigating = true;
			return;
		}

		currentId = parseInt (getCurrentHash ());
		showImg (currentId, true);

	}
}

function loadNextImg () {
	if (srcArray.length-1<currentId)
	$('load-image').html ('<img style="width: 0px; height: 0px;" src="' + srcArray [currentId + 1] +'"></img>')
}

function imageSearchID () {
	var referrer = new String (document.referrer);
	fromReferrer = referrer;
	if (referrer.length == 0) return -1;


	var googleRegExp = new RegExp ('^http://(www|images)\.google\.([^/]+)/imgres(?:.+)imgurl=http://files.sharenator.com/[a-zA-Z0-9_]+-s[0-9]+x[0-9]+-([0-9]+)-[0-9]+\.(jpg|png|gif)', 'i');
	if (referrer.match (googleRegExp)) {
		

		var matches = referrer.match (googleRegExp);

		var id = matches[3];
		
		return imageIds.indexOf (id);
	}

	var yahooRegExp = new RegExp ('^http://(images.)?search.yahoo.com/images/view?(.*?)imgurl=files.sharenator.com%2F([a-z0-9_]+)-s([0-9]+)x([0-9]+)-([0-9]+)\.(jpg|png|gif)&', 'i');
	if (referrer.match (yahooRegExp)) {
		var matches = referrer.match (yahooRegExp);
		var id = matches[6];

		return imageIds.indexOf (id);
	}

	return -1;
}

function reloadMedia () {
	++mediaReloads;
	var timestamp = Math.round(new Date().getTime() / 1000);
	$('body').append ('<img width="0" height="0" style="display: none" border=0 src="http://www.hey.lt/count.php?id=sharenator&r='+ timestamp +'">');

	var topAd = 'http://ads.sharenator.com/728x90.html?page=' + String (window.location) + '&timestamp=' + timestamp;
	var rightAd = 'http://ads.sharenator.com/300x600.html?page=' + String (window.location) + '&timestamp=' + timestamp;
	var videoAd = 'http://ads.sharenator.com/video.html?page=' + String (window.location) + '&timestamp=' + timestamp;
	var newAd   = 'http://ads.sharenator.com/unit300x250.html?page=' + String (window.location) + '&timestamp=' + timestamp;
	var underPostAd = 'http://ads.sharenator.com/300x250a.html?page=' + String (window.location) + '&timestamp=' + Math.round(new Date().getTime() / 1000);
	var exchangersAd = 'http://ads.sharenator.com/300x250b.html?page=' + String (window.location) + '&timestamp=' + Math.round(new Date().getTime() / 1000);
	var footerAd = 'http://ads.sharenator.com/728x90b.html?page=' + String (window.location) + '&timestamp=' + Math.round(new Date().getTime() / 1000);

	if (timestamp-lastReload>2) {

		lastReload = timestamp;
		mediaReloads = 0;

		if ($('#top-ad').length>0) {
			$('#top-ad').attr ('src', topAd);
			$('#top-ad')[0].contentWindow.window.location.reload();
		}

		if ($('#new-ad').length>0) {
			$('#new-ad').attr ('src', newAd);
			$('#new-ad')[0].contentWindow.window.location.reload();
		}

		if ($.cookie ('nick') == null && $('#guest-ad3').length>0) {
			var guestAd3 = 'http://ads.sharenator.com/160x600.html?page=' + String (window.location) + '&timestamp=' + timestamp;

			$('#guest-ad3').attr ('src', guestAd3);
			$('#guest-ad3')[0].contentWindow.window.location.reload();
		}
	}

	if (timestamp-lastReloadRight>2) {
		lastReloadRight = timestamp;

		if ($.cookie ('nick') == null && $('#right-ad').length>0) {
			$('#right-ad').attr ('src', rightAd);
			$('#right-ad')[0].contentWindow.window.location.reload();
		}
	}

	if (timestamp-lastReloadRest>15) {
		lastReloadRest = timestamp;

		if ($.cookie ('nick') == null) {
			//if ($('#under-post-ad').length>0) {
			//	$('#under-post-ad').attr ('src', underPostAd);
			//	$('#under-post-ad')[0].contentWindow.window.location.reload();
			//}

			if ($('#exchangers-ad').length>0) {
				$('#exchangers-ad').attr ('src', exchangersAd);
				$('#exchangers-ad')[0].contentWindow.window.location.reload();
			}

			if ($('#footer-ad').length>0) {
				$('#footer-ad').attr ('src', footerAd);
				$('#footer-ad')[0].contentWindow.window.location.reload();
			}
		}
	}

	/*
	if (timestamp-lastReloadVideo>15) {
	lastReloadVideo = timestamp;

	$('#video-ad').attr ('src', videoAd);
	$('#video-ad')[0].contentWindow.window.location.reload();
	} */
}

function scrollToPost (name) {
	if ($('[name='+name+']').length>0) {
		var pos = $('[name='+name+']').position();
		window.scrollTo(0, pos.top-5);
	} else setTimeout ('scrollToPost(\''+name+'\')', 400);
}

function scrollToLast () {
	if ($('[name=last]').length>0) {
		var pos = $('[name=last]').position();
		window.scrollTo(0, pos.top-5);
	} else setTimeout ('scrollToLast()', 400);
}

function getCurrentHash () {
	if (!window.location.hash) return 0;
	if (window.location.hash == '#last') {
		setTimeout ('scrollToLast()', 200);
		return 0;
	}

	if (window.location.hash.substr (0, 5) == '#post') {
		var target_name = window.location.hash.substr (1);
		setTimeout ('scrollToPost(\''+target_name+'\')', 200);
		return 0;
	}

	var matches = window.location.hash.match (/#\/(?:[a-z0-9_]+)-([0-9]+)\.html/i);
	if (matches) return parseInt (matches[1]);
	return 0;
}

function getImgParams (link) {
	if (!link) return;
	
	var linkNameRegExp = new RegExp ('/([a-zA-Z0-9_]+)-s(?:[0-9]+)x(?:[0-9]+)-([0-9]+)-(?:[0-9]+)\.(jpg|png|gif)');
	return link.match (linkNameRegExp);
}

function voteBox () {
	$('#vote_box').modal ({
		onClose: function ()
		{
			if (main_flash) load_main_flash ();
			$.modal.close();
			lockNavigation = false;
		}
	});
	close_flashes ();

}

function showImg (id, main_script) {
	if (main_script == null) {
		reloadMedia ();
	}

	if (id<0) id = slideImages.length-1;

	if (slideImages.length <= id) {
		if (!lockNavigation) {
			if (!topicRated && $.cookie ('nick') != null) voteBox ();
			else document.location = 'http://members.sharenator.com/random.php?pics=1';
			lockNavigation = true;
		}
		onForward = function () {};
		id = 0;
		return;
	}

	$('.slidenumber').html ((id+1) + ' of ' + slideImages.length);

	if (id+1 == slideImages.length) {
		// change text
		$('#nextTxt').html ('<b>Next Post &gt;</b>');
		$('#nextTxt2').html ('<b>Next Post &gt;</b>');
		
		if ($.cookie('refWahoha')==null && $.cookie ('nick')==null && $.cookie ('meerkat')==null) {
			$('#frame-div').html ('<iframe src="/wahoha.html" scrolling="no" border="0" frameBorder="0" style="width: 100%; height: 170px; border: 0; "></iframe>');
			$('#meerkat').show ();
			$('#meerkat').meerkat({
				background: 'url(http://www.sharenator.com/images/meerkatbg.png) repeat-x left top',
				height: '200px',
				width: '100%',
				position: 'bottom',
				close: '.close-meerkat',
				dontShowAgain: '.dont-show',
				animationIn: 'slide',
				animationSpeed: 1500
			});
			
			 //$.cookie ('meerkat', 'true', {path: '/'});
		}
	} else {
		$('#nextTxt').html ('Next &gt;');
		$('#nextTxt2').html ('Next &gt;');
	}

	var matches = getImgParams (pickedImages[id]);
	if (matches) var imageName = matches[1];
	else imageName = 'empty';

	if (id>0 || window.location.hash.length>0) window.location.hash =  '/'+imageName + '-' + id + '.html';
	currentUrl = String (window.location);

	currentId = id;
	$('#main-image').html (slideImages[id]);
	$('#main-image').find('img').css ('cursor', 'pointer');
	$('#main-image').find('img').hide();
	$('#main-image').find('img').fadeIn (500);

	var pos = $('#div-pos').position();
	if ($(window).scrollTop()>pos.top) window.scrollTo(0, pos.top-20);

	var imgId = 'img-'+id;

	if (imageSizes [imgId]) {
		//$('#image-size').html ('View: <a target="_blank" href="'+imageSizes[imgId].link+'">'+imageSizes[imgId].text+'</a>');
	} else $('#image-size').html ('');

	function withMissingBr (text) {
		if (text.substr (text.length-8).toLowerCase() != '<br><br>') if (text.substr (text.length-4).toLowerCase() == '<br>') text+= '<br>';
		else text+= '<br><br>';
		return text;
	}

	function withoutFrontBr (text) {
		while (text.substr (0, 4).toLowerCase() == '<br>') text = text.substr (4);
		return text;
	}

	if (imageTexts [imgId]) {
		$('#above-image').html (withoutFrontBr (withMissingBr (imageTexts [imgId])));
	} else $('#above-image').html ('');

	if (begText.length>0 && id==0) $('#above-image').prepend (withoutFrontBr (withMissingBr (begText)));
	if (endText.length>0 && id==slideImages.length-1) $('#under-image').html ('<br>'+withoutFrontBr(endText));
	else $('#under-image').html ('');

	loadNextImg ();
}

function slideShow () {
	if (!alreadyCalled) alreadyCalled = true;
	else return;

	$('#main-contents').find('.center').each (function (index) {
		if ($(this).find('img').length == 0) return;

		var imgId = $(this).find('img').attr('id');

		/*
		$(this).find('a').each (function () {
		var target = $(this).attr('target');
		if (target == '_blank') imageSizes [imgId] = {'text': $(this).html(), 'link': $(this).attr('href')};
		else {
		*/
		pickedImages.push ($(this).find('img').attr('src'));
		var matches = getImgParams ($(this).find('img').attr('src'));

		if (matches) imageIds.push (matches[2]);
		/*
		}
		});*/

		//if ($(this).next()[0].tagName == 'BR') $(this).next().remove();

		$(this).replaceWith (imgId);
	});

	if ($('#fb-like').length > 0) $('#fb-like').html ('');

	var text = $('#main-contents').html();

	var tabChr = String.fromCharCode (9);
	var breakChr = String.fromCharCode (10);
	var replaceRegExp = new RegExp (tabChr + '|' + breakChr, 'g');
	text = text.replace (replaceRegExp, '');

	text = text.replace (/<script(.*?)<\/script>/g, '');

	var text_beg = false;
	var text_bet = false;
	var text_end = false;

	if (text.indexOf ('img-0')>10) text_beg = true; // pradzioj teksto

	for (var id in slideImages) {
		var imgId = 'img-'+id;
		var nextId = 'img-' + (parseInt (id)+1);

		if (parseInt (id)<slideImages.length-1) {
			if (text.indexOf (nextId) - text.indexOf (imgId)>10) text_bet = true;
		}
	}


	var lastId = 'img-' + (slideImages.length -1);
	if (text.indexOf (lastId)>-1) {
		if (text.length - text.indexOf (lastId)>15) text_end = true; // po paskutiniu paveiksliuku
	}

	function cutEnd (text) {
		var lastId = 'img-' + (slideImages.length-1);
		return text.substr (text.indexOf(lastId) + lastId.length);
	}

	function cutBeg (text) {
		var firstId = 'img-0';
		return text.substr (0, text.indexOf (firstId));
	}

	if ((text_beg && text_bet) || (text_bet && !text_end)) {
		// tekstas virs paveiksliuku
		for (var id in slideImages) {
			var imgId = 'img-'+id;
			var prevId = 'img-' + (parseInt (id)-1);

			if (id == 0) imageTexts [imgId] = cutBeg (text);
			else {
				imageTexts [imgId] = text.substr (text.indexOf (prevId)+prevId.length, text.indexOf (imgId)-text.indexOf (prevId)-prevId.length);
				imageTexts [imgId] = imageTexts [imgId].replace ('<br>', '');
				imageTexts [imgId] = imageTexts [imgId].replace ('<BR>', '');
				imageTexts [imgId] = imageTexts [imgId].replace (/<br><br><br>/gi, '<br><br>');
			}
		}

		if (text_end) endText = cutEnd (text);


	} else
	if (!text_beg && text_bet && text_end) {
		// tekstas po paveiksliukais
		for (var id in slideImages) {
			var imgId = 'img-'+id;
			var nextId = 'img-'+ (parseInt (id)+1);

			if (id == (slideImages.length-1)) imageTexts [imgId] = cutEnd (text) + '<br>';
			else {
				imageTexts [imgId] = text.substr (text.indexOf (imgId) + imgId.length, text.indexOf (nextId)-text.indexOf (imgId) - nextId.length) + '<br>';
			}

		}
	}

	if (!text_beg && !text_bet && text_end) endText = cutEnd (text);
	if (text_beg && !text_bet && !text_end) begText = cutBeg (text);
	if (text_beg && !text_bet && text_end) {
		begText = cutBeg (text);
		endText = cutEnd (text);
	}

	$('#main-contents').html ('');
	$('#main-contents').html ('<div id="div-pos"></div><div class="slidebuttons"><span class="slideshow">Slideshow: </span>\
	<span class="slideshow mar"><a href="#" onclick="return false" id="return-original">+ expand all</a></span>\
		<a class="button" title="Tip: try using keyboard arrows" id="nextBtn"><span id="nextTxt">Next > </span></a>\
		<span class="slidenumber"></span>\
		<a class="button" id="prevBtn" title="Tip: try using keyboard arrows"><span>< Prev </span></a>\
	<div style="clear: both;"></div>\
</div>\
	 <div id="container" class="slidepic"><div id="above-image"></div><p class="center" id="main-image"></p><div id="image-size" style="text-align: center"></div><div id="under-image"></div></div> <div id="load-image"></div>\
	 <div class="slidebuttons slbott"><span class="slideshow mar bott">\
		<fb:like href="' + String (window.location) +'" send="true"></fb:like>\
		<div id="fb-page"></div></span>\
	<div class="bottbuttons">\
		<a class="button" id="nextBtn2" title="Tip: try using keyboard arrows"><span id="nextTxt2">Next > </span></a>\
		<span class="slidenumber"></span>\
		<a class="button" id="prevBtn2" title="Tip: try using keyboard arrows"><span>< Prev </span></a>\
</div></div><br />');

	function onForward () {
		showImg (currentId + 1);
	}

	function onBackward () {
		showImg (currentId - 1);
	}


	$('#main-image').click (onForward);
	$('#nextBtn').mousedown (onForward);
	$('#nextBtn2').mousedown (onForward);
	$('#prevBtn').mousedown (onBackward);
	$('#prevBtn2').mousedown (onBackward);

	$(document).keyup (function (event) {
		var activeElement = document.activeElement.tagName;
		if (activeElement == 'INPUT' || activeElement == 'TEXTAREA') return;
		//alert (window.location.pathname);

		if (event.keyCode == 39) onForward();
		else
		if (event.keyCode == 37) onBackward();
	});

	$('#return-original').click (function() {
		clearInterval (intervalId);
		$('#main-contents').html (originalBackup);

		$('#main-contents').find('.center').each (function (index) {
			$(this).find ('img').attr ('src', srcArray[index]);

			return false;
		});


		window.location.hash = '';
	});

	imageSearchID ();

	var searchId = imageSearchID();
	if (searchId>-1) currentId = searchId;
	else currentId = getCurrentHash ();

	showImg (currentId, true);
	intervalId = setInterval (grabUrlChanges, 500);

}
