var tgProducts = tgProducts || {};
var previousSubContainer = '';
/**
 * Calls an array of asynchronous functions and calls the continuation
 * function when all are done.
 * @param {Array} functions Array of asynchronous functions, each taking
 *     one argument that is the continuation function that handles the result
 *     That is, each function is something like the following:
 *     function(continuation) {
 *       // compute result asynchronously
 *       continuation(result);
 *     }
 * @param {Function} continuation Function to call when all results are in.  It
 *     is pass an array of all results of all functions
 * @param {Object} opt_this Optional object used as "this" when calling each
 *     function
 */
tgProducts.callAsyncAndJoin = function(functions, continuation, opt_this) {
  var pending = functions.length;
  var results = [];
  for (var i = 0; i < functions.length; i++) {
    // we need a wrapper here because i changes and we need one index
    // variable per closure
    var wrapper = function(index) {
      functions[index].call(opt_this, function(result) {
        results[index] = result;
        if (--pending === 0) {
          continuation(results);
        }
      });
    };
    wrapper(i);
  }
};

/**
 * Class TGProduct
 */
tgProducts.TGProduct = function(params) {
  this.userPrefs_ = {};
  
  if (params) {
    for (var name in params)  if (params.hasOwnProperty(name)) {
      this[name] = params[name];
    }
  }
  
};

tgProducts.TGProduct.prototype.render = function(chrome) {
  if (chrome) {
    var tgProduct = this;
    this.getContent(function(content) {
	   if(tgProducts.container.view_ == 1) {
		  	$('<div class="tgProductView1"></div>').html(content).appendTo(chrome);
	   } else if(tgProducts.container.view_ == 2) {
		  	var tgProductArea = $('<div class="tgProductView2"></div>').html(content).appendTo(chrome);
			// Load product description from the server
			$(tgProductArea).find('span.productDescription').load("data/getProductDescription.aspx?region_id=" + regionId + "&sku=" + tgProduct.productId + "&max_text=450");
			// Link to Product Detail page
			$(tgProductArea).click(function(){
				window.location = ('product_details.aspx?sku=' + tgProduct.productId); 
			});
	   } else if(tgProducts.container.view_ == 3) {
		  	var tgProductArea = $('<div class="tgProductView3"></div>').html(content).appendTo(chrome);
			// Load product description from the server
			$(tgProductArea).find('span.productDescription').load("data/getProductDescription.aspx?region_id=" + regionId + "&sku=" + tgProduct.productId + "&max_text=450");
	   }
    });
  }
};

tgProducts.TGProduct.prototype.getContent = function(continuation) {
/*
	continuation is a function passed for manipulating results
	In this case, put results to some container
*/
  tgProducts.callAsyncAndJoin([
      this.getTitleBarContent, 
      this.getMainContent], function(results) {
        continuation(results.join(''));
      }, this);
};

tgProducts.TGProduct.prototype.getTitleBarContent = function(continuation) {
   if(tgProducts.container.view_ == 1) {
   	 continuation('');
   } else if(tgProducts.container.view_ == 2) {
	 continuation('');
   } else if(tgProducts.container.view_ == 3) {
   	 continuation('');
   }
};


tgProducts.TGProduct.prototype.getMainContent = function(continuation) {
	var subContainer = tgProducts.container.subContainers[tgProducts.container.selectedSubContainer];
	var html='';
	if(tgProducts.container.view_ == 1) {
		// View 1
		html += '<div id="tgProductContent" class="view1">';
		html += '  <div class="header">';
		//html += '  <div><span class="productCode">' + this.productId + ':' + this.entryDate.getMonth() + '/' + this.entryDate.getDate() + '/' + this.entryDate.getFullYear() + '</span>';
		html += '  <div><span class="productCode" >' + this.productId + '</span>';
		if(this.ecommerce && this.stock > 0){
			if(!subContainer.coupon){
				html +=	'   <br/><span class="price">' + currencySign + this.webPrice + '</span>';
			} else {
				html +=	'   <br/><span class="price"><s>' + currencySign + this.webPrice + '</s></span>';
				html += '	<span class="reducedPrice">' + currencySign + this.salePrice + '</span>';
			}
		} else if(this.displayPrice) {
			html +=	'   <br/><span class="price">' + currencySign + this.webPrice + '</span>';
		}
		html += '  </div>';
		html += ' </div>';
		html += ' <div class="section2">';
		if(admin){
			html += '	<a href="a_product_details.aspx?sku=' + this.productId + '"><img class="tgProductImage" src="' + this.imgThumb + '"></img></a>';
			//html += '   <a href="a_product_details.aspx?sku=' + this.productId + '" class="detailLink"><img src="images/productlist_magnifier.gif" alt="View Detail" /></a>';
		} else {
			//html += '	<a href="product_details.aspx?sku=' + this.productId + '"><img class="tgProductImage" src="' + this.imgThumb + '"></img></a>';
			html += '	<a href="product_details.aspx?sku=' + this.productId + '"><div class="image" name="' + this.imgThumb + '"></div></a>'			
			//html += '   <a href="product_details.aspx?sku=' + this.productId + '" class="detailLink"><img src="images/productlist_magnifier.gif" alt="View Detail" /></a>';		
		}
		html += ' </div>';
		html += ' <div class="productName">' + this.productName + '</div>';
		html += ' <div class="ecommerce">';
		if(this.ecommerce){
			if(this.stock > 0) {
				//'Stock: ' + this.stock + ' ::: ' + 
				html += '<a href="http://shop.targus.com/store/targusus/en_US/buy/productID.' + this.shoppingCartCode + '"><img src="images/button_buy_now.jpg" /></a>'
		html += '<br/><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link.asp?sku=' + this.productId + '" width="109" height="13" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe>';
			} else {
				//'Stock: ' + this.stock + ' ::: ' + 
					html += '<iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link_greybutton.asp?sku=' + this.productId + '" width="145" height="25" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe>';
			}
		} else {
			html += tgProducts.getShoppingCartCode(this.shoppingCartCode, this.productId);
		}
//		html += '<br/>bbb<iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link.asp?sku=' + this.productId + '" width="109" height="13" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe>';
		html += ' </div>';
		html += '</div>';
		continuation(html);
	} else if(tgProducts.container.view_ == 2) {
		// View 2
		html += '<div id="tgProductContent" class="view2">';
		html += '<div class="leftPanel"><a href="product_details.aspx?sku=' + this.productId + '"><img id="tgProductImage" src="' + this.imgThumb + '"></img></a></div>';
		html += '<div class="middlePanel">';
		html += '	<span class="productName">' + this.productName + '</span><br/>';
		html += '	<span class="productCode">' + this.productId + '</span><br/>';
		if(this.ecommerce && this.stock > 0){
			if(!subContainer.coupon){
				html +=	'   <span class="price">' + currencySign + this.webPrice + '</span>';
			} else {
				html +=	'   <span class="price"><s>' + currencySign + this.webPrice + '</s></span>';
				html += '	<span class="reducedPrice">' + currencySign + this.salePrice + '</span>';
			}
		} else if(this.displayPrice) {
			html +=	'   <span class="price">' + currencySign + this.webPrice + '</span>';	
		}
		if(this.ecommerce){
			//Added by Byrd 102809 : Add 'More Buying Option' button.			
			if(this.stock > 0) {
				html += '<div class="buynow"><a href="http://shop.targus.com/store/targusus/en_US/buy/productID.' + this.shoppingCartCode + '"><img src="images/button_buy_now.jpg" /></a><br /><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link.asp?sku=' + this.productId + '" width="109" height="13" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe></div>'
			} else {
					html += '<br /><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link_greybutton.asp?sku=' + this.productId + '" width="145" height="25" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe>';
			}
		} else {
			html += '<div class="buynow">' + tgProducts.getShoppingCartCode(this.shoppingCartCode, this.productId) + '</div>';
		}
//		html += '<div class="channel"><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link.asp?sku=' + this.productId + '" width="109" height="13" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe></div>';
		html += '</div>';
		html += '<div class="rightPanel">';
		html += '	<div class="productDescriptionHeader"></div>';
		html += '	<span class="productDescription"></span>';
		html += '</div>';
		html += '</div>';
		continuation(html);
	} else if(tgProducts.container.view_ == 3) {
		// View 3
		html += '<div id="tgProductContent" class="view3">';
		if(this.imgHighRes){
			html += '<div class="highResImage"><table><tr><td valign="middle" height="350"><a href="product_details.aspx?sku=' + this.productId + '"><img id="mainImg" src="http://imagedirectory.targus.com/resizeimage.asp?filename=' + this.imgHighRes + '.tif&constrain=height&size=350" border="0"/></a></td></tr></table></div>';
		} else {
			html += '<div class="imageThumb"><a href="product_details.aspx?sku=' + this.productId + '"><img id="tgProductImage" src="' + this.imgThumb + '" /></a></div>';
		}
		html += '	<div class="productName">' + this.productName + '</div>';
		html += '	<div class="productDetail"><div class="productDescriptionHeader">Description:</div><span class="productDescription"></span></div>';
		html += '	<div class="ecommerce">'
		html += '	<span class="productCode">' + this.productId + '</span><br/>';
		if(this.ecommerce && this.stock > 0){
			if(!subContainer.coupon){
				html +=	'   <span class="price">' + currencySign + this.webPrice + '</span>';
			} else {
				html +=	'   <span class="price"><s>' + currencySign + this.webPrice + '</s></span>';
				html += '	<span class="reducedPrice">' + currencySign + this.salePrice + '</span>';
			}
		} else if(this.displayPrice) {
			html +=	'   <span class="price">' + currencySign + this.webPrice + '</span>';	
		}
		if(this.ecommerce){
			//Added by Byrd 102809 : Add 'More Buying Option' button.
			if(this.stock > 0) {
				html += '<div class="buynow"><a href="http://shop.targus.com/store/targusus/en_US/buy/productID.' + this.shoppingCartCode + '"><img src="images/button_buy_now.jpg" /></a><br /><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link.asp?sku=' + this.productId + '" width="109" height="13" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe></div>'
			} else {
					html += '<br /><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link_greybutton.asp?sku=' + this.productId + '" width="145" height="25" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe>';
			}
		} else {
			html += '<div class="buynow">' + tgProducts.getShoppingCartCode(this.shoppingCartCode, this.productId) + '</div>';
		}
//		html += '<div class="channel"><iframe name="' + this.productId + '" id="' + this.productId + '" src="common/product-ci-link.asp?sku=' + this.productId + '" width="109" height="13" scrolling="no" frameborder="0" allowtransparency="true">Sorry, your browser doesn\'t support iframes.</iframe></div>';	
		html += '</div>';
		html += '<div class="leftarrow"><img src="images/product_view3_leftarrow_inactive.png" /></div>';
		html += '<div class="rightarrow"><img src="images/product_view3_rightarrow_inactive.png" /></div>';				
		html += '</div>';	
		continuation(html);
   }
	
};

/**
 * Class Container
 */
tgProducts.Container = function() {
  this.tgProducts_ = {};
  this.view_ = 1;
  this.nocache_ = 1;
  this.offset_ = 1;
  this.numTGProducts = 0;
  this.totalTGProducts = 0;
  this.selectedSortingMode = '3';
  // signed max int
  this.maxheight_ = 0x7FFFFFFF;
}

tgProducts.Container.prototype.tgProductClass = tgProducts.TGProduct;

tgProducts.Container.prototype.setNoCache = function(nocache) {
  this.nocache_ = nocache;
};

tgProducts.Container.prototype.setView = function(view) {
  this.view_ = view;
};

tgProducts.Container.prototype.setMaxHeight = function(maxheight) {
  this.maxheight_ = maxheight;
};

tgProducts.Container.prototype.getTGProductKey_ = function(instanceId) {
  return 'tgProduct_' + instanceId;
};

/*
tgProducts.Container.prototype.getTGProduct = function(instanceId) {
  return this.tgProducts_[this.getTGProductKey_(instanceId)];
};
*/

tgProducts.Container.prototype.createTGProduct = function(opt_params) {
  return new this.tgProductClass(opt_params);
};

tgProducts.Container.prototype.addTGProduct = function(tgProduct) {
  	this.numTGProducts++;
//  tgProduct.id = this.getNextTGProductInstanceId();
//  this.tgProducts_[this.getTGProductKey_(tgProduct.id)] = tgProduct;
	this.tgProducts_[tgProduct.productId] = tgProduct;
};

tgProducts.Container.prototype.addTGProducts = function(tgProducts) {
  for (var i = 0; i < tgProducts.length; i++) {
    this.addTGProduct(tgProducts[i]);
  }
};

tgProducts.Container.prototype.getTGProduct = function(offset){
	var subContainer = tgProducts.container.subContainers[this.selectedSubContainer];
	var itemCount = subContainer.itemCount;	
	switch(this.selectedSortingMode){
		// Alpha A-Z
		case '1':	tgProduct = this.tgProducts_[subContainer.itemListByName[(offset - 1)]];
					break;
		// Alpha Z-A
		case '2': 	tgProduct = this.tgProducts_[subContainer.itemListByName[itemCount - (offset - 1) - 1]];
					break;
		// Arrival Date
		case '3': 	tgProduct = this.tgProducts_[subContainer.itemListByDate[(offset - 1)]];
					break;
		// Price High to Low
		case '4': 	tgProduct = this.tgProducts_[subContainer.itemListByPrice[(offset - 1)]];
					break;
		// Price Low to High
		case '5': 	tgProduct = this.tgProducts_[subContainer.itemListByPrice[itemCount - (offset - 1) - 1]];
					break;
	}
	return tgProduct;
}

/**
 * Renders all tgProducts in the container.
 */
tgProducts.Container.prototype.renderTGProducts = function() {  
  var end_offset;
  var subContainer = tgProducts.container.subContainers[this.selectedSubContainer];
  var offset = subContainer.offset;
  var itemCount = subContainer.itemCount;
  var container = document.getElementById('' + tgProducts.container.selectedSubContainer + '-products-container');
  $('#' + this.selectedSubContainer + '-products-container').html('');
  if(this.view_ == 1) {
	  if(offset + (tgProducts.Container.prototype.view1_ItemsPerPage_ - 1) > itemCount) {
	  	end_offset = itemCount;
	  } else {
	    end_offset = offset + (tgProducts.Container.prototype.view1_ItemsPerPage_ - 1);
	  }
	  //alert(this.selectedSortingMode);

	  for (var i=offset; i<=end_offset; i++){	
	  
		var tgProduct = this.getTGProduct(i);
		
		if(tgProduct){
			this.renderTGProduct(tgProduct);
			if(i%3 != 0){ 
				$('<div class="tgProductView1Saperator"></div>').appendTo(container);
			} else {
				$('<br class="clearfloat" />').appendTo(container);
			}
		} else {
			//alert(subContainer.items['item-' + i]);
			//alert(tgProduct);
			//alert(subContainer.itemListByName[(i - 1)]);
		}
	  }
	  $('div.image').each(function(){
		var img_container = this;								   
		var img_src = $(this).attr('name');
		var img = new Image();
		$(img).load(function () {
			$(img_container).replaceWith(this);
		}).error(function () {
			$(img_container).replaceWith('<img src="images/image_na.png" />');
		}).attr('src', img_src);
	  });
	  $('#tgProductContent .photoLink').each(function(){
		$(this).click(function(){
			//window.open('http://www.targus.com/us/popup.asp?sku=' + $(this).attr('productId') + '&name=' + $(this).attr('productId'),'400x700','toolbar=yes,status=no,scrollbars=yes,location=no,menubar=no,directories=no,width=400,height=548');
			window.open('popup.aspx?sku=' + $(this).attr('productId') + '&name=' + $(this).attr('productId'),'400x700','toolbar=yes,status=no,scrollbars=yes,location=no,menubar=no,directories=no,width=400,height=548');
			//alert('test'); //Byrd
			return false;
		});
	  });
	  
	  //Dialog on hover
	  $('.tgProductView1').each(function(){
			var productDiv = this;
			$(productDiv).hover(
				function(e){
					$(this).addClass('tgProductView1Hover');
					$('#productDialog').remove();
					//tgDialog = setTimeout(function(){showDialog($(productDiv).position().left, $(productDiv).position().top)},1500);
					var loader = $('<div id="dialogLoader" class="dialogLoader"><img src="images/ajax-loader.gif" /></div>');
					loader.insertAfter(productDiv);
					loader.css("top",$(productDiv).position().top + 12).css("left",$(productDiv).position().left + 185);
					tgDialog = setTimeout(function(){												   
						var productCode = $(productDiv).find('span.productCode').text();
						var html = '<div id="productDialog" class="dialog">';
						html += '</div>';
						var dialog = $(html);
						tgProducts.getDialogContent(dialog,productCode);
						dialog.css('display','none');						
						dialog.css("top",$(productDiv).position().top - 100).css("left",$(productDiv).position().left - 150);
						dialog.insertAfter(productDiv);
						dialog.mouseleave(function(){
							dialog.remove();
						});
					},300);
					//alert('test'); //Byrd
					return false;
				},
				function(){
					$(this).removeClass('tgProductView1Hover');					
					$('#dialogLoader').remove();
					if(typeof(tgDialog) != 'undefined'){
						clearTimeout(tgDialog);
					}
					if(typeof(tgDialogDisplay) != 'undefined'){
						clearTimeout(tgDialogDisplay);
					}
					//alert('test'); //Byrd
					return false;
				}
	  		);								 
	  });
	  
  } else if(this.view_ == 2) {
	  if(offset + (tgProducts.Container.prototype.view1_ItemsPerPage_ - 1) > itemCount) {
	  	end_offset = itemCount;
	  } else {
	    end_offset = offset + (tgProducts.Container.prototype.view1_ItemsPerPage_ - 1);
	  }
	  //alert(this.selectedSortingMode);

	  for (var i=offset; i<=end_offset; i++){	
	  
		var tgProduct = this.getTGProduct(i);
		
		if(tgProduct){
			this.renderTGProduct(tgProduct);
		} else {
			//alert(tgProduct);
		}
	  }	  
	  $('#tgProductContent .photoLink').each(function(){
		$(this).click(function(){
			//window.open('http://www.targus.com/us/popup.asp?sku=' + $(this).attr('productId') + '&name=' + $(this).attr('productId'),'400x700','toolbar=yes,status=no,scrollbars=yes,location=no,menubar=no,directories=no,width=400,height=548');
			window.open('popup.aspx?sku=' + $(this).attr('productId') + '&name=' + $(this).attr('productId'),'400x700','toolbar=yes,status=no,scrollbars=yes,location=no,menubar=no,directories=no,width=400,height=548');
			//alert('test'); //Byrd
			return false;
		});
	  });	  

	  $('.tgProductView2').each(function(){
			var productDiv = this;
			$(productDiv).hover(
				function(e){
					$(this).addClass('tgProductView2Hover');
					//alert('test'); //Byrd
					return false;
				},
				function(){
					$(this).removeClass('tgProductView2Hover');					
				}
	  		);								 
	  });

	} else if(this.view_ == 3) {
		var tgProduct = this.getTGProduct(offset);
		if(tgProduct){
			this.renderTGProduct(tgProduct);
		} else {
			//alert(tgProduct);
		}
		//Preload next high resolution image
		if(offset < itemCount){		
			var nextTgProduct = this.getTGProduct(offset + 1);
			if(nextTgProduct){
				if(nextTgProduct.imgHighRes){
					var imgSrc = 'http://imagedirectory.targus.com/resizeimage.asp?filename=' + nextTgProduct.imgHighRes + '.tif&constrain=height&size=350';
					$('<img>').attr('src', imgSrc);
				}
			}
		}
		//Add effect and register event to the next button
		if(offset > 1) {
			$('.tgProductView3 .leftarrow img').click(
				function(){
					tgProducts.container.movePrevious();
				}		
			).hover(
				function(e){
					$(this).attr('src','images/product_view3_leftarrow_active.png');
				},
				function(){
					$(this).attr('src','images/product_view3_leftarrow_inactive.png');				
				}
			);
		} else {
			$('.tgProductView3 .leftarrow img').css('display','none');
		}
		//Add effect and register event to the back button		
		if(offset < itemCount){
			$('.tgProductView3 .rightarrow img').click(
				function(){
					tgProducts.container.moveNext();
				}
			).hover(
				function(e){
					$(this).attr('src','images/product_view3_rightarrow_active.png');
				},
				function(){
					$(this).attr('src','images/product_view3_rightarrow_inactive.png');				
				}
			);		
		} else {
			$('.tgProductView3 .rightarrow img').css('display','none');
		}
  }
  this.updateDisplayInfo();  
};

tgProducts.Container.prototype.renderTGProduct = function(tgProduct) {
  //var chrome = this.layoutManager.getTGProductChrome(tgProduct);
  //tgProduct.render(chrome);
  //alert('tgProduct=' + tgProduct);
  var container = document.getElementById('' + tgProducts.container.selectedSubContainer + '-products-container');

  tgProduct.render(container);
};

tgProducts.Container.prototype.nextTGProductInstanceId_ = 0;

tgProducts.Container.prototype.view1_ItemsPerPage_ = 12;

tgProducts.Container.prototype.view2_ItemsPerPage_ = 12;

tgProducts.Container.prototype.pageBuffer = 3;

tgProducts.Container.prototype.getNextTGProductInstanceId = function() {
  return this.nextTGProductInstanceId_++;
};

tgProducts.Container.prototype.movePrevious = function() {
  var subContainer = tgProducts.container.subContainers[this.selectedSubContainer];
  var itemCount = subContainer.itemCount;
  
  if(this.view_ == 1) {
  	if(subContainer.offset > this.view1_ItemsPerPage_) {
		subContainer.offset = subContainer.offset - this.view1_ItemsPerPage_;
	} else {
		subContainer.offset = 1;
	}
	$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
	tgProducts.container.renderTGProducts();
  } else if(this.view_ == 2) {
  	if(subContainer.offset > this.view2_ItemsPerPage_) {
		subContainer.offset = subContainer.offset - this.view2_ItemsPerPage_;
	} else {
		subContainer.offset = 1;
	}
	$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
	tgProducts.container.renderTGProducts();	
  } else if(this.view_ == 3) {
  	if(subContainer.offset > 1) {
		subContainer.offset--;
//		$('#' + tgProducts.container.selectedSubContainer + 'products-container > div:nth-child(1)').animate({opacity: "1", left: "+=242"}, "slow");			  
		  
//  		$('#' + tgProducts.container.selectedSubContainer + 'products-container > div:nth-child(2)').animate({opacity: "0", left: "+=242"}, "slow", function(){
			$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
			tgProducts.container.renderTGProducts();
//		});
	} else {
		this.offest_ = 1;
	}
  }
  return subContainer.offset;
};

tgProducts.Container.prototype.moveNext = function() {	
  var subContainer = tgProducts.container.subContainers[this.selectedSubContainer];
  var itemCount = subContainer.itemCount;
//  var offset = subContainer.offset;
  
//  alert(subContainer.id + ":" + itemCount + ":" + subContainer.offset);
  
  if(this.view_ == 1) {
  	if(subContainer.offset <= (itemCount - this.view1_ItemsPerPage_)) {
		subContainer.offset = subContainer.offset + this.view1_ItemsPerPage_;
		$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
		tgProducts.container.renderTGProducts();
	}
  } else if(this.view_ == 2) {
  	if(subContainer.offset <= (itemCount - this.view2_ItemsPerPage_)) {
		subContainer.offset = subContainer.offset + this.view2_ItemsPerPage_;
		$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
		tgProducts.container.renderTGProducts();		
	}
  } else if(this.view_ == 3) {	  
  	if(subContainer.offset < (itemCount)) {
		subContainer.offset = subContainer.offset + 1;
//		$('#' + tgProducts.container.selectedSubContainer + 'products-container > div:nth-child(2)').animate({opacity: "0", right: "+=242"}, 1000, "easeOutQuad");			  
		  
//  		$('#' + tgProducts.container.selectedSubContainer + 'products-container > div:nth-child(3)').animate({opacity: "1", right: "+=242"}, 1000, "easeOutQuad", function(){
		$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
		tgProducts.container.renderTGProducts();
//		});
	}
  }    
 
  return this.offset_;
};

tgProducts.Container.prototype.showView = function(view) {	
	if(view){
		this.setView(view);
	}
	$('#' + tgProducts.container.selectedSubContainer + '-products-container').html("");
	this.renderTGProducts();
	this.updateDisplayInfo();
};

tgProducts.Container.prototype.updateDisplayInfo = function(){
  	var subContainer = tgProducts.container.subContainers[this.selectedSubContainer];
  	var offset = subContainer.offset;
  	var itemCount = subContainer.itemCount;
	
	$('#totalRecords').text(this.totalTGProducts);
	$('#currentOffset').text(offset);
	$('#numRecords').text(itemCount);
	if(this.view_ == 1 || this.view_ == 2) {
		$('#recordResult').text("Showing " + this.getStartOffset() + " - " + this.getEndOffset() + " of " + itemCount);
		$('#recordResult_bottom').text("Showing " + this.getStartOffset() + " - " + this.getEndOffset() + " of " + itemCount);	
	} else {
		$('#recordResult').text("Showing Record " + this.getStartOffset() + " of " + itemCount);
		$('#recordResult_bottom').text("Showing Record " + this.getStartOffset() + " of " + itemCount);		
	}
	
	//Byrd
	//alert('test');
	//document.getElementById("dv_wait").style.visibility = "hidden";	
}

tgProducts.Container.prototype.getStartOffset = function() {	
  	var offset = tgProducts.container.subContainers[this.selectedSubContainer].offset;
	return offset;
};

tgProducts.Container.prototype.getEndOffset = function() {
  	var subContainer = tgProducts.container.subContainers[this.selectedSubContainer];
  	var offset = subContainer.offset;
  	var itemCount = subContainer.itemCount;
	if(this.view_ == 1) {
		offset += (this.view1_ItemsPerPage_ - 1);
	} else if(this.view_ ==2){
		offset += (this.view1_ItemsPerPage_ - 1);
	} else if(this.view_ ==3){
		offset += 0;	
	}
	return offset <= itemCount? offset : itemCount;
};

tgProducts.Container.prototype.setTotalTGProducts = function(numProducts){
	this.totalTGProducts = numProducts;
	this.pages = new Object();
	var pageSize = (this.view1_ItemsPerPage_ > this.view2_ItemsPerPage_ ? this.view1_ItemsPerPage_: this.view2_ItemsPerPage_);
	var numPages = numProducts/pageSize;
	if ((numPages * 10) % 10 < 5 && (numPages * 10) % 10 > 0) { 
		numPages = Math.round(numPages) + 1; 
	} else { 
		numPages = Math.round(numPages);
	}
	this.pages.numPages = numPages;
	for(i=1; i<=numPages; i++){
		this.pages["page" + i] = new Object();
		this.pages["page" + i].startIndex = ((i - 1) * pageSize) + 1;
		if(i * pageSize <= numProducts) {
			this.pages["page" + i].endIndex = i * pageSize;
		} else {
			this.pages["page" + i].endIndex = numProducts;
		}
		this.pages["page" + i].loaded = false;
	}

}

tgProducts.Container.prototype.determinePage = function(offset){
	offset = offset - 1;
	var pageSize = (this.view1_ItemsPerPage_ > this.view2_ItemsPerPage_ ? this.view1_ItemsPerPage_: this.view2_ItemsPerPage_);
	return (offset - (offset % pageSize))/pageSize + 1;
}

tgProducts.Container.prototype.initTabs = function() {
	$('#products-container').html('');
	$('#products-container').append('<div id="tabs"></div>');
	$('#tabs').append('<ul></ul>');

	var i=0;
	var subContainerList = new Array();
	for (var key in tgProducts.container.subContainers) {
		var subContainer = tgProducts.container.subContainers[key];
		subContainerList[i++] = subContainer;
  	}
	//Sort subContainers
	subContainerList.sort(function(a,b){
		//alert(a.displayOrder + 'vs' + b.displayOrder);
		return a.displayOrder - b.displayOrder;
	});
	for(i=0; i<subContainerList.length; i++){
		var subContainer = subContainerList[i];
		var key = 'subContainer-' + subContainer.id;
		if(i==0 || key==previousSubContainer){
			tgProducts.container.selectedSubContainer = key;
		}
    	$('#tabs > ul').append('<li><a href="#' + key + '">' + subContainer.name + '(' + subContainer.itemCount + ')</a></li>');		
		$('#tabs').append('<div id="' + key + '"><div id="'+ key + '-products-container" class="tgProductContainer"></div></div>');		
	}
	var tabs = $("#tabs").tabs();
	tabs.tabs('select', '#' + previousSubContainer);
	$('#tabs a').each(function(){
		$(this).click(function(){
			//change bucket type
			var subContainer = $(this).attr('href');
			subContainer = subContainer.substring(1,subContainer.length);
			previousSubContainer = subContainer;
			tgProducts.container.selectedSubContainer = subContainer;
			tgProducts.container.renderTGProducts();
			tgProducts.container.updateDisplayInfo();			
			return false;
		 });							   
	});
	// to make sure the underline will continue to the far right
/*
	$('#tabs > ul').append('<div style="float: right"></div>');
	
	$('#views').html('');
	$('#views').append('<div id="selectedview"></div>');
	
	$('#selectedview').append('Views: <a id="btn_view1" style="background-image: none;" href="#"><img class="noborder" src="images/productlist_view1.gif"/></a>&nbsp;<a id="btn_view2" href="#"><img class="noborder" src="images/productlist_view2.gif"/></a>&nbsp;<a id="btn_view3" href="#"><img class="noborder" src="images/productlist_view3.gif"/></a>');
*/

}

tgProducts.Container.prototype.initSortingLists = function() {
	//alert('y' + this.tgProducts_['RG0315C']);
	var tgProducts_temp = this.tgProducts_;
	//alert(this.tgProducts_['RG0315C']);
	for(var key in this.subContainers){
		var subContainer = this.subContainers[key];
		subContainer.itemListByDate.sort(function(a,b){
			if(typeof(tgProducts_temp[b])=='undefined'){alert(b);}
			return (tgProducts_temp[b].entryDate.getTime() - tgProducts_temp[a].entryDate.getTime());
		});
		subContainer.itemListByPrice.sort(function(a,b){
			var price_a = tgProducts_temp[a].webPrice;
			var price_b = tgProducts_temp[b].webPrice;
			if(! price_a){
				price_a = -99;
			}
			if(! price_b){
				price_b = -99;
			}
			return (price_b - price_a);
		});
	}
}

tgProducts.getShoppingCartCode = function(shoppingCartCode, productId){
	var html='';
	switch(shoppingCartCode){
		case '0':
			//Non-USA Products without Ecommerce
  			break;
		case '1':
			//Coming Soon
  			html += '<img src="images/button_coming_soon.jpg" alt="Coming Soon" />';
  			break;
		case '2':
			//Sold Out
  			html += '';
  			break;
		case '3':
			//Dell Models
  			html += '<a href="http://accessories.us.dell.com/sna/products/Carrying_Cases/productdetail.aspx?c=us&l=en&cs=19&sku=' + productId + '&ocoldqt=' + productId + '&oc=' + productId + '" target="_blank"><img src="images/button_shop_online_dell.jpg" border="0" alt="Buy Through Dell.com"></a>';
  			break;
		case '4':
			//cdProjects Products (Not Used)
  			html += '<a href="CDP_retail.asp"><img src="images/productlist_wheretobuy.gif" border="0" alt="Where To Buy">';
  			break;
		case '5':
			//Commercial/Bulk Models
  			html += '<img src="images/productlist_onlyforresale.gif" border="0" alt="Only For Resale" />';
  			break;
		case '6':
			//HP Models
  			html += '<a href="http://h30094.www3.hp.com/product.asp?mfg_partno='  + productId + '&&pagemode=ca"' + ' target="_blank"><img src="images/button_shop_online_hp.jpg" border="0" alt="Buy Through HP.com"></a>';
  			break;
		case '7':
			//Blank (Alliance Skus)
  			html += '';
  			break;
		case '8':
			//Built To Order (Contact Form)
  			html += '<a href="about_sales.asp"><img src="images/productlist_bto.gif" border="0"></a>';
  			break;				
		default:
			html += '';
	}
	return html;
}

tgProducts.getDialogContent = function(contentContainer, productId){
	$.ajax({
		type: "GET",
		url: "ui/getDialogContent.aspx?sku=" + productId,
		dataType: "html",
		success: function(html) {
			$(html).find('img').each(function(){
				//images preloader
				$('<img>').attr('src',$(this).attr('src'));
			});
			//fix ie6 issue
			html += $('#hiframe').html();
			$(contentContainer).html(html);
			tgDialogDisplay = setTimeout(function(){
				$('#dialogLoader').remove();
				$(contentContainer).css('display','block');
				$(contentContainer).mouseleave(function(){
					dialog.remove();
				});
			},1200);
		}
	}); //close $.ajax(	
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");

}

function showDialog(posX,posY){
	
	$('<div id="dialog" title="Dialog Title"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p></div>').dialog({
		autoOpen: false,
		width: 600, 
		closeOnEscape: true, 
		modal: true,
//		position: [(posY - 0),(posX - 0)]
		position: [(posX - 0),(posY - pageYOffset)]
	});
	$('#dialog').dialog('open');
	
	//alert('x=' + posX + ',y=' + (posY - pageYOffset));
	return false;
}

function refreshTabs(){
	tgProducts.container = new tgProducts.Container();
	tgProducts.init();				
}
	
function changeSortingMode(mode){
	tgProducts.container.selectedSortingMode = mode;
	
	for(var subContainer in tgProducts.container.subContainers) {
		tgProducts.container.subContainers[subContainer].offset = 1;
	}
	
	tgProducts.container.renderTGProducts();
}

/**
 * Default container.
 */
tgProducts.container = new tgProducts.Container();
//jQuery.easing.def = "easeOutBounce";
var k=0;

//GB_DV_WAIT.style.visibility = "visible";
//document.getElementById("dv_wait").style.visibility = "hidden";
