var dictionary;
var newWindowInAnchor;
var hotelPageTargetAttribute;
var Showcase;

//кол-во запросов
var kSending;
//кол-во принятых ответов
var kReceiving;
//временное хранилище принятых ответов
var tempPrices = new Array();

ShowcaseElement = function()
{
	this.departureCity = -1;
	this.destinationCountry = -1; 
	this.destinationCities = [];
	this.hotels = [];
	this.stars = [];
	this.meals = [];
	this.departureDateFromNowCount = -1;
	this.departureDateCount = -1;
	this.nightsFrom = -1;
	this.nightsTo = -1;
	this.priceFrom = -1;
	this.priceTo = -1;
	this.currency = -1;
	this.adult = -1;
	this.child = -1;
	this.operatorIds = [];
	this.positionCount = -1;
	this.filtrateIdenticalHotels = false;
}

ShowcaseElement.prototype.Validate = function()
{
	if(this.destinationCountry < 1)
		return "Страна не задана";
	if(this.departureDateFromNowCount < 0)
		return "Дата вылета не задана";
	if(this.departureDateCount < 1)
		return "Дата вылета не задана";
	if(this.departureCity < 1)
		return "Город вылета не задан";
	if(this.adult < 0)
		return "Количество взрослых не задано";
	if(this.positionCount < 1)
		return "Количество позиций не задано или меньше 1";
		
	return "OK";
}

function GetShowcase()
{
	for (var i = 0; i < Showcase.length; i++) {
		var validateResult = Showcase[i].Validate();
		if (validateResult != "OK") {
			alert(validateResult);
			ToggleShowcaseWaitBox("hide");
			return;
		}
		if(Showcase[i].currency == -1) {
		   Showcase[i].currency = showcaseCurrencyId; 
		}
	}
	
	kSending = 0;
	kReceiving = 0;
	for (var i = 0; i < Showcase.length; i++) {
    kSending++;
  	var params = [];
    params.push([Showcase[i]]);

  	var priceObject = null;
    priceObject = new Price(remoteUri + "/Price.ashx");
  	priceObject.getShowcase(params, showcase_callback);
	}
}

function showcase_callback(response)
{	
	if ((response.error == null) && (response.result != null) && (response.result.length > 0) ) {
		var truePrices = getArrayWithoutNull(response.result);
		if(truePrices.length > 0) {
      tempPrices.push(truePrices);
		}
	} else {
		tempPrices.push("");
		if (response.error != null) {
			if (response.error.message != null) {
				ToggleShowcaseWaitBox("hide");
				alert(response.error.message);
			}
		}
	}
	processPrices(truePrices);
}

//Функция обрабатывает полученный ответ
function processPrices(truePrices)
{
  kReceiving++;
  //если получили последний ответ, то
  if (kSending == kReceiving) {
    //помещаем все полученные ответы в один массив
    var truePricesAll = new Array();
    for(var index=0; index<tempPrices.length; index++) {
      for (var i=0;i<semiAJAX.answers.length;i++) {
        if ((semiAJAX.answers[i]==index) && (tempPrices[i]!="")) {
          truePricesAll = truePricesAll.concat(tempPrices[i]);
        }
      }
    }
    //отрисовываем результаты
    drawShowcase(truePricesAll);
  }
}

function drawShowcase(truePrices)
{
	ToggleShowcaseWaitBox("hide");
	var table = $("Showcase");
	var currentTD = $("showcaseFirstElement");
	var tourDiv = $("Tour");
	if ((table != null) && (currentTD != null) && (tourDiv != null)) {
		var tableBody = table.tBodies[0];
		var templateTD = currentTD.clone(false);
		templateTD.removeProperty('id');
		currentTD = templateTD.clone(false);
		for(var r = 0; r < tableBody.rows.length; r++) tableBody.deleteRow(r);
		for (var tr = 0; tr < ShowcaseHeight; tr++) {
			for (var td = 0; td < ShowcaseWidth; td++) {
				var count = tr * ShowcaseWidth + td;
				if (count >= truePrices.length) return;
				
				if (td == 0) {
					var newTR = new Element("tr");
					currentTD.injectInside(newTR);
					newTR.injectInside(tableBody);
				} else {
					currentTD.injectInside(tableBody.rows[tr]);
				}
				var cloneTour = tourDiv.clone(true);
				cloneTour.id += '-' + tr + 'x' + td;
				setModalID(cloneTour, '-' + tr + 'x' + td);
				drawTour(cloneTour, truePrices[count]);
				cloneTour.injectInside(currentTD);
				cloneTour.setStyle('display', "block");
				currentTD = templateTD.clone(false);
			}
		}
		tourDiv.remove();
	}
}

function drawTour(view, tour)
{
	var tourChilds = view.childNodes;
	var tourChild;
	
	if(!tour) return;

	var popupHeight = parseInt(window.getHeight() * 0.9); hotelPageHeight = hotelPageHeight > popupHeight ? popupHeight : hotelPageHeight;
	var popupWidth = parseInt(window.getWidth() * 0.9); hotelPageWidth = hotelPageWidth > popupWidth ? popupWidth : hotelPageWidth;
	
	for(var i = 0; i < tourChilds.length; i++) {
		tourChild = tourChilds[i];
		if (tourChild.className != null) {
			switch (tourChild.className) {
				case "modaljs": {
					switch (tourChild.id.replace(/-\d+x\d+/, '')) {
						case "anchorImage": {
							tourChild.setProperties({
								href: 'index.php?option=com_csbronni&view=tours&layout=hotel&tmpl=component&hotelId=' + buildSlug(tour.price.hotel.id, tour.price.hotel.englishName) + '&priceId=' + tour.price.id + '&currencyId=' + showcaseCurrencyId,
								rel: "{handler: 'iframe', size: {x: " + hotelPageWidth + ", y: " + hotelPageHeight + "}}"
							});
							break;
						}
						case "anchorPrice": {
							tourChild.setProperties({
								href: 'index.php?option=com_csbronni&view=tours&layout=hotel&tmpl=component&hotelId=' + buildSlug(tour.price.hotel.id, tour.price.hotel.englishName) + '&priceId=' + tour.price.id + '&currencyId=' + showcaseCurrencyId,
								rel: "{handler: 'iframe', size: {x: " + hotelPageWidth + ", y: " + hotelPageHeight + "}}"
							});
							/*tourChild.setProperties({
								href: 'index.php?option=com_csbronni&view=tours&layout=detail&tmpl=component&priceId=' + tour.price.id + '&currencyId=' + showcaseCurrencyId,
								rel: "{handler: 'iframe', size: {x: " + viewPageWidth + ", y: " + viewPageHeight + "}}"
							});*/
							break;
						}
					}
					tourChild.addEvent('click', OnClickSqueeze);
					break;
				}	
				case "image": {
					if (tour.imageGuid == "00000000-0000-0000-0000-000000000000") {
						tourChildImg = 'images/hotbronni/' + imageDefaultSrc;
					} else {
						tourChildImg = remoteUri + "/Handlers/HotelImageHandler.ashx?ImageGuid=" + tour.imageGuid + "&MaximumSize=" + imageMaxWidth + "," + imageMaxHeight + "";
					}
					tourChild.setStyles({
						width: imageMaxWidth,
						height: imageMaxHeight,
						background: 'transparent url(' + tourChildImg + ') center center no-repeat'
					});
					break;
				}
				case "destinationCountry": {
					tourChild.innerHTML = tour.price.country.russianName + getStars(tour.price.star.russianName);
					break;
				}							
				case "hotel": {
					tourChild.innerHTML = tour.price.hotel.russianName + ", " + tour.price.star.russianName;
					break;
				}
				case "price": {
					if (priceRepresentation != "PricePerPerson") {
						tourChild.innerHTML = getRoundedPrice(PriceCorrectionFun(tour.price.operatorPrice)) + " " + tour.price.operatorCurrency.key;
					} else {
						tourChild.innerHTML = getRoundedPrice(PriceCorrectionFun(tour.price.operatorPricePerPerson)) + " " + tour.price.operatorCurrency.key;
					}
					break;
				}
				case "departureDate": {
					tourChild.innerHTML = (Date.fromUTCString(tour.price.checkinDate)).toRUString();
					break;
				}
				case "duration": {
					tourChild.innerHTML = tour.price.duration + ' ночей';
					break;
				}
				case "touristsCount": {
					var touristsCount = tour.price.adultCount + tour.price.childrenCount;
					tourChild.innerHTML = touristsCount;
					break;
				}
			}
		}
		drawTour(tourChild, tour);
	}
}

function OnClickSqueeze(e)
{
	var anc = e.currentTarget || e.srcElement;
	if(e) var e = new Event(e).stop();
	anc = (window.ie) ? anc.parentNode : anc;
	if(anc) {
		SqueezeBox.fromElement(anc);
	}
}

function setModalID(view, suffix)
{
	if(view) {
		view.getChildren().each(function(el) { 
			if(el.className == 'modal') {
				el.id += suffix;
			} 
			if(el.getChildren().length) setModalID(el, suffix);
		});
	}
}

function getRoundedPrice(price)
{
	return price.replace(/\.\d+/, '');
}

function getStars(stars)
{
	var ret = '';
	stars = parseInt(stars);
	if(stars >0 && stars < 5) {
		for(var i = 0; i < stars; i++ ) {
			ret += '*';
		}
		ret = '<sup>' + ret + '</sup>';
	}
	return ret;
}

ToggleShowcaseWaitBox = function(state) 
{
	if ($("ShowcaseWaitBox") == null) return;
	
	if (state == 'show') {
		$("ShowcaseWaitBox").setStyle('display', 'inline');
	}	else if (state == 'hide') {
		$("ShowcaseWaitBox").setStyle('display', 'none');
	}	
}

