// gallery.js

function gbl(prop) {
	switch (prop) {
		case "LOADING_BAR": return '/vendor/'+VENDOR_DIR+'/images/config_load_bar.gif';	
	}
}

var images = new Array();
var __currentImage = -1;
var __currentPage = 1;
var __imagesPerPage = 8;		// based on Tom's new design
var aSwatch = [{}];				// simulating the configurator, because the scene7 zoom viewer in scene7funcs_common.js uses this array
var aCollection = [{}];			// simulating the configurator, because the scene7 zoom viewer in scene7funcs_common.js uses this array
var s7GalleryPrefix = 'http://s7d5.scene7.com/is/image/LevolorOnline/gallery_lv_';


function initGallery() {
	updateImages();
}

function clearImages() {
	__currentImage = -1;
	__currentPage = 1;
	images = new Array();
	$("div[id=thumbs]").html('<img src="'+gbl('LOADING_BAR')+'" border="0" style="width:220px;height:19px;margin-left:15px;margin-top:40px;" />');
	$("span[id=gallery_counters]").attr("style", "display:none");
}

function addImage(elem) {
	var img = {
		id: 					$(elem).attr('id'),
		name: 					$(elem).attr('model'),
		model_id: 				$(elem).attr('model_id'),
		blindshadetype:			$(elem).attr('blindshadetype'),
		color: 					$(elem).attr('swatch'),
		swatch_id: 				$(elem).attr('swatch_id'),
		swatch_oekey: 			$(elem).attr('swatch_oekey'),
		swatch_img: 			$(elem).attr('swatch_img'),
		swatch_thumb: 			$(elem).attr('swatch_thumb'),
		category_id:			$(elem).attr('category_id'),
		category: 				$(elem).attr('category'),
		category_rewrite: 		$(elem).attr('category_rewrite'),
		swatch_browsing: 		$(elem).attr('swatch_browsing'), 
		swatch_ordering: 		$(elem).attr('swatch_ordering'), 
		configure_print: 		$(elem).attr('configure_print'), 
		configure_order: 		$(elem).attr('configure_order'),
		collection_name:		$(elem).attr('collection_name'),
		coord_collection:		$(elem).attr('coord_collection'),
		coord_color:			$(elem).attr('coord_swatch'),
		coord_name:				$(elem).attr('coord_name')
	};
    var index = images.length;
    images[images.length] = img;
}

function updateArrows() {
	$("a[id=previous_arrow]").attr("style", "display:"+(__currentImage<=0 ? "none" : "inline"));
	$("a[id=next_arrow]").attr("style", "display:"+(__currentImage>=0 && images.length-1!=__currentImage || __currentImage<=0 && images.length>1 ? "inline" : "none"));
}	
function prevImage() {
	if (__currentImage > 0)
		showImage(__currentImage - 1);
	return false;
}
function nextImage() {
	if (__currentImage < images.length - 1 && __currentImage >= 0)
		showImage(__currentImage + 1);
	return false;
}

function prevPage() {
	if (__currentPage > 1) {
		__currentPage--;
		// since the page changed, we're going to show the last image on the previous page (remembering that image indexes are 0-based)
		// this will also call refreshThumbsDisplay
		showImage((__currentPage * __imagesPerPage) - 1);
	}
}
function nextPage() {
	var numPages = Math.floor(images.length/__imagesPerPage) + 1;
	if (__currentPage < numPages) {
		__currentPage++;
		// since the page changed, we're going to show the first image on the next page (remembering that image indexes are 0-based)
		// this will also call refreshThumbsDisplay
		showImage((__currentPage-1) * __imagesPerPage);
	}
}
function refreshThumbsDisplay() {
	var numPages = Math.floor(images.length/__imagesPerPage) + 1,
		startImageIndex = (__currentPage-1) * __imagesPerPage,
		endImageIndex = Math.min(images.length, __currentPage * __imagesPerPage) - 1,
		index, img, html
	
	$("div[id=thumbs]").html('');
	if (images.length == 0) {
		$("div[id=thumbs]").html('Sorry, no photos are available for the above selections.');
		$("span[id=gallery_counters]").hide();
	} else {
		for (index=startImageIndex; index<=endImageIndex; index++) {
			img = images[index];
			//$("div[id=thumbs]").append('<img src="'+PRODUCT_IMAGES_URL+'/gallery/thumb/'+img['id']+'.jpg" id="thumb'+index+'" onclick="showImage('+index+');" height="50" width="70" border="0" alt="" />');
			// TOM's changes for LEVOLOR-83 (6/25 comment)
			html = '<div class="thumb' + (index == __currentImage ? ' selected' : '') + '" id="thumb' + index + '" onclick="showImage('+index+');">';
			//html += '<img class="color" src="'+PRODUCT_IMAGES_URL+'/gallery/thumb/color/'+img['id']+'.jpg" />';
			//html += '<img class="gray" src="'+PRODUCT_IMAGES_URL+'/gallery/thumb/gray/'+img['id']+'.jpg" />';
			html += '<img class="color" src="' + s7GalleryPrefix + img['id'] + '_thumb" />';
			html += '<img class="gray" src="' + s7GalleryPrefix + img['id'] + '_thumb?op_saturation=-100" />';
			html += '</div>';
			$("div[id=thumbs]").append(html);
		}
		$("span[id=gallery_total]").html(images.length);
		$("span[id=gallery_counters]").attr("style", "display:inline");
	}
	
	$("div.thumb-nav a").removeClass("dead");
	if (__currentPage <= 1) {
		$("div.thumb-nav a.up").addClass("dead");
	}
	if (__currentPage >= numPages) {
		$("div.thumb-nav a.down").addClass("dead");
	}
}
// add events to the up/down thumb page navigation
$("div.thumb-nav a.up:not(.dead)").live('click', prevPage);
$("div.thumb-nav a.down:not(.dead)").live('click', nextPage);

function updateImages() {
	var pid = $("select[name=product]").val();
	if (!pid) pid = MODEL_CAT_ID;
	var rid = $("select[name=room]").val();
	var bstype = $("select[name=blindshadetype]").val();

	if (!pid || !rid) { return; }

	clearImages();

	$.ajax({
		url: '/ideas/gallery-list.php?type=getimages&pid='+escape(pid)+'&rid='+escape(rid)+'&bstype='+escape(bstype),
		type: 'POST',
		dataType: 'xml',
		timeout: 15000,
		error: function(robj, etype, eobj) {
		},
		success: function(xml) {
			__currentPage = 1;	// reset the page to the first page
			images = new Array(); // clear the images array.
			$(xml).find('image').each(function() {
				addImage($(this)); // add each image that was returned.
			});
			updateArrows();
			refreshThumbsDisplay();
			if (__currentImage < 0) 
				showImage(0); // show initial image
		}
	});
}

function updateRooms() {
	var pid = $("select[id=product]").val();

	if (!pid) { return; }

	$.ajax({
		url: '/ideas/gallery-list.php?type=getrooms&pid='+escape(pid),
		type: 'POST',
		dataType: 'xml',
		timeout: 15000,
		error: function(robj, etype, eobj) {
		},
		success: function(xml) {
			current_value = $("select[id=room]").val();
			$("select[id=room]").empty(); // empty all options
			$("select[id=room]").append('<option value="none">All</option>');
			idx=1;
			keep_selected = 0;
			$(xml).find('room').each(function() {
				$("select[id=room]").append('<option value="'+$(this).attr('id')+'">'+$(this).attr('name')+'</option>');
				if ($(this).attr('id') == current_value) {
					keep_selected = idx;	
				}
				idx++;
			});
			document.getElementById('room').selectedIndex = keep_selected;	// can't use jQuery here b/c of a bug
			updateImages();
		}
	});
}

function updateProducts() {
	var rid = $("select[id=room]").val();

	if (!rid) { return; }

	$.ajax({
		url: '/ideas/gallery-list.php?type=getproducts&rid='+escape(rid),
		type: 'POST',
		dataType: 'xml',
		timeout: 15000,
		error: function(robj, etype, eobj) {
		},
		success: function(xml) {
			
			current_value = $("select[id=product]").val();
			$("select[id=product]").empty(); // empty all options
			$("select[id=product]").append('<option value="none">All</option>');
			idx=1;
			keep_selected = 0;
			$(xml).find('product').each(function() {
				$("select[id=product]").append('<option value="'+$(this).attr('id')+'">'+$(this).attr('name')+'</option>');
				idd = $(this).attr('id');
				if ($(this).attr('id') == current_value) {
					keep_selected = idx;
				}
				idx++;
			});
			if (document.getElementById('product'))
				document.getElementById('product').selectedIndex = keep_selected;  // can't use jQuery here b/c of a bug
			updateImages();
		}
	});
}


function simulateConfigurator(image) {
	// this function builds the aSwatch and aCollection array with a single element each
	// this is to simulate the zoom viewer dialog popup (scene7funcs_common.js, orderswatches.js, _configurator.js, orderswatches_typedefs.js, typedefs.js)
	// which is tightly coupled with the configurator environment and expects these certain things to be defined
	// we will give it what it needs to operate
	var swatch, collection,
		catPath = image.category_rewrite;
	aSwatch = [{
		text: image.color,
		oekey: image.swatch_oekey,
		s7AssetId: (catPath ? catPath + '_' + image.swatch_oekey : null),
		s7thumb: (catPath ? s7.swatchThumbnail.urlPrefix + catPath + '_' + image.swatch_oekey + s7.swatchThumbnail.urlSuffix : PRODUCT_IMAGES_URL+'/swatches/' + images[index].swatch_thumb)
	}];
	aCollection = [{
		collectionname: image.collection_name
	}];
}


function showImage(index) {
	var releasecover = false;

	if (index < 0) 								index = 0;
	if (index >= images.length) 				index = images.length - 1;
	if (index == __currentImage)  				return;
    if (__currentImage == -1 && index >= 0) 	releasecover = true;
   
	__currentImage = index;
	__currentPage = Math.floor(__currentImage/__imagesPerPage) + 1;
	refreshThumbsDisplay();
	simulateConfigurator(images[index]);
    
	$("span[id=swatch_link]").hide();
	$("span[id=config_link]").hide();
	$(".swatch-border .number").html('');
	
	// Replace the previous image with the loader bar.
   	$('img.gallery_loading_bar').remove();
	$('#main_image').hide().after('<img class="gallery_loading_bar" border="0" src="' + gbl('LOADING_BAR') + '" style="margin-top:180px;margin-left:200px;" />');
	/*
	$("div[id=info]").html('<h2>'+images[index].name+'</h2>'+
							'<strong>type:</strong> '+images[index].category+'<br/>'+
							'<strong>color:</strong> '+images[index].color+'<br/>'+
							(images[index].blindshadetype ? '<strong>blind & shade type:</strong> '+images[index].blindshadetype : ''));
	*/
	// 5/19/11/kdh - Changing this according to Tom's specs in LEVOLOR-83
	$("#gallery-image h1:eq(0)").html(images[index].name);
	
	var productInfo = '<div style="width: 300px; position: absolute; bottom: 10px; left: 10px;overlap: hidden;">' +
	  				  '<span class="color" style="font-size: 17px; margin-bottom: 2px;">'+images[index].name+'</span>' +
	  				  '<span class="color" style="margin-left: 10px; font-size: 13px;">Color: '+images[index].color+'</span>' +
	  				  '<span class="color" style="margin-left: 10px; font-size: 13px">Collection: '+images[index].collection_name+'</span></div><div style="width: 184px; position: absolute; bottom: 7px; left: 325px; font-size: 10px; overlap: hidden;">'; 
	  				  
	if(images[index].coord_name){
		productInfo +=   '<span class="color" style="font-size: 11px; "><b>Accent Window</b></span>';
		productInfo +=   '<span class="color" style="font-size: 11px;">Product: '+images[index].coord_name+'</span>';
		if(images[index].coord_color){
			productInfo +=   '<span class="color" style="font-size: 11px;">Color: '+images[index].coord_color+'</span>';
		}
		if(images[index].coord_collection){
			productInfo +=   '<span class="color" style="font-size: 11px;">Collection: '+images[index].coord_collection+'</span></div>';
		}
	}
	
	$("div[id=info]").html(productInfo);
	$("#infoHeader").html(images[index].category);
	


    var mimg = new Image();
    mimg.onload = function() { 
    	$('img.gallery_loading_bar').remove();
    	$('#main_image').attr("src", mimg.src).show();
		$(".swatch-border a").attr("swatchAssetId", aSwatch[0].s7AssetId);
		if (images[index].swatch_ordering == '1') {
			$("img[id=swatch_corner]").attr('src','/images/product_corner_maroon.gif');
			$("img[id=swatch_corner]").attr('width',90);
			$("img[id=swatch_corner]").attr('height',90);
			$("span[id=swatch_link]").show();
			$("a[id=swatch_href]").attr('href','/products/'+images[index].category_rewrite+'/colors.php?mcid='+images[index].category_id);
		}
		else if (images[index].swatch_browsing == '1') {
			$("img[id=swatch_corner]").attr('src','/images/product_corner_browse.gif');
			$("img[id=swatch_corner]").attr('width',120);
			$("img[id=swatch_corner]").attr('height',120);
			$("span[id=swatch_link]").show();
			$("a[id=swatch_href]").attr('href','/products/'+images[index].category_rewrite+'/colors.php?mcid='+images[index].category_id);
		}
		if (images[index].configure_order == '1') {
			$("span[id=config_link]").show();
			$("a[id=config_href]").attr('href','/store/configurator.php?mid='+images[index].model_id);
		}
	}
	//mimg.src = PRODUCT_IMAGES_URL+'/gallery/full/' + images[index].id + '.jpg';
    mimg.src = s7GalleryPrefix + images[index].id + '?$gallery_lv$';
	$(".swatch-border img").attr("src", aSwatch[0].s7thumb);
	$(".swatch-border .number").html(images[index].swatch_oekey);
	$(".swatch-border").show();
	$("span[id=gallery_index]").html(index+1);
	updateArrows();
}



/*
 * Listeners for the magnify buttons to open the s7 flyout viewer
 * These listeners were copied from orderswatches.js and configurator.js
 */
// watch the hovers on the swatches so we can show their magnify link
$("div.swatch-border").live('mouseenter', function() {
	$(this).find('a.magnify').show();
}).live('mouseleave', function() {
	$(this).find('a.magnify').hide();
});

var zoomDiv;
$("a.magnify").live('click', function(e) {
	e.preventDefault();
	s7.showZoomDialog(this);
	return false;
});



// LEVOLOR-132:  We're changing the way the loading bar is displayed so it isn't stretched
// since there are a billion gallery.tpl.php files that each draw the initial loading bar image,
// we're just going to start out by hiding it so that the rest of the event code above can
// take care of the real display
$(function() {
	$('#main_image').hide();
});



