﻿function MyLibrary(thumbWidth, thumbHeight, mainWidth, mainHeight) {
	var that = this;
	var _thumbWidth = thumbWidth;
	var _thumbHeight = thumbHeight;
	var _mainWidth = mainWidth;
	var _mainHeight = mainHeight;
	var _selectedProduct;
	var _selectedProductDiv;
	var _txtPrice;
	var _txtComments;
	var _isDirty;
	var _selectedPort;
	var _btnSave;
	
	this.LoadControl = function() {
		that._txtPrice = $('#txtPrice');
		that._txtComments = $('#txtComments');
		
		that._txtPrice.keyup(function(e) { 
			if(e.which == 13) {
				if(that._isDirty) {
					that._btnSave.click();
				}
			}
			else {
				if(that._txtPrice.val() != undefined && that._txtPrice.val().length > 0) 
					setIsDirty(true); 
			}
		});
		that._txtComments.keyup(function(e) { if(that._txtComments.val() != undefined && that._txtComments.val().length > 0) setIsDirty(true); });
		
		that._btnSave = $('#saveItemOptions');
		that._btnSave.bind('click', function () {updateProduct();});
		
		// Need to auto-set the height of the frame based on the internal contents.
		$('#info-lib-frame').load(function() { $(this).height($(this).contents().find('body').height() + 50);});
		
		getPortfolios();
	}
	
	this.LoadAltImages = function() {
		getAltImages();
	}
	
	this.GetSelectedProduct = function() {
		return that._selectedProduct;
	}
	
	function getPortfolios() {
		setIsDirty(false);
		doAjax('CorpMarketsService.asmx', 'GetPortfolios', function(data) {loadPortfolios(data.d);});
	}

	function getPortfolioCount() {
		return $('#portfolio-items').children('.item').length;
	}
	
	function getProductCount() {
		return $('#library-products-content').children('.item').length;
	}
	
	function loadPortfolios(data) {
		var items = $('#portfolio-items');
		var item; 
		
		items.empty();
		
		if(data.length == 0) {
			$('#portfolio-none').show();
			that._selectedPort = undefined;
		}
		else {
			$('#portfolio-none').hide();
			for(var i=0;i<data.length;i++) {
				if(i == 0) {
					that._selectedPort = data[i];
					item = createPortItem(data[i], false);
				}
				else {
					item = createPortItem(data[i], false);
				}
					
				items.append(item);
			}
		}
		
		// showPortfolio();
	}
		
	// Shows a portfolio when it's edit button is clicked.
	function showPortfolio() {
		$('#library-products-content').parent().slideDown(300);

		if (that._selectedPort && that._selectedPort.PortfolioId) {
			doSynchronousAjax('CorpMarketsService.asmx', 'GetPortfolioProducts', function(data) { 
				loadPortfolioProducts(data); 
				$('#library-products-header').html(that._selectedPort.PortfolioName + ' (' + data.d.length + ')');
			}, "{portfolioId:" + that._selectedPort.PortfolioId + "}");
		}
		else {
			var list = $('#library-products-content');
			list.empty();
			$('#library-products-header').html('');
		}
		
		$(".library > #tertiary").hide();
		$(".library > #secondary").show();
		
		return false;
	}
	
	function delPortfolioCallback(stats, portfolioId) {
		 if(stats.d) {
			if(that._selectedPort.PortfolioId == portfolioId || getPortfolioCount() == 0) 
				getPortfolios();
			else
				div.remove();
				
			MyLibBanner.Update(stats.d);
		}
	}
	
	function delPortfolio(portfolioId) {
		doSynchronousAjax('CorpMarketsService.asmx', 'DeletePortfolio', function(stats) { delPortfolioCallback(stats, portfolioId); }, "{portfolioId:" + portfolioId + "}");
	}
	
	function delProductCallback(stats) {
		if(stats.d) {
			if(getProductCount() == 0) 
				delPortfolio(that._selectedPort.PortfolioId);
			else
				MyLibBanner.Update(stats.d);
		}
	}
	
	function delProduct(portfolioProductId) {
		doSynchronousAjax('CorpMarketsService.asmx', 'DeletePortfolioProduct', function(stats) { delProductCallback(stats); }, "{portfolioProductId:" + portfolioProductId + "}");
	}
	
	// Gets a products alternate images form the server
	function getAltImages() {
		doAjax('CatalogService.asmx', 'GetProductAlternateImages', function(data) {loadAltImages(data.d);}, "{productId:'" + that._selectedProduct.ProductId + "', thumbWidth: " + _thumbWidth +", thumbHeight: " + _thumbHeight + ", mainWidth: " + _mainWidth + ", mainHeight: " + _mainHeight + "}");
	}
	
	// Gets a product from the server
	function getProduct() {
		doSynchronousAjax('CatalogService.asmx', 'GetProduct', function(data) {loadProductDisplay(data.d);}, "{productId:'" + that._selectedProduct.ProductId + "'}");
	}
	
	// Sends product updates to the server
	function updateProduct() {
		if(that._isDirty) {
			that._selectedProduct.Price = that._txtPrice.val();
			that._selectedProduct.Comments = that._txtComments.val();
			
			var jsonData = "{portfolioProductId:'" + that._selectedProduct.PortfolioProductId + 
							"', price: '" + that._selectedProduct.Price + 
							"', comments: '" + that._selectedProduct.Comments + 
							"', customImageUrl: '" + that._selectedProduct.ImageUrl + "'}";
							
			doAjax('CorpMarketsService.asmx', 'SavePortfolioProduct', function(data) { 
				that._selectedProduct.Price = data.d;
				that._selectedProductDiv.find('.price').text(data.d);
				that._txtPrice.val(data.d);}, jsonData);
				
			setIsDirty(false);
		}	
	}
	
	function renamePortfolio(portfolioId, name) {
		doSynchronousAjax('CorpMarketsService.asmx', 'RenamePortfolio', null, "{portfolioId:" + portfolioId + ", name: '" + name + "'}");
	}
	
	function cpiBubbleEvent(p) {
		return that._selectedPort.PortfolioId == p.PortfolioId ? true : false;
	}
	
	function createPortItem(p, selected) {
		var div = $('<div></div>');
		var h4 = $('<h4>' + p.PortfolioName + '</h4>');
		var txt = $('<input class="editPortName" type="text" value="' +  p.PortfolioName + '"/>');
		var del = $('<a href="#" class="delete">delete</a>');
		var edit = $('<a href="#" class="edit">edit</a>');
		var save = $('<a href="#" class="edit" style="display:none;">save</a>');
		
		// bind events
		save.bind('click', function() { p.PortfolioName = txt.val(), h4.text(p.PortfolioName); renamePortfolio(p.PortfolioId, p.PortfolioName); txt.hide(); h4.show(); save.hide(); edit.show(); del.show(); return cpiBubbleEvent(p);});
		edit.bind('click', function() {h4.hide(); txt.show(); txt.focus(); save.show(); edit.hide(); del.hide(); return false; });
		del.bind('click', function() {
			var conf = confirm("You are about to delete the portfolio named '" + p.PortfolioName + "'. Are you sure?");
			if(conf == 1) 
				delPortfolio(p.PortfolioId);
			
			return false;
		}); 
		div.bind('click', function() {toggleClass(div, 'div', 'selected'); that._selectedPort = p; div.addClass('selected'); showPortfolio(); return false;});
	
		// append items
		div.append(h4);
		div.append(txt); 
		div.append(save); 
		div.append(del);	
		div.append(edit);
		
		if(selected)
			div.addClass('selected');
		
		return div;	
	}
	
	function createAltImage(alt, index) {
		var rdoId = "rdo" + that._selectedProduct.ProductId + index;
		var img = $('<img src="/Resources/Images/loadingAnimation.gif" width="' + _thumbWidth + '" />');
		var label = $('<label for="' + rdoId + '"></label>');	
		var item = $('<div class="item"></div>');
		var rdo = $('<br /><input id="' + rdoId + '" type="radio" style="vertical-align: middle;" name="rdoAltImg" value="' + alt.ThumbNailUrl + '" />');
	
		(function(src) { img.one('load', function() {this.src = src; }); })(alt.ThumbNailUrl);
		
		// Bind click event to the radio button. This event saves the change to the database.
		rdo.bind('change', function() {
			that._selectedProduct.ImageUrl = this.value;
			toggleClass($(this).parent(), 'div', 'selected');
			if(this.checked) 
				that._isDirty = true; // NOTE: Bypass the normal setIsDirty() method because we don't want the save changes button to show.
				that._selectedProductDiv.children('img').attr('src',this.value);
				updateProduct();
			});
	
		label.append(img);
		item.append(label);	
		item.append(rdo);
		item.append('<span>use this image</span>');
		
		if(that._selectedProduct.ImageUrl == alt.ThumbNailUrl)
			rdo.change();
			
		return item;
	}
	
	// Loads the selected product's alternate images
	function loadAltImages(data) {
		var imgDiv = $('#images-container');
		imgDiv.empty();
		
		if(data.length > 0) {
			$('#lblChgImg').show();
			
			for(var i=0;i<data.length;i++) 
				imgDiv.append(createAltImage(data[i], i));
		}
		else {
			$('#lblChgImg').hide();
		}
	}
	
	function delProductFn(p, item) {
		var conf = confirm('Are you sure?');
		
		if(conf == 1) {
			item.remove();
			delProduct(p.PortfolioProductId);
		}
	}
	
	function selectProductFn(div, pp) {
		toggleClass(div, 'div', 'selected');
		selectProduct(pp, div); 
		setIsDirty(false);
	}
	
	function createPortfolioProduct(pp) {
		var newItem = $('<div class="item"><h4>' + pp.DisplayName + '</h4><img src="' + pp.ImageUrl + '&wid=' + _mainWidth + '&hei=' + _mainHeight + '"></div>');
		var opt = $('<div class="option"></div>');
		var del = $('<a href="#">delete</a>');
		var price = $('<span class="price">' + pp.Price + '</span>');
		
		opt.append(del);
		opt.append(price);
		newItem.append(opt);
		
		del.click(function() { delProductFn(pp, newItem); return false; } );
		newItem.click(function() { selectProductFn($(this), pp); return false;});
		
		return newItem;
	}
	
	// Loads portfolio images in the left panel.
	function loadPortfolioProducts(data) {
		var list = $('#library-products-content');
		list.empty();
		
		for(var i=0;i<data.d.length;i++) {
			var newItem = createPortfolioProduct(data.d[i]);
			list.append(newItem);
			
			if(i == 0) 
				newItem.click();
		}	
		
		list.append('<div class="clear"> </div>');
	}

	// Selects the product (used by bindEvent).
	function selectProduct(pp, div) {
		that._selectedProduct = pp;
		that._selectedProductDiv = div;
		getProduct();
		getAltImages();
	}
	
	// Loads the product details section
	function loadProductDisplay(p) {
		var prodDiv = $('#info-lib');
		
		that._txtPrice.val(that._selectedProduct.Price == null ? '' : that._selectedProduct.Price);
		that._txtComments.val(that._selectedProduct.Comments == null ? '' : that._selectedProduct.Comments);
					
		prodDiv.children('.style').html('style: ' + p.Style == null ? '' : p.Style);
		prodDiv.children('.name').html(p.DisplayName);
		prodDiv.children('.sku').html(p.ProductId);
		prodDiv.children('.msrp').html('msrp: ' + p.FormattedPrice);
		
		if(p.Size == null) 
			prodDiv.children('.size').hide();
		else
			prodDiv.children('.size').html('size: ' + p.Size);
			
		loadProductDetails(p);

		$('#info-lib-frame').attr('src', '/custompages/LibraryImprintData.aspx?ProductId=' + p.ProductId);

		if (p.IsProofable)
			$("#addLogo").show();
		else
			$("#addLogo").hide();
	}
	
	function loadProductDetails(p) {
		var ul = $('#info-lib-details');
		ul.empty();
		for(var i=0;i<p.Details.length;i++)
			ul.append('<li>' + p.Details[i] + '</li>');
	}
					
	function setIsDirty(isDirty) {
		that._isDirty = isDirty;
		
		if(that._isDirty)
			that._btnSave.show();
		else
			that._btnSave.hide();
	}
	
	function toggleClass(item, selector, css) {
		item.siblings(selector).removeClass(css);
		item.addClass(css);
	}
}