﻿function ProductCategoryClientCode(myLibraryDialog1) {
	var that					= this;
	var priceRanges				= null;
	var myLibraryDialog			= myLibraryDialog1;

	this.ShowAddToMyPortfolio = function(event) {
		var container = $(this).parents('.pwitem').eq(0);
		var productid = container.find('#objectBin').eq(0).text();

		myLibraryDialog.ShowDialog(productid);
	}

	this.UpdateSortArgs = function (val) {
		if (val == "dflt")
			newQuery = $.query.remove("sort").toString();
		else
			newQuery = $.query.set("sort", val).toString();

		this.ChangeUrlQueryArgs(newQuery);
	}

	this.UpdatePriceFilterArgs = function(key, minp, maxp) {
		var newQuery = $.query.set("pf", key).set("minp", minp).set("maxp", maxp).toString();
		this.ChangeUrlQueryArgs(newQuery);
	}
	
	this.UpdateColorFilterArgs = function(val) {
		var newQuery = $.query.set("cf", val).toString();
		this.ChangeUrlQueryArgs(newQuery);		
	}

	this.UpdateThemeFilterArgs = function(val) {
		var newQuery = $.query.set("tf", val).toString();
		this.ChangeUrlQueryArgs(newQuery);
	}

	this.ChangeUrlQueryArgs = function (newQuery) {

		var newUrl = document.location.protocol + "//" + document.location.host + document.location.pathname + newQuery;
		if (newUrl != document.location.href)
			document.location.href = newUrl;
	}
	
	function ctor() {
		$(".pwitem > .add").click(that.ShowAddToMyPortfolio);
	}
	ctor();
} /***** end ProductCategoryClientCode *****/

function MyLibraryDialog() {
	this.Dialog = new GenericLightBoxDialog("lightBox1", $("#add-product"));

	var _SP					= null; // storage provider
	var _currentKey			= null;
	var _callback			= null;
	var that				= this;
	
	function loadPortfolioChoices() {
		var ddl = $("#ddlPortFolio");
		var pList = _SP.GetPortfolioList();
		ddl.empty();
		for (k = 0; k < pList.length; k++) {
			ddl.append("<option value='" + pList[k].PortfolioId + "'>" + pList[k].PortfolioName + "</option>");
		}
	}

	this.ShowDialog = function(productKey) {
		_currentKey = productKey;
		this.Dialog.ShowDialog(true);
	}

	this.ShowDialogAndAddProofs = function(productKey, successCallBack) {
		_currentKey = productKey;
		_callback = successCallBack;
		this.Dialog.ShowDialog(true);
	}

	this.CloseDialog = function() {
		this.Dialog.CloseDialog();
	}

	this.ToggleCreateNew = function() {
		var e = $('#newPortfolioEntry');
		if (e.css("display") == "none")
			e.show(1, function() { that.Dialog.UpdateSize(); }).hide(5).slideDown(500);
		else {
			e.slideUp(500).hide(1, function() { that.Dialog.UpdateSize(); });
			$("#tbPortfolioName").get(0).value = "";
			$("#taPortfolioDescr").get(0).value = "";
		}
	}

	this.ProcessSubmit = function() {
		var portfolio = $("#ddlPortFolio").val();
		var newPortfolio = $("#tbPortfolioName").val();
		var newPortfolioDescr = $("#taPortfolioDescr").val();
		var libStats = null;

		if (newPortfolio && _currentKey) {
			libStats = _SP.CreateNewPortfolio(newPortfolio, newPortfolioDescr, _currentKey);
			loadPortfolioChoices();
		}
		else if (portfolio && _currentKey) {
			libStats = _SP.AddToPortfolio(portfolio, _currentKey);
		}

		$("#tbPortfolioName").val("");
		$("#taPortfolioDescr").val("");

		this.Dialog.CloseDialog();
		loadPortfolioChoices();
		MyLibBanner.Update(libStats);

		if (libStats && _callback)
			_callback(); // invoke successful submit callback 
	}

	function ctor() {

		_SP = new MyLibraryStorage();
		loadPortfolioChoices();
	}
	ctor();

	function MyLibraryStorage() {
		var that = this;
		var COOKIE_KEY = "MyLibraryPortfoliosIdInfo";
		var anonymousId = null;
		var serverWasAuthenticated = false;
		var cookieWasEverAuthenticated = false;

		MyLibraryStorage.ERR_SERVER_CONNECTION = " : Server connection error";
		MyLibraryStorage.ERR_ACCESS_DENIED = " : Access denied, ensure that you are authenticated.";
		MyLibraryStorage.ERR_SESSION_EXPIRED = " : Your authenticated session has expired please re-login.";
		MyLibraryStorage.ERR_SERVER_DATA_ERROR = " : Server connection error";

		this.GetPortfolioList = function() {
			var output = null;
			var params = "{}"; 
			doSynchronousAjax('CorpMarketsService.asmx'
							, 'GetPortfoliosForUser', function(data) { output = data; }, params);

			if (output && output.d)
				return output.d;
			else
				return null; // displayErrorMessage(MyLibraryStorage.ERR_SERVER_DATA_ERROR);
		}

		this.CreateNewPortfolio = function(newPortfolio, newPortfolioDescr, productKey) {
			var output = null;
			var params = "{name: " + prepareAjaxParamString(newPortfolio)
								   + ", description: " + prepareAjaxParamString(newPortfolioDescr)
								   + ", productId: " + prepareAjaxParamString(productKey)
 								   + "}"; // ,
			doSynchronousAjax('CorpMarketsService.asmx'
							, 'CreateNewPortfolio', function(data) { output = data; }, params);

			if (output && output.d)
				return output.d;  //parseInt(output.d);
			else
				return false; // displayErrorMessage(MyLibraryStorage.ERR_SERVER_DATA_ERROR);

		}

		this.AddToPortfolio = function(portfolioId, productKey, currentLogoId, proofImages) {
			var output = null;
			var params = "{ portFolioId: " + portfolioId
										   + ", productId: " + prepareAjaxParamString(productKey)
										   + "}"; // ,
			doSynchronousAjax('CorpMarketsService.asmx'
							, 'AddProductToPortFolio', function(data) { output = data; }, params);

			if (output && output.d)
				return output.d;  //Boolean(output.d);
			else
				return false;  //displayErrorMessage(MyLibraryStorage.ERR_SERVER_DATA_ERROR);
		}
		
		function ctor() {
		}
		ctor();
	}
} /***** end MyLibraryDialog *****/

function MyLibBanner() { }

MyLibBanner.LoadControl = function() {
	var obj = $("#quick-cart > li > .viewProdLibrary");
		obj.removeAttr("href");
		
		obj.click(function() {
			obj = $("#no-portfolios");
			obj2 = $("#quick-cart");
			obj.css("top", obj2.position().top + obj2.height() + 4);
			obj.css("left", obj2.position().left);
			obj.slideDown("normal");
			obj.click(function() { $(this).slideUp("normal"); });
			
		});	
}

MyLibBanner.Update = function(libStats) {
	if (libStats) {
		var items = $("#quick-cart > .port, #quick-cart > .prod");
		items.hide();
		$("#quick-cart > .prod > span").text(libStats.ProductCount);
		$("#quick-cart > .port > span").text(libStats.PortfolioCount);

		items.animate({ "height": "toggle" }, "slow");

		if (libStats.PortfolioCount > 0) {
			$("#quick-cart > li > a").unbind().attr("href", $("#quick-cart > li > .templink").attr("href"));
		}
		else {
			var location = window.location.protocol + '//' + window.location.host + '/products/' 
			window.location = location;
		}
	}
}

function ProductProofDialog(onCloseCallBack) {
	this.Dialog = new GenericLightBoxDialog("lightBox2", $("#add-logo"));
	var _currentKey = null;
	var that = this;
	var _addedHandler = false;
	var _callBack = onCloseCallBack;
	var _noLogoPath = "/resources/images/backgrounds/noLogo.png";
	var _defaultProductImage = "about:blank";


	this.ShowDialog = function(productKey) {
		if (!_addedHandler) {
			$("#cppframeUpload").load(that.LogoChangedHandler);
			_addedHandler = true;
		}

		_currentKey = productKey;
		$("#cppframeUpload").get(0).src = "/CustomPages/IframeLogoUpload.aspx?product=" + _currentKey;  //$.query.get('product');
		this.Dialog.ShowDialog(true);
	}

	this.CloseDialog = function() {
		this.Dialog.CloseDialog();
		if (_callBack)
			_callBack();
	}

	this.LogoChangedHandler = function() {

		var iframe = $("#cppframeUpload").get(0);
		var impMethodContainer = $("#cppImprintTechnique > .section-type");
		if (iframe && iframe.contentWindow && iframe.contentWindow.hasLogo()) {

			var logoUrl = iframe.contentWindow.getCurrentLogoUrl(120, 72);
			var proofUrl = iframe.contentWindow.getInitialProofImagePath(338, 345);
			var proofsUrlList = iframe.contentWindow.getProofImageUrlList();
			

			if (logoUrl) {
				$("#uploadedLogoEdit > div > img").attr("src", logoUrl);
				$("#removeLogo").show();

			}
			if (proofUrl) {
				$("#cppAddLogo").find(".section-img").find("img").attr("src", proofUrl);
				$("#cppImprintTechnique > .section-img > img").attr("src", proofUrl).show();
			}

			impMethodContainer.empty();
			if (proofsUrlList && proofsUrlList.Items) {
				$(proofsUrlList.Items).each(
					function(i) {
						impMethodContainer.append
						(
							"<div class=\"imprintType\"" + (i==0? " active" : "")  + "><img src=\""
							+ this.Url + "&wid=142&hei=144" + "\" /><br /><span>"
							+ this.Name + "</span><span id=\"spLargeUrl\" style='display: none;'>"
							+ this.Url + "&wid=338&hei=345" + "</span></div>"
						);
					}
				);
				
				impMethodContainer.append('<div class="clear">&nbsp;</div>');
				
				impMethodContainer.find(".imprintType").click(
					function() {
						var obj = this;

						$("#cppImprintTechnique > .section-type > div").removeClass("active");
						$(obj).toggleClass("active");

						var url = $(obj).find("#spLargeUrl").text();
						$("#cppImprintTechnique > .section-img > img").attr("src", url);
					}
				);

			}
			else {
				impMethodContainer.append("<label>We Apologize for the inconvenience, this product is not available for personalization at this time.</label>");
			}
		}
		else {
			impMethodContainer.empty();
			impMethodContainer.append("<label>This feature requires that you upload a logo first.</label>");
		}
	}

	this.RemoveCurrentLogo = function() {
		var iframe = $("#cppframeUpload").get(0);

		$("#removeLogo").hide();
		$("#removeLogoInproc").show();

		if (iframe.contentWindow.removeCurrentLogo()) {

			var impMethodContainer = $("#cppImprintTechnique > .section-type");


			$("#uploadedLogoEdit > div > img").attr("src", _noLogoPath);
			$(".section-img > img").attr("src", _defaultProductImage);

			$("#removeLogoInproc").hide();
			
			
			impMethodContainer.empty();
			impMethodContainer.append("<label>This feature requires that you upload a logo first.</label>");
			$("#cppImprintTechnique > .section-img > img").attr("src", "about:blank").hide();


		}
	}

	this.SendEmail = function() {
		var emailTo = $("#emailTo").val();
		var subject = $("#emailSubject").val();
		var body = $("#emailBody").val();


		var iframe = $("#cppframeUpload").get(0);
		var proofsUrlList = iframe.contentWindow.getProofImageUrlList();

		if (!iframe.contentWindow.hasLogo()) {
			setEmailStatusMsg("This feature requires a logo to be uploaded first.", false);
			return;
		}


		if (!proofsUrlList || !proofsUrlList.Items || proofsUrlList.Items.length == 0) {
			setEmailStatusMsg("Unable to send. This product has no available customizable views.", false);
			return;
		}


		if (isMultipleEmailAddressValid(emailTo)) {
			setEmailStatusMsg('sending... <img src="/resources/images/loadingAnimation.gif" height="13px" width="208px" />');

			var output = null;
			var params = "{emailTo: " + prepareAjaxParamString(emailTo)
										   + ", emailSubject: " + prepareAjaxParamString(subject)
										   + ", userBody: " + prepareAjaxParamString(body)
										   + ", proofImageUrls: " + json2string(proofsUrlList.Items)
 										   + "}"; // ,
			doSynchronousAjax('CorpMarketsService.asmx'
									, 'SendProductProofEmail', function(data) { output = data; }, params);

			if (output && output.d)
				setEmailStatusMsg("Thank you. An email with your personalized product link has been sent. Please contact us at 800.243.4066. For more information on our products or how to purchase.", true);
			else
				setEmailStatusMsg("Unable to send email.", false);
		}
		else
			setEmailStatusMsg("The to email address is not valid", false);
	}

	function setEmailStatusMsg(msg, success) {

		var status = $("#emailStatus");

		status.html(msg);
		
		if (success && (success == false))
			status.css("color", "#b10034");		
	}



	function ctor() {
		$("#add-logo > .closebtn").click(function() { that.CloseDialog(); });
		$("#uploadedLogoEdit > #removeLogo").click(function() { that.RemoveCurrentLogo(); });
		$('#sendLogoSample > #emailSend').click(function() { that.SendEmail(); });
		_defaultProductImage = $(".section-img > img").attr("src");

		$("#tabs > .tab").click(function() {

			// switch tab
			$("#tabs > .tab").removeClass("active");
			$(this).toggleClass("active");

			// switch content
			var selId = this.id.replace(/t_/, "");
			$("#cppAddLogo, #cppImprintTechnique, #cppSendLogo").removeClass("show");
			$("#" + selId).toggleClass("show");

		});		
	}
	ctor();
}