﻿var loadInter;
var activeThumbPage = 1;
var lasturl = "";

$(document).ready(function() {

	checkLoad();
	checkUrl();

	initStaticTips();

	//show appropriate scrollSub
	if ($(".sliderMask .navi li.sliderNav").length > 0) {
		$(".sliderMask .navi li.sliderNav").each(function() {
			var item = $(this);
			item.bind("click", function() { flipThumbs($(this).text()) });
		});
	}

	//$("body").attr("onkeydown", "keyDown(event)");

	preloadImgs();

	//preloadImgs2();
});

//standard preload
function preloadImgs() {

	//load image paths into array and attach src path to image object
	images = new Array();
	imageObj = new Image();

	$(".galleryThumbWrap a").each(function(i) {
		var path = $(this).attr("rel").split(",")[0];
		images[i] = path;
		imageObj.src = images[i];
		i++;
	});
}

//preloading using jquery
function preloadImgs2() {
	images = new Array();
	$(".galleryThumbWrap a").each(function(i) {
		var path = $(this).attr("rel").split(",")[0];
		images[i] = path;
		i++;
	});

	$.preloadImages(images);

	jQuery.preloadImages = function() {
		for (var i = 0; i < arguments.length; i++) {
			jQuery("<img>").attr("src", arguments[i]);
		}
	}
}

function checkLoad() {

	//alert("Check load");
	if ($(".photoView .photoViewInner #fullImg").attr("src") != "") {
		$(".photoView .photoViewInner").fadeIn(1000);
		$(".photoView #singlePhotoSub").fadeIn(500);
		$("#ldrPhotoView").hide();
		clearInterval(loadInter);
	}
	else
		loadInter = setInterval("checkLoad()", 5000);
}

function checkUrl(hash) {
	//alert("Check url");
	if (!hash)
		hash = getHash();

	if (hash == "")
		hash = $(".galleryThumbWrap a:first").attr('href').replace("#", "");

	if (hash != lasturl) {
		if ($("#" + hash).length > 0) {
			lasturl = hash;
			updateGallery(hash);
			$(".photoView .photoViewInner").fadeIn("slow");
		}
		else {
			hash = $(".galleryThumbWrap a:first").attr('href').replace("#", "");
			lasturl = hash;
			updateGallery(hash);
		}
	}
}

function updateGallery(id) {
	$("#ldrPhotoView").show();

	id = id.replace("#", "");

	var curPicThumb = $("#" + id);

	var relArray = $(curPicThumb).attr("rel").split(",");
	var path = relArray[0];
	var loadExt = relArray[1];

	var lastIndex = $(".galleryThumbWrap a").size() - 1;
	var currPicThumbIndex = $(".galleryThumbWrap a").index($(curPicThumb));
	var nextIndex = currPicThumbIndex + 1;
	var prevIndex = currPicThumbIndex - 1;

	if (currPicThumbIndex == lastIndex)
		nextIndex = 0;

	if (currPicThumbIndex == 0)
		prevIndex = lastIndex;

	nextId = $(".galleryThumbWrap a:eq(" + (nextIndex) + ")").attr("id");
	prevId = $(".galleryThumbWrap a:eq(" + (prevIndex) + ")").attr("id");


	//alert("path: " + path + ", currIndex: " + currPicThumbIndex + ", nextIndex: " + nextIndex + ", prevIndex: " + prevIndex + ", loadExt: " + loadExt + ", nextId: " + nextId + ", prevId: " + prevId);

	setActiveThumb(id);
	SetPicLink(id, nextId, prevId);
	$("#fullImg").attr("src", path);
	$('#btnAddTag').unbind('click');
	$("#btnAddTag").click(function() { addTags(id); });
	//setPhotoIndex(currPicThumbIndex, lastIndex);

	LoadTags(id, loadExt);
	loadBuyLink(id);
	setFavId(id);
	setInfoLink(id);
	setFbookLink(id);
	setPermalink(id);
	setFavLink(id)

	//$("#ldrPhotoView").hide();

	return false;
}


//run gallery thumbs
function popThumbs() {
	var totalWidth = $("div.scrollContainer div:first-child").width();
	var hiddenWidth = totalWidth - $(".thumbWrap").width();
	if (hiddenWidth != 0) {
		$("#popThumbs a").text(">>");
		$(".thumbWrap").animate({
			width: totalWidth + "px"
		}, 700, function() { $(".sliderMask .navi").show("slow"); setActivePageLink(activeThumbPage); });
	} else {
		$(".sliderMask .navi").hide("slow", function() {
			$(".thumbWrap").animate({
				width: "72px"
			}, 700);
			$("#popThumbs a").text("<<");
		});
	}
};

function setActiveThumb(id) {
	$(".activeThumb").removeClass("activeThumb");
	$("#" + id).addClass("activeThumb");
}

function flipThumbs(page) {
	var container = $(".scrollContainer");
	//var position = $(container).position();
	var newPosition = -1 * (page - 1) * $(".scrollContainer .scrollSub:first-child").width();
	$(container).animate({ left: newPosition }, 500);

	setActivePageLink(page);
};

function setActivePageLink(page) {
	activeThumbPage = page;
	$(".sliderMask .navi .activeSlideLink").removeClass("activeSlideLink");
	$(".sliderMask .navi li:eq(" + (page - 1) + ")").addClass("activeSlideLink");
}

//function setPhotoIndex(currIndex, total) {
//	$("#photoIndex").text("Photo " + (currIndex + 1) + " of " + (total + 1));
//}

function loadBuyLink(picId) {
	var buyLink = $("#shopLink");

	$.get("/lookup/availOptions.aspx?i=" + picId, function(data) {
		if (data == "1") {
			buyLink.show();
			buyLink.attr("href", "/photos/buy.aspx?i=" + picId);
		} else {
			buyLink.hide();
		}
	});
}

function setFavId(picId) {
	var favInput = $(".favPhotoId");
	if (favInput != null) {
		favInput.val(picId);
	}
}

function setInfoLink(picId) {

	var infoLink = $("#infoLink");

	$(infoLink).attr('rel', '/ui/photoInfo.aspx?t=false&i=' + picId);

	$(infoLink).attr('title', '');
}

function setFbookLink(id) {
	var hash = document.location.hash;
	var url = document.location.href;
	url = url.replace(hash, "");
	$("#fbook").attr("href", "http://www.facebook.com/share.php?u=" + url + "#" + id);
}

function setFavLink(id) {
    if ($("#favoriteLink").attr("href") != "#loginPop") {
        $("#favoriteLink").attr("href", "javascript:photoFav(" + id + ");");
    }
}

function setPermalink(id) {
	var perma = $("#permalink");
	var hash = document.location.hash;
	var url = document.location.href;
	url = url.replace(hash, "");
	
	//alert("url: " + url + ", hash: " + hash + ", id: " + id);

	$(perma).qtip({
		content: {
			text: "url: <input onclick='javascript:select();' value='" + url + "#" + id + "'/>"
		},
		style: { name: 'dark'},
		hide: { when: 'mouseout', fixed: true },
		position: {
			adjust: { x: 0, y: 3 },
			corner: {
				target: 'bottomLeft',
				tooltip: 'leftTop'
			}
		}

	});
}

function SetPicLink(id, nextId, prevId) {
	var curPic = document.getElementById("picLink");
	var nextPic = document.getElementById(nextId);
	var prevPic = document.getElementById(prevId);
	var nextLink = document.getElementById("nextLink");
	var prevLink = document.getElementById("prevLink");
	//alert("nextPic: " + nextPic + ", prevPic: " + prevPic + ", nextLink: " + nextLink + ", prevLink: " + prevLink);

	if (nextPic != null && curPic != null && nextLink != null && prevLink != null) {
		prevLink.setAttribute("href", prevPic.getAttribute("href").split("#")[1]);
		curPic.setAttribute("href", nextPic.getAttribute("href").split("#")[1]);
		nextLink.setAttribute("href", nextPic.getAttribute("href").split("#")[1]);
	}
	else {
		curPic.setAttribute("href", "javascript:void(0);");
		curPic.setAttribute("onclick", "");
		curPic.setAttribute("style", "cursor:default;");
	}

};

function LoadTags(picId, loadCredits) {
	var driverLine = $("#allTagWrap");
	var filter = querySt("gf");


	//check if a gallery or category filter is applied
	if (filter != "" && filter != null) {
		filter = "&g=" + filter;
	}
	else {
		filter = querySt("cf");
		if (filter != "" && filter != null) {
			filter = "&c=" + filter;
		} else
			filter = "";
	}

	driverLine.load("/lookup/all.aspx?i=" + picId + "&ex=" + loadCredits + filter, [], function() {
		if (loadCredits) {
			//grab crumbs and photographer
			$("#allTagWrap .tempPhotoCrumbs").hide();
			$("#allTagWrap .tempPtgrCredit").hide();
			if ($("#allTagWrap .tempPhotoCrumbs").length > 0)
				$(".photoCrumbs").html($("#allTagWrap .tempPhotoCrumbs").html());
			if ($("#allTagWrap .tempPtgrCredit").length > 0)
				$(".ptgrCredit").html($("#allTagWrap .tempPtgrCredit").html());
		}
		else {
			$("#allTagWrap .tempPhotoCrumbs").hide();
			$("#allTagWrap .tempPtgrCredit").hide();
		}
	});
};

function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i = 0; i < gy.length; i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function getHash()
{ return document.location.hash.replace("#", ""); }

function keyDown(temp) {
	if (window.event) temp = temp.keyCode; else temp = temp.which;
	switch (temp) {
		case 37:
			updateGallery($("#prevLink").attr("href"));
			break;

		case 39:
			updateGallery($("#nextLink").attr("href"));
			break;
	}

}


function initStaticTips() {

	$("#photoSets ul").width($("#photoSets strong").width() + 20);

	$(".headFilterOpt strong").hover(function() {
		$(this).siblings().show();
	}, function() {
	$(this).siblings().hide();
	});

	$(".headFilterOpt ul").hover(function() {
		$(this).show();
		$(this).siblings().addClass("active");
	}, function() {
		$(this).hide();
		$(this).siblings().removeClass("active");
	});

	$("#shopLink").qtip({
		content: {
			text: 'Purchase this photo'
		},
		style: { name: 'dark', tip: true },
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomRight'
			}
		}
	});

	$("#favoriteLink").qtip({
		content: {
			text: "Add to Favorites"
		},
		style: { name: 'dark', tip: true },
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomRight'
			}
		}
	});

	$("#fbook").qtip({
		content: {
			text: "Share on Facebook"
		},
		style: { name: 'dark', tip: true },
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomRight'
			}
		}
	});


	$("#tagLink").qtip({
		content: {
			text: "Tag Photo"
		},
		style: { name: 'dark', tip: true },
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomRight'
			}
		}
	});

	$("#infoLink").qtip({
		content: {
			text: '<img src="/images/misc/loader.gif" alt="Loading..." />',
			url: jQuery("#infoLink").attr('rel'),
			title: {
				text: 'Photo Details'
			}
		},
		style: { name: 'dark', tip: true,
		width: { min: 170 }
		 },
		hide: { when: 'mouseout', fixed: true },
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomRight'
			}
		},
		api: {
			beforeShow: function() {
				var url = jQuery("#infoLink").attr('rel');
				var data = this.options.content.data;
				var method = this.options.content.method;
				this.loadContent(url, data, method);
			}
		}
	});
}
