var init = false;
var stormq = null, frmFlickr, frm2;
var fxFullSize = null, fxLegend = null, fxHitEnter = null, fxSplash = null;
var allPhotos = null;
var clicklist = null;
var currentFlickrPhoto = null; var isMac = false, isSafari = false;
var currentQuery = null, currentQueryLicense = null;
var qsParam = new Object();
function g(id) { return document.getElementById(id); }
Array.prototype.clear=function() { this.length = 0; };
function initPage() {
	
	isMac = (navigator.appVersion.indexOf('Mac') != -1);

	if (navigator.vendor && navigator.vendor.indexOf('Apple') != -1) {
		isSafari = true;
		document.body.id = 'safari';
	}
	g('searchbox').style.display = 'block';
	g('advanced-link').style.display = 'block';
	
	resizePage();
	allPhotos = new Object;
	stormq = g('stormq');
	
	fstormClick(true);
	
	clicklist = new Array();
	
	fxFullSize = new fx.Opacity('fullsize-image', {duration: 1000, transition: fx.sinoidal});
	fxLegend = new fx.Opacity('legend', {duration: 400});
	fxHitEnter = new fx.Opacity('hit-enter', {duration: 400});
	fxSplash = new fx.Opacity('splash', {duration: 400} );
	
	setInterval('ping()', 15000);
	
	fxLegend.hide();
	fxHitEnter.hide();
	fxSplash.setOpacity(1);
	
	updateTrayDisplay();

	if (window.opera) {
		g('f2').width = '335';
		g('legend').style.visibility = 'hidden';
		g('hit-enter').style.visibility = 'hidden';
	}
	else {
		g('legend').style.visibility = 'visible';
		g('hit-enter').style.visibility = 'visible';
	}
	
	init = true;
	
	processQueryString();
	
}

function processQueryString() {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	if (!parms || parms.length == 0) {
		parms = new Array(query);
	}
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParam[key] = unescape(val);
		}
		else {
			var key = parms[i];
			qsParam[key] = key;
		}
	}
	
	for(var key in qsParam) {
		if (qsParam[key]) {
			switch(key) {
				case 'advanced':
					advanced();
					break;
				case 'q':
					stormq.value = qsParam[key];
					window.query();
					break;
			}
		}
	}

}

function explain() {
	toggle('fstorm-explained');
}

function toggle(id, visibleState) {
	var obj = g(id);
	if (!obj) return;
	if (!visibleState) visibleState = 'block';
	if (obj.style.display == 'none')
		obj.style.display = visibleState
	else
		obj.style.display = 'none';
}

function toggleViz(id) {
	var obj = g(id);
	if (!obj) return;
	if (obj.style.visibility == 'hidden')
		obj.style.visibility = 'visible';
	else
		obj.style.visibility = 'hidden';
}


var timerHideLicense = null;
function showLicense() {
	if (timerHideLicense) {
		clearTimeout(timerHideLicense);
		timerHideLicense = null;
	}
	g('license-explain').style.display = 'inline';
}
function hideLicense() {
	if (!timerHideLicense) {
		timerHideLicense = setTimeout('timedHideLicense()', 1000);
	}
}

function timedHideLicense() {
	g('license-explain').style.display = 'none';
	timerHideLicense = null;
}

function toggleIntro() {
	if (hasClicked) {
		fxLegend.toggle();
		// fxHitEnter.toggle();
	}
	fxSplash.toggle();
}

var introHidden = false;
var hasQueried = false;
function query() {
	if (!init) return false;
	word = encodeURIComponent(stormq.value);
	if (!introHidden) {
		toggleIntro();
		if (window.opera) {
			g('legend').style.visibility = 'hidden';
			g('hit-enter').style.visibility = 'hidden';
		}
		introHidden = true;
		switchTo(mode);
		setTimeout('setWaitingVisible(true)', 1100);
	}
	else
		setWaitingVisible(true);

	setTimeout('hideIntro()', 1000);
	
	g('update-btn').style.display = 'none';
	g('results').style.display = 'block';
	
	currentQueryLicense = getCurrentLicenseFilter();
	if (currentQueryLicense) {
		url = "flickrize.php?q=" + word + "&license=" + currentQueryLicense;
	}
	else {
		url = "flickrize.php?q=" + word;
	}
	
	g('f2').src = url;
	
	currentQuery = stormq.value;
	hasQueried = true;
	return false;
}

function hideIntro() {
	g('legend').style.display = 'none';
	g('hit-enter').style.display = 'none';
	g('splash').style.display = 'none';
	introHidden = hasClicked = true;
}

function updateCurrentImageSize() {
	if (!currentFlickrPhoto) return;
	var curr = g('fullsize-image');
	if (!curr) {
		return;
	}
	curr.src = getImageUrlForScreenSize(currentFlickrPhoto);
}

function getImageUrlForScreenSize(photo) {
	if (document.body.className == SMALL_SCREEN) {
		return photo.getSmall();
	}
	else {
		return photo.getMedium();
	}
}

function FlickrPhoto(id, image_base, author, license) {
	this.id = id;
	this.image_base = image_base;
	this.author = author;
	this.author_id = id.split('/')[0];
	this.license = license;
	this.query = currentQuery;
	this.num = ++numClicks;
	this.query_license = (currentQueryLicense != null) ? currentQueryLicense : '-';
	return this;
}

FlickrPhoto.prototype.getUrl = FlickrPhoto_getUrl;
function FlickrPhoto_getUrl() {
	return "http://www.flickr.com/photos/" + this.id;
}

FlickrPhoto.prototype.getOriginal = FlickrPhoto_getOriginal;
function FlickrPhoto_getOriginal() {
	return "http://static.flickr.com/" + this.image_base + "_o.jpg";
}

FlickrPhoto.prototype.getMedium = FlickrPhoto_getMedium;
function FlickrPhoto_getMedium() {
	return "http://static.flickr.com/" + this.image_base + ".jpg";
}

FlickrPhoto.prototype.getSmall = FlickrPhoto_getSmall;
function FlickrPhoto_getSmall() {
	return "http://static.flickr.com/" + this.image_base + "_m.jpg";
}

FlickrPhoto.prototype.getSquare = FlickrPhoto_getSquare;
function FlickrPhoto_getSquare() {
	return "http://static.flickr.com/" + this.image_base + "_s.jpg";
}

var fadeOutTimer = null;
function showFlickrPhoto(photo, fromClickStream) {
	
	currentFlickrPhoto = photo;
	
	g('xpert-image').style.display = 'none';
	g('flickr-image').style.display = 'block';
	g('photo-details').style.display = 'none';
	g('photo-loading').style.display = 'block';
	g('preview').style.display = 'block';
	
	var image = g('fullsize-image');
	
	fadeOutTimer = setTimeout('fadeOut()', fromClickStream ? 500 : 50);
	
	image.onload = function() { showFlickrPhotoDetails(currentFlickrPhoto); }
	image.src = getImageUrlForScreenSize(photo);
	
	hideShortcutHint();

	if (!fromClickStream) addToClickStream(photo);
	
}

function fadeOut() {
	fxFullSize.custom(1.0, 0.6);
	fadeOutTimer = null;
}

function showFlickrPhotoDetails(photo) {
	
	clearTimeout(fadeOutTimer);
	fxFullSize.clearTimer();
	fxFullSize.setOpacity(1);
	
	g('photo-details').style.display = 'none';
	g('photo-loading').style.display = 'none';
	
	var url = photo.getUrl();

	g('flickr-link').href = url;
	g('fullsize-link').href = url;
	g('contact-action').href = 'http://www.flickr.com/messages_write.gne?to=' + photo.author_id;
	g('author-link').innerHTML = photo.author;
	g('author-link').href = 'http://www.flickr.com/photos/' + photo.author_id + '/';
	g('author-link').innerHTML = photo.author;
	
	timedHideLicense();
	
	var lic_descr = getLicenseDescription(photo.license);
	if (lic_descr == null) {
		g('copyright-image').src="images/cr.gif";
		g('copyright-license').style.display = 'inline';
		g('cc-license').style.display = 'none';
		g('download-action').href = photo.getMedium().replace('.jpg', '_d.jpg');	
		g('download-action').style.display = 'none';
	}
	else  {
		g('copyright-image').src="images/cc.gif";
		g('copyright-license').style.display = 'none';
		g('cc-license').style.display = 'inline';
		var obj = g('cc-license-link');
		obj.href =  getLicenseUrl(photo.license);
		obj.innerHTML = lic_descr;
		g('download-action').href = photo.getOriginal().replace('_o.jpg', '_o_d.jpg');	
		g('download-action').style.display = 'inline';
	}
	
	g('photo-loading').style.display = 'none';
	g('photo-details').style.display = 'block';
	
	updateTrayAction(photo);
	
}

function nodownload() {
	alert('This Flickr user requested that the photo is not available for download at high resolution ("All Rights reserved").\nPlease contact the Flickr user to ask for permission.');
}

function updateTrayAction(photo) {
	if (photo != currentFlickrPhoto || currentFlickrPhoto == null) return;
	trayAction = g('tray-action');
	if (isInTray(photo)) {
		trayAction.innerHTML = "<strong>Remove</strong> from Tray";
	}
	else {
		trayAction.innerHTML = "Add to Tray";
	}
}

function getLicenseDescription(license_id) {
	switch (license_id) {
		case '4':
			return "Attribution";
		case '6':
			return "Attribution, No Derivatives";
		case '3':
			return "Attribution, No Derivatives, Non-Commercial";
		case '2':
			return "Attribution, Non-Commercial";
		case '1':
			return "Attribution, Non-Commercial, Share-Alike";
		case '5':
			return "Attribution, Share-Alike";
		default:
			return null;
	}
}

function getLicenseUrl(license_id) {
	switch (license_id) {
		case '4':
			return "http://creativecommons.org/licenses/by/2.0/";
		case '6':
			return "http://creativecommons.org/licenses/by-nd/2.0/";
		case '3':
			return "http://creativecommons.org/licenses/by-nc-nd/2.0/";
		case '2':
			return "http://creativecommons.org/licenses/by-nc/2.0/";
		case '1':
			return "http://creativecommons.org/licenses/by-nc-sa/2.0/";
		case '5':
			return "http://creativecommons.org/licenses/by-sa/2.0/";
		default:
			return "#";
	}
}

function flickrClick(id, image_base, author, license, wasCtrl) {
	
	var photo = allPhotos[id];
	
	if (!photo) {
		allPhotos[id] = photo = new FlickrPhoto(id, image_base, author, license);
	}
	
	if (wasCtrl) {
		modifyTray(photo, isInTray(photo));
		switchToTray();
	}
	else {
		showFlickrPhoto(photo, false);
		if (mode == NONE) switchToHistory();
	}
}

function clicked(photo) {
	if (!photo || !photo.id) return;
	clicklist.push(photo);
}

function ping() {
	if (clicklist.length == 0)
		return;
	var qs = new Array();
	qs.push("h=" + numInStream  + "&t=" + numInTray);	
	for (var p in clicklist) {
		var photo = clicklist[p];
		if (!photo || photo.id == undefined) continue;
		qs.push("&p[]=" + encodeURIComponent(photo.id));
		qs.push("&i[]=" + encodeURIComponent(photo.image_base));
		qs.push("&l[]=" + encodeURIComponent(photo.license));
		qs.push("&c[]=" + encodeURIComponent(photo.num));
		qs.push("&q[]=" + encodeURIComponent(photo.query));
		qs.push("&ql[]=" + encodeURIComponent(photo.query_license));
	}
	clicklist.clear();
	if (qs.length == 1) return;
	var post = qs.join('');
	new ajax ('c.php', { postBody: post } );
}

function addToOrRemoveFromTray(photo) {
	var alreadyInTray = isInTray(photo);
	modifyTray(photo, alreadyInTray);
}


var stream = null;
var urls = null;
function addToClickStream(photo) {
	if (stream == null) stream = new Object;
	if (divStream == null) var divStream = g('clickstream');
	divStream.style.display = 'block';
	addTo(stream, divStream, photo);
}


var tray = null;
var numInTray = 0, numInStream = 0, numClicks = 0;
var numHints = 0;
function addToTray() {
	if (!isInTray(currentFlickrPhoto)) {
		modifyTray(currentFlickrPhoto, false);
	}
	else {
		modifyTray(currentFlickrPhoto, true);
		if (numHints == 1) {
			showShortcutHint();
			numHints = 2;
		}
	}
	switchToTray();
	
	if (numHints == 0) {
		showShortcutHint();
		numHints = 1;
	}
}
function showShortcutHint() {
	var key = "<strong>CTRL</strong>";
	if (window.opera || isMac) {
		key = "<strong>SHIFT</strong>";
	}
	else {
		// leave as is
	}
	g('shortcut-key').innerHTML = key;
	g('shortcut').style.display = 'block';
}
function hideShortcutHint() {
	g('shortcut').style.display = 'none';
}
function modifyTray(arg, remove) {
	var photo = arg || currentFlickrPhoto;
	if (!photo) return;
	if (tray == null) tray = new Object;
	if (divStream == null) var divStream = g('tray');
	
	if (remove) {
		if (isInTray(photo)) numInTray--;
		removeFrom(tray, divStream, photo);
	}
	else {
		if (!isInTray(photo)) numInTray++;
		addTo(tray, divStream, photo);
	}
	
	updateTrayDisplay();
	updateTrayAction(photo);
}

function isInTray(photo) {
	if (!tray) return null;
	return (tray[photo.id] != null);
}

function removeFromTray(photo) {
	if (!photo) photo = currentFlickrPhoto;
	modifyTray(photo, true);
}

function updateTrayDisplay() {
	var obj = g('more-tray-buttons');
	if (numInTray > 0) {
		obj.className = 'enabled';
	}
	else {
		obj.className = 'disabled';
	}
	var obj = g('num');
	if (!obj) return;
	obj.innerHTML = numInTray;
}
function clearTray() {
	if (!tray) return;
	var toRemove = new Array();
	for (var id in tray) {
		toRemove.push(tray[id]);
	}
	var divStream = g('tray');
	for (var i = 0; i < toRemove.length; i++) {
		var img = toRemove[i];
		divStream.removeChild(img);
	}
	tray = new Object();
	numInTray = 0;
	updateTrayDisplay();
	updateTrayAction(currentFlickrPhoto);
}

function download() {
	var qs = new Array();
	qs.push("save.php?action=save");
	for (var id in tray) {
		var photo = getPhotoFromImageObject(tray[id]);
		if (!photo) continue;
		qs.push("&id[]=" + encodeURIComponent(photo.id));
		qs.push("&img[]=" + encodeURIComponent(photo.image_base));
		qs.push("&auth[]=" + encodeURIComponent(photo.author));
		qs.push("&lic[]=" + encodeURIComponent(photo.license));
		qs.push("&q[]=" + encodeURIComponent(photo.query));
	}
	if (qs.length == 1) return;
	var url = qs.join("");
	var newWindow = window.open(url);
	if (!newWindow) {
		alert('Hm- We tried to open a new window for your downloads but your browser appears to have blocked it. Please check your pop-up blocker settings and try again.');
	}
}


function removeFrom(arr, div, photo) {
	var id = photo.id;
	var img = arr[id];
	if (img != null) {
		div.removeChild(img);
		img = null;
		arr[id] = null;
		if (arr == stream) numInStream--;
	}	
	else {
		if (arr == stream) clicked(photo);
	}
	return img;
}
function addTo(arr, div, photo) {

	var img = removeFrom(arr, div, photo);
	
	var id = photo.id;
	var isTray = arr == tray;
	
	
	img = document.createElement("img");
	img.src = photo.getSquare();
	
	if (urls == null) urls = new Object;
	if (urls[img.src] == null) urls[img.src] = id;
	
	if (isTray) {
		img.onclick = trayClick;
	}
	else {
		img.onclick = historyClick;
		numInStream++;
	}

	if (div.childNodes.length > 0)
		div.insertBefore(img, div.childNodes[0]);
	else
		div.appendChild(img);
			
	if (div.childNodes.length >= 12) {
		div.className = 'overflow';
	}
	else {
		div.className = '';
	}
	
	arr[id] = img;
}
function getTarget(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}
function getPhotoIdFromClick(e) {
	var targ = getTarget(e);
	if (!targ.src || !urls || !urls[targ.src]) return null;
	
	var id = urls[targ.src];
	return id;
}

function getPhotoFromImageObject(img) {
	if (!img || !allPhotos || !img.src || !urls || !urls[img.src]) return null;
	var id = urls[img.src];
	return allPhotos[id];
}

function hasCtrlKey(e) {
	return (e.ctrlKey||e.shiftKey||e.altKey);
}

function historyClick(e) { 
	if (!e) e = window.event;
	lid(getPhotoIdFromClick(e), HISTORY, hasCtrlKey(e));
}
function trayClick(e) { 
	if (!e) e = window.event;
	lid(getPhotoIdFromClick(e), TRAY, hasCtrlKey(e));
}
var hasClicked = false, bInit = 0;
function queryClick() {
	try {
		if (!init) { if (bInit > 2) return; bInit++; setTimeout('queryClick()', 1000); }
		if (!hasClicked) {
			fxLegend.toggle();
			// if (g('advanced').style.display != 'block') fxHitEnter.toggle();
		}
		hasClicked = true;
	}
	catch(x) {
		if (bInit > 2) return; bInit++; setTimeout('queryClick()', 1000);
	}
}
function fstormClick(randomize) {
	var q = getNextQuery(randomize);
	if (q != null) {
		stormq.value = q;
		if (!randomize) stormq.focus();
	}
}
var queryIndex = 0;
function getNextQuery(randomize) {
	var result = null;
	if (queries && queries.length > 0) {
		if (randomize) {
			var len = queries.length - 1;
			queryIndex = Math.floor( len * Math.random() );
		}
		if (queryIndex >= queries.length)
			queryIndex = 0;
		result = queries[queryIndex];
	}
	queryIndex++;
	return result;
}

var NONE = 0;
var HISTORY = 1;
var TRAY = 2;
var mode = NONE;

function switchTo(newMode) {
	mode = newMode;
	var historyButton = g('history-button');
	var trayButton = g('tray-button');
	var clickStreamDiv = g('clickstream');
	var trayDiv = g('tray');
	var moreButtons = g('more-tray-buttons');

	switch(mode) {
		case NONE:
			clickStreamDiv.style.visibility = trayDiv.style.visibility = 'hidden';
			historyButton.className = trayButton.className = '';
			break;
		case HISTORY:
			trayDiv.style.visibility = 'hidden';
			clickStreamDiv.style.visibility = 'visible';
			historyButton.className = 'active';
			moreButtons.style.display = 'none';
			trayButton.className = '';
			break;
		case TRAY:
			if (hasClicked && introHidden) trayDiv.style.visibility = 'visible';
			clickStreamDiv.style.visibility = 'hidden';
			trayButton.className = 'active';
			historyButton.className = '';
			moreButtons.style.display = 'block';
			break;
	}
	if (hasClicked && introHidden) trayDiv.style.display = clickStreamDiv.style.display = 'block';
	
}

function switchToTray() {
	switchTo(TRAY);
}
function switchToHistory() {
	switchTo(HISTORY);
}


function lid(id, source, hasCtrl) {
	var photo = allPhotos[id];
	if (photo == null) return;
	hideShortcutHint();
	if (hasCtrl) {
		if (source == TRAY || isInTray(photo))
			removeFromTray(photo);
		else 
			modifyTray(photo);
	}
	else {
		showFlickrPhoto(photo, source == HISTORY);
	}
}



function xpertImage(src, url) {
	divPreview = g('xpert-image');
	g('flickr-image').style.display = 'none';
	g('preview').style.display = 'block';
	divPreview.style.display = 'block';
	currentFlickrPhoto = null;	
	divPreview.innerHTML = '<p><a href="' + url + '" target="_blank"  ><img id="currentPhoto" src="http://www.stockxpert.com/' + src + '" border="0"/></a></p><p class="flickr-link"><a href="' +  url + '" target="_blank">Open on Stock Expert</a></p>';

}
function ct() {
	var obj = g('ce');
	obj.href = String.fromCharCode(109,97,105,108,116,111,58,102,108,105,99,107,114,115,116,111,114,109,64,122) + String.fromCharCode(111,111,45,109,46,99,111,109);
	setTimeout("rs()", 1000);
}
function rs() {
	document.getElementById('ce').href = "#contact";
}
function ce() {
	102,108,105,99,107,114,115,116,111,114,109,64,122,111,111,45,109,46,99,111,109
}
function getScreenWidth() {
	// via the fantubulous quirksmode :) 
	// http://www.quirksmode.org/viewport/compatibility.html
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return x;
}
var SMALL_SCREEN = 'small-screen';
var MEDIUM_SCREEN = 'medium-screen';
var LARGE_SCREEN = 'large-screen';

var resizeTimer = null;
var hasResized = false;
function resizePage() {
	if (hasResized) hasResized = false;
	if (!hasResized && !resizeTimer)
		resizeTimer = setTimeout('resizeTimerFunction()', 1000);
}
function resizeTimerFunction() {
	var newWidth = getScreenWidth();
	if (newWidth >= 1100) {
		document.body.className = LARGE_SCREEN;
	}
	else if (newWidth >= 1000) {
		document.body.className = MEDIUM_SCREEN;
	}
	else {
		document.body.className = SMALL_SCREEN;
	}
	updateCurrentImageSize();
	hasResized = true;
	clearTimeout(resizeTimer);
	resizeTimer = null;
}

function refineSearch(word) {
	var newQuery = null;
	if (currentQuery == null)
		newQuery = word;
	else {
		var index = currentQuery.indexOf(',');
		if (index != -1) {
			var sourceWord = currentQuery.substr(0, index);
			newQuery = sourceWord + ', ' + word;
		}
		else {
			newQuery = currentQuery + ', ' + word;
		}
	}
	if (newQuery) {
		stormq.value =currentQuery = newQuery;
		query();
	}
}

function setWaitingVisible(flag) {
	var obj = g('waiting');
	if (!obj) return;
	obj.className = '';
	obj.style.visibility = (flag) ? 'visible' : 'hidden';
}

function startLoadingResults() {
	var obj = g('waiting');
	if (!obj) return;
	obj.className = 'dimmed';
}
function doneLoadingResults() {
	setWaitingVisible(false);
}
function advanced() {
	if (!init) return;
	var adv = g('advanced');
	g('hit-enter').style.display = 'none';
	g('cc-banner').style.display = 'none';
	g('update-btn').style.display = 'none';
	toggle('advanced');
}

function showCCBanner() {
	toggle('cc-banner');
}

function licenseChanged() {
	var objLicense = g('license');
	var option = objLicense.options[objLicense.selectedIndex];
	if (option.value == '') {
		g('update-btn').style.display = 'none';
	}
	else  {
		if (option.value == '-') {
			objLicense.selectedIndex = objLicense.options.length - 2;
		}
		g('cc-banner').style.display = 'none';
		g('update-btn').style.display = 'block';
	}
}

function updateLicenseFilter() {
	if (!hasClicked) {
		g('legend').style.display = 'none';
		g('hit-enter').style.display = 'none';
	}
	query();
}

function getCurrentLicenseFilter() {
	var adv = g('advanced');
	if (adv.style.display != 'none') {
		var objLicense = g('license');
		var option = objLicense.options[objLicense.selectedIndex];
		if (option.value == '') {
			return null;
		}
		else {
			if (option.value == '-') {
				objLicense.selectedIndex = objLicense.options.length - 2;
			}
			return objLicense.options[objLicense.selectedIndex].value;
		}
	}
	else {
		return null;
	}
}

