﻿// Do this as early as possible
$(document).ready(function(){
	// Hook up an onload handler to always
	//	fade in asynchronously load images.
    $(".image").load(function () {
        $(this).fadeIn("slow");
        if (isPlaying) {
            // Showing a slide...show for 5 seconds and
            //	then load the next one.
            setTimeout(function () { showNextSlide(); }, 3000);
        }
    });
	slider.init("slidetop", "slidebot", "slider");
	
	// Initialize the hover buttons
	initHoverButtons();
	
	// Load the thumbnails
	loadThumbs("");
});

// Add a fade effect on the mouse over/out
function initHoverButtons()
{
	$(".hover_button img").each(function(){
		$(this).fadeTo("slow", 0.67);
		$(this).hover(
				function(){
					$(this).fadeTo("fast", 1.0);
				},
				function(){
					$(this).fadeTo("fast", 0.67);
				}
			);
	});
}

// Request a new set of thumbnails
function loadThumbs( relativePath )
{
    var rp = relativePath.replace(/\\/g, '/');
    rp = rp.replace("http://photo.swtenergy.com/", "")
    rp = unescape(rp)
	$.ajax({
		type: "POST",
		url: "ServiceLayer.asmx/GetThumbHtml",
		data: "{relativePath:'" + rp + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(msg){OnFailed(msg.d);},
		success: function(msg){OnSucceedThumbs(msg.d);}
	});
}

// Parse the returned html and update the UI
function OnSucceedThumbs(html)
{
	// Really have two html chunks seperated by a '|'
	var temp = new Array();
	temp = html.split('|');

	$("#_divOuterThumbs").fadeOut("slow", function () {

	    // Reset the slider to the top
	    slider.moveTop();

	    // Show the new html
	    $(this).html(temp[0]).fadeIn("slow", function () {
	        // Calculate and the length for the slider
	        var offset = $(".outerFrame:last").offset();
	        var slidearea = $("#slidearea").offset();
	        var height = slidearea.top - offset.top;
	        slider.setSlideLength(height);

	        // Connect up the javascript for each image frame
	        $(".imageFrame").each(function (i) {
	            // Fade in the element as soon as possible
	            $(this).fadeIn("slow").fadeTo("slow", 0.67);

	            // Hook up mouse event handlers.
	            $(this).hover(
								function () {
								    $(this).fadeTo("fast", 1.0);
								},
								function () {
								    $(this).not(".imageFrameSelected").fadeTo("fast", 0.67);
								});

	            // Click event
	            $(this).click(function () {
	                // Show this thumbnail in the large frame.
	                showImage($(this).attr("id"));
	                return false;
	            });
	        });

	        // Connect up the javascript for each folder frame
	        $(".folderFrame").each(function (i) {
	            // Fade in the element as soon as possible
	            $(this).fadeIn("slow").fadeTo("slow", 0.67);

	            // Hook up mouse event handlers.
	            $(this).hover(
								function () {
								    $(this).fadeTo("fast", 1.0);
								},
								function () {
								    $(this).fadeTo("fast", 0.67);
								});

	            // Click event
	            $(this).click(function () {
	                // Load the next directory
	                var relativePath = $(this).find('a').attr('href');
	                loadThumbs(relativePath);
	                return false;
	            });
	        });

	    });
	});
		
	$("#_divPath").html(temp[1]);
}

// Show the new image
function showImage(imageDivId)
{
	// If there was a previously selected element
	//	then deselect it and fade it out a bit
	$(".imageFrameSelected").removeClass("imageFrameSelected").fadeTo("fast", 0.67);
	
	// Get the jQuery object for the new div
	var jqDiv = $("#" + imageDivId);
	
	// Fade the new picture in all the way and set
	//	it as selected.
	jqDiv.fadeTo("fast", 1.0).addClass("imageFrameSelected");
	
	// Gather information that has been embedded
	//	into the html elements.
	var jqElem = jqDiv.find('img');
	var thumbUrl = jqElem.attr('src');
	var temp = new Array();
	temp = thumbUrl.split('&');
	var imageUrl = temp[0];
	for(var i=1;i<temp.length;i++)
	{
		// 't=1' means show the thumbnail
		//	we want to remove this.
		if(temp[i]!='t=1')
		{
			imageUrl += '&' + temp[i];
		}
	}
	var imageName = jqElem.attr('alt');
	
	// Fade the current image out	
	$(".image").fadeOut("slow", function(){
		// Hook up the new image.
		$(this).attr("src", imageUrl).attr("alt", imageName);

		// Connect up the save link
		$("#_aSave").attr("href", imageUrl + "&d=1");
		
		// Get other info about this image.
		UpdateImageInfo(imageUrl);
	});
	
	// Prevent the postback click
	return false;
}


// Rotate image clockwise
function RotateCW()
{
	var imageUrl = $(".image").attr("src");
	imageUrl = imageUrl.replace(/\\/g,'/');
	var newTitle = $("#_title").val();
	$.ajax({
		type: "POST",
		url: "ServiceLayer.asmx/RotateCW",
		data: "{imageUrl:'" + imageUrl + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(msg){OnFailed(msg.d);},
		success: function(msg){OnSucceedAdmin(msg.d);}
	});
	return false;
}

// Rotate image counter-clockwise
function RotateCCW()
{
	var imageUrl = $(".image").attr("src");
	imageUrl = imageUrl.replace(/\\/g,'/');
	var newTitle = $("#_title").val();
	$.ajax({
		type: "POST",
		url: "ServiceLayer.asmx/RotateCCW",
		data: "{imageUrl:'" + imageUrl + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(msg){OnFailed(msg.d);},
		success: function(msg){OnSucceedAdmin(msg.d);}
	});
	return false;
}


// Set the image title
function SetTitle()
{
	var imageUrl = $(".image").attr("src");
	imageUrl = imageUrl.replace(/\\/g,'/');
	var newTitle = $("#_title").val();
	$.ajax({
		type: "POST",
		url: "ServiceLayer.asmx/SetTitle",
		data: "{imageUrl:'" + imageUrl + "',newTitle:'" + newTitle +"'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(msg){OnFailed(msg.d);},
		success: function(msg){OnSucceedAdmin(msg.d);}
	});
}


// Set image tags
function SetTags()
{
	var imageUrl = $(".image").attr("src");
	imageUrl = imageUrl.replace(/\\/g,'/');
	var newTags = $("#_tags").val();
	$.ajax({
		type: "POST",
		url: "ServiceLayer.asmx/SetTags",
		data: "{imageUrl:'" + imageUrl + "',newTags:'" + newTags +"'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(msg){OnFailed(msg.d);},
		success: function(msg){OnSucceedAdmin(msg.d);}
	});
}


// Update the image info
function UpdateImageInfo(imageUrl)
{
	imageUrl = imageUrl.replace(/\\/g,'/');
	$.ajax({
		type: "POST",
		url: "ServiceLayer.asmx/GetImageInfo",
		data: "{imageUrl:'" + imageUrl + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(msg){OnFailed(msg.d);},
		success: function(msg){OnSucceedAdmin(msg.d);}
	});
}


// Success callbacks
function OnSucceedAdmin(value)
{
	$("#_imageInfo").html(value);
	
	var temp = new Array();
	temp = value.split('[');
	if(temp.length==2)
	{
		// Show the image title
		var title = temp[0];
		title = title.substring(0, title.length - 1);
		$("#_title").attr("value", title);
				
		var rhs = temp[1];
		temp = rhs.split(']');
		if(temp.length==2)
		{
			// Show the image tags
			$("#_tags").attr("value", temp[0]);
		}
	}
	else
	{
		// No tags
		$("#_tags").attr("value", "");
		
		// Find the last '-'
		var i = value.lastIndexOf('-');
		var title = value.substring(0, i-1); // lose the space
		$("#_title").attr("value", title);
	}
}

// Fail callback
function OnFailed(error)
{
	alert(error.get_message());                                                      //having issues here for IE7
}

// ***************SLIDE SHOW FUNCTINS******************** //
var isPlaying = false;
var jsDivs = undefined;
var slideShowIndex = 0;

function Play()
{
	// Load all the thumb divs into an array
	jsDivs = $(".outerFrame div").not(".folderFrame");
	
	// Only do slide show if more than one slide exists.
	if(jsDivs.length > 1)
	{			
		// Set the starting index. Use the selected image
		//	if one has been selected.
		slideShowIndex = 0;
		for(var i=0;i<jsDivs.length;i++)
		{
			var className = jsDivs.eq(i).attr("class");
			if(className.indexOf("imageFrameSelected")!=-1)
			{
				slideShowIndex = i;
				break;
			}
		}
		
		// Swap the play and stop buttons.
		$("#_aPlay").hide();
		$("#_aStop").show();
		
		// Start the show.
		isPlaying = true;
		showNextSlide();
	}
	return false;
}

function Stop()
{
	// Swap the play and stop buttons.
	$("#_aPlay").show();
	$("#_aStop").hide();
	
	// Stop the show.
	isPlaying = false;
	return false;
}

function showNextSlide()
{
	if(isPlaying)
	{
		// Get the div for the next image
		var jsDiv = jsDivs.eq(slideShowIndex);
		
		// Increment the slide count...wrap
		//	around to the beginning if necessary
		slideShowIndex++;
		if(slideShowIndex>=jsDivs.length)
		{
			slideShowIndex = 0;
		}
		
		// Force the next image to be cached
		//	to speed up the transitions.
		var nextDiv = jsDivs.eq(slideShowIndex);
		var jqElem = nextDiv.find('img');
		var thumbUrl = jqElem.attr('src');
		var temp = new Array();
		temp = thumbUrl.split('&');
		var imageUrl = temp[0];
		for(var i=1;i<temp.length;i++)
		{
			if(temp[i]!='t=1')
			{
				imageUrl += '&' + temp[i];
			}
		}
		$("#_image2").attr("src", imageUrl);
		
		// Show the new image.
		showImage(jsDiv.attr("id"));
	}
}
