﻿Type.registerNamespace("Finatica");
Type.registerNamespace("Finatica.CompanyCard");
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Finatica.CompanyCard.joinCompany = function() {
	position = $.trim(prompt("Введите вашу позицию в этой компании"));
	if (position == null || position.length == 0)
		return;

	var joinCompanyServiceProxy = new Finatica.WebServices.CompanyHelper();
	joinCompanyServiceProxy.JoinCompany(Finatica.CompanyCard.companyID, true, position, Finatica.CompanyCard.OnJoinSucceeded, Finatica.CompanyCard.OnJoinFailed);
}

Finatica.CompanyCard.OnJoinSucceeded = function(result, userContext, methodName) {
	if (methodName == "JoinCompany") {
		$('#' + Finatica.CompanyCard.divInfEmployeeID).show();
		$("#" + Finatica.CompanyCard.lbJoinID).hide();
		$find(Finatica.Common.NotificatorID).addMessage('success', 'Вы успешно присоединились к компании');
	}
	if (methodName == "SendEmployeeEmailConfirmation") {
		$find(Finatica.Common.NotificatorID).addMessage('success', 'Активационная ссылка отправлена');
	}
	if (methodName == "UnJoinCompany") {
		$('#' + Finatica.CompanyCard.divInfNotApprovedEmployeeID).hide();
		$('#' + Finatica.CompanyCard.divInfEmployeeID).hide();
		$('#' + Finatica.CompanyCard.lbJoinID).show();
		
		$find(Finatica.Common.NotificatorID).addMessage('alert', 'Вы вышли из числа сотрудников компании. Все предложения, опубликованные от имени этой компании, были перенесены в архив');
	}
}

Finatica.CompanyCard.OnJoinFailed = function(result, userContext, methodName) {
	if (methodName == "JoinCompany") {
		$find(Finatica.Common.NotificatorID).addMessage('error', "Ошибка возникла при попытке присоединиться к компании!");
	}
	if (methodName == "SendEmployeeEmailConfirmation") {
		$find(Finatica.Common.NotificatorID).addMessage('error', 'Активационная ссылка не отправлена');
	}
}

Finatica.CompanyCard.SendConfirmationLink = function() {
	var joinCompanyServiceProxy = new Finatica.WebServices.CompanyHelper();
	joinCompanyServiceProxy.SendEmployeeEmailConfirmation(Finatica.CompanyCard.companyID, Finatica.CompanyCard.OnJoinSucceeded, Finatica.CompanyCard.OnJoinFailed);
}

Finatica.CompanyCard.UnJoinCompany = function() {
	if (!confirm("Вы уверены, что хотите выйти из компании?"))
		return;
	var joinCompanyServiceProxy = new Finatica.WebServices.CompanyHelper();
	joinCompanyServiceProxy.UnJoinCompany(Finatica.CompanyCard.companyID, Finatica.CompanyCard.OnJoinSucceeded, Finatica.CompanyCard.OnJoinFailed);
}

Finatica.CompanyCard.firstTime = true;

Finatica.CompanyCard.openGoodsCategories = function(categoryID) {
	
	var dict = $find(Finatica.CompanyCard.finMD);

	if (Finatica.CompanyCard.firstTime == true) {
		$("a").not('[href^=java]').not('[href=#]').not(":contains('select')")
			.not(".rlbButton").not(".dictionaryopen").bind("click", function() { return confirm("Вы уверены, что хотите покинуть страницу, не сохранив изменения?"); });
			
		dict.add_opened(function(sender) {
			if (sender.currentDictionary == "Goods") {
				$("#" + sender.popupDivID).find("input[type=button]#btnFilter").click();
			}			
		});

		dict.add_opening(function() {
			$find(Finatica.CompanyCard.finMD).selectedValues.Sectors2 = JSON.parse($('#' + Finatica.CompanyCard.hdnFixedSectorsID).val()).Sectors2;
		});

		dict.currentDictionary = "Goods";
		dict.add_closing(function(sender) {
			$("div#" + sender.popupDivID + "> div.d-header > ul.tabs > li > a > input[type=hidden][value=Goods]").parent().click();
		});
		Finatica.CompanyCard.firstTime = false;
	}

	dict.remove_closed(Finatica.CompanyCard.catProductionClose);
	dict.remove_closed(Finatica.CompanyCard.catWholesaleTradeClose);
	dict.remove_closed(Finatica.CompanyCard.catRetailClose);
	dict.remove_closed(Finatica.CompanyCard.catServicesClose);

	dict.remove_closed(Finatica.CompanyCard.catWholesalePurchaseClose);
	dict.remove_closed(Finatica.CompanyCard.catRetailPurchaseClose);
	dict.remove_closed(Finatica.CompanyCard.catServicesPurchaseClose);

	if (categoryID == Finatica.CompanyCard.goodsCategoryProduction) { dict.add_closed(Finatica.CompanyCard.catProductionClose); }
	if (categoryID == Finatica.CompanyCard.goodsCategoryWholesaleTrade) { dict.add_closed(Finatica.CompanyCard.catWholesaleTradeClose); }
	if (categoryID == Finatica.CompanyCard.goodsCategoryRetail) { dict.add_closed(Finatica.CompanyCard.catRetailClose); }
	if (categoryID == Finatica.CompanyCard.goodsCategoryServices) { dict.add_closed(Finatica.CompanyCard.catServicesClose); }

	if (categoryID == Finatica.CompanyCard.goodsCategoryWholesalePurchase) { dict.add_closed(Finatica.CompanyCard.catWholesalePurchaseClose); }
	if (categoryID == Finatica.CompanyCard.goodsCategoryRetailPurchase) { dict.add_closed(Finatica.CompanyCard.catRetailPurchaseClose); }
	if (categoryID == Finatica.CompanyCard.goodsCategoryServicesPurchase) { dict.add_closed(Finatica.CompanyCard.catServicesPurchaseClose); }

	$find(dict.treeViews["Goods"]).get_nodes().clear();
	$find(dict.treeViews["Sectors2"]).get_nodes().clear();
	dict.filterState["Goods"] = null;

	var div = $("input[type=hidden][value=" + categoryID + "]").parent();
	$("#" + dict.hiddenFieldID).val($(div).find("span.resultHidden > input[type=hidden]").val());
	$("#" + Finatica.CompanyCard.finMD).find("a.md-Goods").click();
}

Finatica.CompanyCard.catProductionClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryProduction);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catProductionClose);
}

Finatica.CompanyCard.catWholesaleTradeClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryWholesaleTrade);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catWholesaleTradeClose);		
}

Finatica.CompanyCard.catRetailClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryRetail);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catRetailClose);		
}

Finatica.CompanyCard.catServicesClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryServices);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catServicesClose);
}

Finatica.CompanyCard.catWholesalePurchaseClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryWholesalePurchase);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catWholesalePurchaseClose);		
}

Finatica.CompanyCard.catRetailPurchaseClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryRetailPurchase);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catRetailPurchaseClose);		
}

Finatica.CompanyCard.catServicesPurchaseClose = function(sender, isSaving) {
	if (isSaving == false)
		return;
	Finatica.CompanyCard.setGoodsCategories(Finatica.CompanyCard.goodsCategoryServicesPurchase);
	$find(Finatica.CompanyCard.finMD).remove_closed(Finatica.CompanyCard.catServicesPurchaseClose);		
}

Finatica.CompanyCard.setGoodsCategories = function(categoryID) {
	var dict = $find(Finatica.CompanyCard.finMD);
	var selectedValue = $("#" + dict.hiddenFieldID).val();
	var div = $("input[type=hidden][value=" + categoryID + "]").parent();
	$(div).find("span.resultHidden > input[type=hidden]").val(selectedValue);
	var selectedValues = $find(dict.listBoxID).get_items();
	var resultHtml = "";
	for (var i = 0; i < selectedValues.get_count(); i++) {
		resultHtml += "<li><a href=\"#\" class=\"service catalog\">" + selectedValues.getItem(i).get_text() + "</a></li>";
	}
	$(div).find("ul").html(resultHtml);
}

Finatica.CompanyCard.openRubricatorNode = function(goodsID, sender) {
	var parentElement = $(sender).parent();

	if (parentElement.find('i.minus').length > 0) {
		parentElement.find('i.minus').removeClass('minus').addClass('plus');
		parentElement.find('ul, hr').hide();
		return;
	}

	if (parentElement.find('ul').length > 0) {
		parentElement.find('ul, hr').show();
		parentElement.find('i.plus').removeClass('plus').addClass('minus');
		return;
	}

	while ($(parentElement[0]).hasClass('.categoryDiv') == false) {
		var parentElement = $(parentElement[0]).parent();
	}
	var typeID = $(parentElement).find('input[type=hidden]').val();
	var proxy = new Finatica.WebServices.CompanyHelper();
	proxy.GetGoodsCategoryProducts(Finatica.CompanyCard.companyID, goodsID, typeID, Finatica.CompanyCard.nodeOpenSuccess, Finatica.CompanyCard.nodeOpenFail, sender);
}

Finatica.CompanyCard.nodeOpenSuccess = function(result, userContext, methodName) {
	$(userContext).find('i').removeClass('plus').addClass('minus');
	var res = JSON.parse(result);
	$(userContext).parent().find('ul').remove();
	var ulCat = "<hr /><ul class='no-markers'>"
	if (res.Categories != null && res.Categories.length > 0) {

		for (var i = 0; i < res.Categories.length; i++) {
			var category = res.Categories[i];
			if (category.ProductCount == 0 && category.HasSubCategories == false) {
				ulCat += "<li><div class='catalog-item'><a class=\"catalog-item-name\">" + category.Name + "</a></div><div class=\"catalog-counter\"><b>0</b></div></li>";
			}
			else {
				ulCat += "<li><div class='catalog-item'><a class=\"catalog-item-icon\" href=\"#\" onclick=\"Finatica.CompanyCard.openRubricatorNode('" 
							+ category.GoodsCategoryID
							+ "',this);return false;\"><i class=\"icon plus\"></i>"							
							+ "</a><a class=\"catalog-item-name\" href=\"#\" onclick=\"Finatica.CompanyCard.openRubricatorNode('" 
							+ category.GoodsCategoryID
							+ "',this);return false;\">"
							+ category.Name
							+ "</a></div><div class='catalog-counter'><b>" 
							+ category.ProductCount + "</b></div></li>";
			}
		}
	}

	if (res.Products != undefined && res.Products.length > 0) {
		for (var i = 0; i < res.Products.length; i++) {
			var prod = res.Products[i];
			ulCat += "<li><div class='card'><img src='/BinHandler.aspx?id=" + prod.LogoID +
							"&x=40&y=40' class='picture' title='" + prod.Name + "'><h3><a href='/products/" + prod.PageName
							+ "'>" + prod.Name + "</a></h3><p>";

			if (prod.IsFixedPrice == false) {
				if ((prod.Price != null && prod.Prшce != 0) || (prod.MaxPrice != null && prod.MaxPrшce != 0)) {
					ulCat += "Цена: ";
					if (prod.Price != null && prod.Price != 0)
						ulCat += " от " + prod.Price;

					if (prod.MaxPrice != null && prod.MaxPrice != 0)
						ulCat += " до " + prod.MaxPrice;

					ulCat += " " + prod.PriceCurrencyID;
				}
			}
			else {
				if (prod.Price != null && prod.Price != 0)
					ulCat +="Цена: " + prod.Price + " " + prod.PriceCurrencyID;
			}
			ulCat += "</p><br/><p>" + prod.Description
							+ "</p></div></li>";
		}
	}

	ulCat += "</ul>";
	$(userContext).parent().append(ulCat);
}
