var scrollLoop;

$.ajaxSetup( {
		url: "http://www.i2iart.com/lib.php"
	} );
	

function setupSplash()
{
	// Set splash div to correct width
	$('#splash_scroll').css( "width", ( $('#splash_scroll > div').size() * 960 ) + "px" );
	
	// Start auto scrolling
	scrollLoop = setTimeout( "autoScroll();", 6000 );
}

function autoScroll()
{
	// Check if at end
	var width = $('#splash_scroll').css( "width" );
	width = width.substr( 0, width.length-2 );
	var left = $('#splash_scroll').css( "left" );
	left = left.substr( 0, left.length-2 );
	if( ( left * -1 ) == ( width - 960 ) )
	{
		// Move all divs behind the last one
		var divs = $('#splash_scroll div:not(#splash_scroll div:last-child)').detach();
		$('#splash_scroll').append( divs );
		
		// Reset Scroll position
		$('#splash_scroll').css( "left", 0 );
	}

	$('#splash_scroll').animate( { left: "-=960" }, 1000 );
	scrollLoop = setTimeout( "autoScroll();", 6000 );
}

function searchImages( type )
{
	// Clear search results/msg
	$('#searchResults').html( "" );
	$('#searchMessage').html( "" );
	
	var keywords = $('#keywords').val().toLowerCase();
	if( keywords != "" )
	{
		keywords = keywords.split( " " );
	}
	var artist = $('#artist').val();
	var imageNum = $('#imageNum').val();
		
	$('#searchMessage').html( "Searching..." );

	$.ajax( {
		dataType: "json",
		data: ({ method: "search", type: type, keywords: keywords, artist: artist, imageNum: imageNum }),
		success: function( data ) {
			// Check for error messages
			if( data.error )
			{
				$('#searchMessage').html( data.error );
				return;
			}
			
			// Update result message
			var string = " results.";
			if( data.resultNum == 1 )
			{
				string = " result.";
			}

			$('#searchMessage').html( "Your search returned " + data.resultNum + string );
			
			for( var i in data )
			{
				// Skip result number record
				if( i == "resultNum" )
				{
					continue;
				}
			
				var image = data[i];
				
				// Create div and hide it
				var div = document.createElement( 'div' );
				$(div).addClass( 'image_thumb' );
				div.onclick = new Function ("popupImage( "+image.id+", '"+type+"' );");
				$(div).hide();
				
				// Add image to div
				var html = "<img src='http://www.i2iart.com/images/"+image.artist_id+"/"+image.thumbnail+"' alt='"+image.name+"' id='search_"+image.id+"' />";
				html += "<br />"+image.code;
				$(div).html( html );
				
				// Add div to page and fade it in
				$('#searchResults').append( div );
				$("#search_"+image.id).load( function() {
					$(this).parent().fadeIn( 'slow' );
				} );
			}		
		},
		error: function() {
			$('#searchMessage').html( "Search failed." );
		}
	} );
}

function popupImage( id, type )
{
	$.ajax( {
		dataType: "json",
		data: ({ method: "loadImage", id: id }),
		success: function( image ) {
			var html = "Unable to load image.";
			if( image != null )
			{
				// Load either flash or image
				if( image.path.search(/.swf/i) != -1 )
				{
					html = "<object codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' width='100%' height='100%' align='middle'>";
					html += "<param name='allowScriptAccess' value='sameDomain'>";
					html += "<param name='movie' value='http://www.i2iart.com/images/"+image.artist_id+"/"+image.path+"'>";
					html += "<param name='quality' value='high'>";
					html += "<param name='wmode' value='opaque' />";
					html += "<embed src='http://www.i2iart.com/images/"+image.artist_id+"/"+image.path+"' quality='high' wmode='opaque' width='100%' height='100%' name='"+image.name+"' align='middle' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'>";
					html += "</object>";
				}
				else
				{
					html = "<img src='http://www.i2iart.com/images/"+image.artist_id+"/"+image.path+"' alt='"+image.name+"' title='"+image.name+"' id='stockLargeImage' />";
				}
				
				// Check for null last name
				var artistName = image.fname + " " + image.lname;
				if( image.lname == null )
				{
					artistName = image.fname
				}
				
				html += "<div class='image_details_"+type+"'><span class='image_details_num'>"+image.code+"</span> <span class='image_details_title'>"+image.name+"</span> <span class='image_details_title'>"+image.description+"</span> <span class='image_details_artist'>"+artistName+"</span></div>";
			}
			$('#popupImage').html( html );
			
			$('#fade').fadeTo( "slow", 0.6 );
			if( image.path.search(/.swf/i) != -1 )
			{	
				$('#popupImageHolder').fadeIn( "slow" );
			}
			else
			{
				$('#stockLargeImage').load( function() {
					$('#popupImageHolder').fadeIn( "slow" );
				} );
			}
		},
		error: function() {
			$('#popupImage').html( "Unable to load image." );
		}
	} );
}

function openPopup( element )
{
	$('#fade').fadeTo( "slow", 0.6 );
	$('#'+element).fadeIn( 'slow' );
}

function closePopup()
{
	$('#fade').fadeOut( 'slow' );
	$('.popup').fadeOut( 'slow' );
}

function loadImage( id, num )
{
	$('#largeImage').html( "Loading..." );
	$('#largeImageDesc').html( "" );
	
	$.ajax( {
		dataType: "json",
		data: ({ method: "loadImage", id: id }),
		success: function( image ) {
			if( image == null )
			{
				$('#largeImage').html( "Image not found." );
				return;
			}
			
			// Load either flash or image
			if( image.path.search(/.swf/i) != -1 )
			{
				$('#largeImage').width( "100%" );
				$('#largeImage').height( "100%" );
				var html = "<object id='largeImageFlash' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'  width='100%' height='100%'  align='middle'>";
				html += "<param name='allowScriptAccess' value='sameDomain'>";
				html += "<param name='movie' value='http://www.i2iart.com/images/"+image.artist_id+"/"+image.path+"'>";
				html += "<param name='quality' value='high'>";
				html += "<param name='wmode' value='opaque' />";
				html += "<embed src='http://www.i2iart.com/images/"+image.artist_id+"/"+image.path+"' quality='high'  width='100%' height='100%' wmode='opaque' name='largeImageFlash' align='middle' swliveconnect='true' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'>";
				html += "</object>";
				$('#largeImage').html( html );
			}
			else
			{
				// Reset these to default
				$('#largeImage').width( "auto" );
				$('#largeImage').height( "auto" );
				
				// Hide large image, update it, then fade it in
				$('#largeImage').hide();
				var html = "<img src='http://www.i2iart.com/images/"+image.artist_id+"/"+image.path+"' alt='"+image.name+"' title='"+image.name+"' />";
				$('#largeImage').html( html );
				$('#largeImage > img').load( function() {
					$('#largeImage').fadeIn( "slow" );
				} );
			}
			
			// Set click event for prev/next arrows
			$('#left_arrow').get(0).onclick = new Function( "prevImage( "+image.id+" );" );
			$('#right_arrow').get(0).onclick = new Function( "nextImage( "+image.id+" );" );
			
			$('#largeImageDesc').html( "("+num+") "+image.code+" <span id='largeImageTitle'>"+image.name+"</span>" + image.description );
		},
		error: function() {
			$('#largeImage').html( "Image not found." );
		}
	} );
}

function loadArtist( id )
{
	$.ajax( {
		dataType: "json",
		data: ({ method: "loadArtist", id: id }),
		success: function( artist ) {
			if( !artist )
			{
				loadLink( "index.php" );
				return;
			}
			
			// Load images
			loadArtistPortfolio( artist.id );
			
			// Check for null last name
			var artistName = artist.fname + " " + artist.lname;
			if( artist.lname == null )
			{
				artistName = artist.fname
			}
			
			// Set page title
			document.title = artistName + " | i2i Art Inc. Artist Representation";
			
			$('#artistImage').attr( "src", "http://www.i2iart.com/images/artists/"+artist.photo );
			$('#artistImage').attr( "alt", artistName + " Image" );
			$('#artistName').html( artistName );
			
			// Create short bio with MORE link
			var shortBio = artist.bio.substr( 0, 135 );
			shortBio += "...<br /><a href=\"#\" onclick=\"openPopup( 'fullBioHolder' ); return false;\">MORE...</a>";
			$('#artistBio').html( shortBio );
			$('#fullBio').html( artist.bio );			
			
			// Parse links
			var html = "";
			if( artist.weblinks != null && artist.weblinks != "" )
			{
				var links = artist.weblinks.split( "," );
				for( var i = 0; i < links.length; i++ )
				{
					link = links[i].split( " - " );
					html += "<li><a href='"+link[0]+"' target='_blank'>"+link[1]+"</a></li>";
				}
			}
			$('#artistLinksList').html( html );
			
			loadArtistBlogLinks( artist.initials );
		},
		error: function() {
			$('#artistName').html( "Artist not found." );
		}
	} );
}

function loadArtistBlogLinks( initials )
{	
	$.ajax( {
		url: "http://www.i2iart.com/lib_blog.php",
		dataType: "text",
		data: ({ method: "loadArtistBlogLinks", initials: initials }),
		success: function( html ) {
			$('#artistLinksBlog').html( html );
		},
		error: function() {
			$('#artistLinksBlog').html( "Failed to load blog links." );
		}
	} );
}

function setupArtistImageScroll( labels, totalWidth, widths )
{
	var productWidth = totalWidth - 687;

	$('#slider').slider( { 
		animate: true,
		min: 0, 
		max: productWidth, 
		slide: function( ev, ui ) {
			// Only update css if sliding handle (a), otherwise clicking on bar will not animate
			if( $(ev.originalTarget).is( "a" ) )
			{
				$('#portfolioImages').css( 'left', '-' + ui.value + 'px' );
			}
		},
		change: function( ev, ui ) {
			$('#portfolioImages').animate( { 'left' : '-' + ui.value + 'px' }, 500, 'linear' );
		}
	} );
	
	// Since scroller does not fill the whole scroll image, bind click events to holding div
	$('#portfolioSlider').click( function( e ) {
		var posx;
		if( !e ) var e = window.event;
		
		if( e.layerX )
		{
			posx = e.layerX
		}
		else
		{
			var offset = $('#portfolioSlider').offset();
			posx = e.clientX - offset.left;
		}
		
		if( posx < 100 )
		{
			if( posx < 21 ) // Left arrow button
			{
				var value = $("#slider").slider( "value" ) - 200;
				if( value < 0 ) value = 0;

				$("#slider").slider( "value", value );
			}
			else // Scroll bar left side
			{
				$("#slider").slider( "value", 0 );
			}
		}
		else
		{
			if( posx > 614 ) // Right arrow button
			{
				var size = $("#slider").slider( "option", "max" );
				var value = $("#slider").slider( "value" ) + 200;
				if( value > size ) value = size;

				$("#slider").slider( "value", value );
			}
			else // Scroll bar right side
			{
				$("#slider").slider( "value", $("#slider").slider( "option", "max" ) );
			}
		}
	} );
	
	// Add portfolio labels
	var labelsHTML = "";
	for( var i = 1; i < labels.length; i++ )
	{	
		// Scale to fit scroll bar (which is 502px wide)
		var width = widths[i-1];
		width = Math.round( ( width / totalWidth ) * 502 );
		
		// Shift left 65px to account for small slider width (362px), if first label
		if( i == 1 )
		{
			width -= 65;
		}
		else // Shift left to account for the word 'portfolio'
		{
			width -= 60;
		}
		
		// If portfolio label is blank, add &nbsp to keep spacing correct
		if( labels[i] == "" )
		{
			labels[i] = "&nbsp";
		}
		else // Add word Portfolio
		{
			labels[i] = "Portfolio " + labels[i];
		}
		
		labelsHTML += "<span style='margin-left: "+width+"px;'>"+labels[i]+"</span>";
	}
	$('#slider').append( labelsHTML );
}

function loadArtistPortfolio( id )
{
	$.ajax( {
		dataType: "json",
		data: ({ method: "loadArtistPortfolio", id: id }),
		success: function( data ) {
			var imagesHTML = "";
			var curLabel = -1;
			var curWidth = 0;
			var totalWidth = 0;
			var count = 0;
			var labels = new Array();
			var widths = new Array();
			for( var i in data )
			{
				var image = data[i];
				count++;
				
				// If new label, create label with correct width and start new
				if( curLabel != image.portfolio )
				{
					// Save label and width
					labels.push( curLabel );
					widths.push( curWidth );
					totalWidth += curWidth;
					
					// Reset with new label/width
					curWidth = image.width + 4;
					
					// Add divider if not first portfolio
					if( curLabel != -1 )
					{
						imagesHTML += "<div class='divider'><img src='http://www.i2iart.com/images/divider.png' alt='Divider' /></div>";
						curWidth += 48;
					}
					
					curLabel = image.portfolio;
				}
				else // Add to width (include 4px margin)
				{
					curWidth += image.width + 4;
				}
				
				// Add image
				imagesHTML += "<div id='image_"+image.id+"' onclick='loadImage("+image.id+", "+count+"); return false;' >";
				imagesHTML += "<img src='http://www.i2iart.com/images/"+image.artist_id+"/"+image.thumbnail+"' alt='"+image.name+"' title='"+image.name+"' />";
				imagesHTML += "<span class='portNum'>"+count+"</span></div>";
			}
			// Save last label/width
			labels.push( curLabel );
			widths.push( curWidth );
			totalWidth += curWidth;
			
			// Update html
			$('#portfolioImages').html( imagesHTML );
			setupArtistImageScroll( labels, totalWidth, widths );
			
			// Load either the specified image or a random one
			if( $('#image_id').val() != null && $('#image_id').val() != "" )
			{
				var loadID = $('#image_id').val();
				$('#image_'+loadID).click();
			}
			else
			{
				var random = Math.floor( Math.random() * $('#portfolioImages div').length );
				$('#portfolioImages div').eq( random ).click();
			}		
		},
		error: function() {
			$('#portfolioImages').html( "Failed to load images." );
			$('#portfolioSlider').hide();
		}
	} );
}

function loadPortfolio()
{	
	$.ajax( {
		dataType: "json",
		data: ({ method: "loadPortfolio" }),
		success: function( data ) {
			if( data.error )
			{
				$('#portfolioGrid').html( data.error );
				return;
			}
			
			for( var i in data )
			{
				var artist = data[i];
				
				// Create div and hide it
				var div = document.createElement( 'div' );
				$(div).addClass( 'grid_thumb' );
				div.onclick = new Function ("loadLink( '"+artist.link+"' );");
				$(div).hide();
				
				// Add image to div
				var html = "<img src='"+artist.image+"' alt='"+artist.name+"' id='artist_"+i+"' />";
				
				// Add status if neccessary
				if( artist.status != "" )
				{
					html += "<div class='status'>"+artist.status+"</div>";
				}
				else
				{
					html += "<br />";
				}
				html += artist.name;
				$(div).html( html );
				
				// Add div to page and fade it in
				$('#portfolioGrid').append( div );
				$("#artist_"+i).load( function() {
					$(this).parent().fadeIn( 'slow' );
				} );
			}		
		},
		error: function() {
			$('#portfolioGrid').html( "Unable to load artists." );
		}
	} );
}

function loadLink( link )
{
	window.location.assign( link );
}

function siteSearchFocus()
{
	$('#search').val( "" );
}

function siteSearchBlur()
{
	if( $('#search').val() == "" )
	{
		$('#search').val( "Search" );
	}
}

function siteSearch()
{
	var search = $('#search').val();
	
	if( search == "" )
	{
		return;
	}
	
	loadLink( "http://www.i2iart.com/search.php?search="+search.toLowerCase() );
}

function loadResultsNum()
{
	var string = " results.";
	if( $('#resultsNum').val() == 1 )
	{
		string = " result.";
	}

	$('#searchMessage').html( "Your search for '" + decodeURI( location.search.substring( 8 ) ) + "' returned " + $('#resultsNum').val() + string );
}

function nextImage( id )
{
	if( $('#image_'+id).next().hasClass( "divider" ) )
	{
		$('#image_'+id).next().next().click();
	}
	else
	{
		$('#image_'+id).next().click();
	}
}

function prevImage( id )
{
	if( $('#image_'+id).prev().hasClass( "divider" ) )
	{
		$('#image_'+id).prev().prev().click();
	}
	else
	{
		$('#image_'+id).prev().click();
	}
}

