var priceSymbol = "&pound;";
var COL_DEPARTURE_DATE = 1;
var COL_GOING_TO = 2;
var COL_FLYING_FROM = 3;
var COL_PRICE = 4;

var NO_OFFERS_FOR_SITE = '<p class="nooffers">Sorry, but there are no ski deals left for this season.</p>';
var NO_OFFERS = '<p class="nooffers">Sorry, but there are no ski deals left for {placeholder}.</p>';

Params=function(showCountry, showResort, showAccommodation, importantColumn, errorMsgPlaceHolder) {
	this.showCountry = showCountry;
	this.showResort = showResort;
	this.showAccommodation = showAccommodation;
	this.importantColumn = importantColumn;
	this.errorMsgPlaceHolder = errorMsgPlaceHolder;
}

/*
   Dummy error handler to catch all the error reported by DWR.
*/
DWREngine.setErrorHandler(DWRErrorHandler);
function DWRErrorHandler(v) {
	return true;
}

function getSiteId() {
	return document.getElementById('SITEID_SO').value;
}

function getDealsBySite() {
	specialOfferFacade.getDealsBySite(getSiteId(), displayDealsForSite);
}

function getCheapestPriceForAllCountriesBySite() {
	specialOfferFacade.getCheapestPriceForAllCountriesBySite(getSiteId(), displayCheapestPriceForAllCountriesBySite);
}

/*Easter Deals function */
function getEasterDeals() {
	var callbackProxy = function(dataFromServer) {
		var param = new Params(true, true, false, COL_DEPARTURE_DATE, 'easter');
		displayDealsByMonth(dataFromServer, param);
	};
	var callMetaData = { callback:callbackProxy };
	specialOfferFacade.getEasterDeals(getSiteId(), callMetaData);
}

function getDealsForSmallCountry(countryCode, countryName, isDestinationPage) {
	var callbackProxy = function(dataFromServer) {
		var param = new Params(false, true, true, COL_GOING_TO, countryName);
		  displayDealsForSmallCountry(dataFromServer, param);
	};
	var callMetaData = { callback:callbackProxy };
	specialOfferFacade.getDealsByCountry(getSiteId(), countryCode, false, isDestinationPage, callMetaData);
}

function getDealsForBigCountry(countryCode, countryName) {
	var callbackProxy = function(dataFromServer) {
		var param = new Params(false, true, true, COL_GOING_TO, countryName);
		  displayDealsForBigCountry(dataFromServer, param);
	};
	var callMetaData = { callback:callbackProxy };
	specialOfferFacade.getDealsByCountry(getSiteId(), countryCode, true, false, callMetaData);
}

function getCheapestPriceForAllResortsByCountry(countryCode) {
	specialOfferFacade.getCheapestPriceForAllResortsByCountry(getSiteId(), countryCode, displayCheapestPriceForAllResortsByCountry);
}

function getDealsByCountryAndResort(countryCode, resortCode, resortName, isDestinationPage) {
	var callbackProxy = function(dataFromServer) {
		var param = new Params(false, true, true, COL_GOING_TO, resortName);
		  displayDealsByCountryAndResort(dataFromServer, param);
	};
	var callMetaData = { callback:callbackProxy };
	specialOfferFacade.getDealsByCountryAndResort(getSiteId(), countryCode, resortCode, isDestinationPage, callMetaData);
}

function getCheapestPriceForAllMonthsBySite() {
	specialOfferFacade.getCheapestPriceForAllMonthsBySite(getSiteId(), displayCheapestPriceForAllMonthsBySite);
}

function getDealsByMonth(monthCode, monthName) {
	var callbackProxy = function(dataFromServer) {
		var param = new Params(true, true, false, COL_DEPARTURE_DATE, monthName);
		displayDealsByMonth(dataFromServer, param);
	};
	var callMetaData = { callback:callbackProxy };
	specialOfferFacade.getDealsByMonth(getSiteId(), monthCode, callMetaData);
}

function getCheapestPriceForAllAirportsBySite() {
	specialOfferFacade.getCheapestPriceForAllAirportsBySite(getSiteId(), displayCheapestPriceForAllAirportsBySite);
}

function getDealsByDeparturePoint(departureCode, departureAirport) {
	var callbackProxy = function(dataFromServer) {
		var param = new Params(true, true, false, COL_FLYING_FROM, departureAirport);
		displayDealsByDeparturePoint(dataFromServer, param);
	};
	var callMetaData = { callback:callbackProxy };
	specialOfferFacade.getDealsByDeparturePoint(getSiteId(), departureCode, callMetaData);
}

function getLocationName(so, param, rating) {
	var retValue = '';
	if(param.showAccommodation) {
		retValue += '<span class="accommodation">'+ so.accommodation + ' </span>' +  rating ;
	}
	if(param.showResort) {
		retValue += '<span class="resort">'+ so.resort + ' </span>';
	}
	if(param.showCountry) {
		retValue += '<span class="country">'+ so.country + ' </span>';
	}
	return retValue;
}

function getSortableLocationName(so, param) {
	var retValue = '';
	if(param.showAccommodation) {
		retValue += so.accommodation;
	}
	if(param.showResort) {
		retValue += so.resort;
	}
	if(param.showCountry) {
		retValue += so.country;
	}
	return retValue;
}

function displayDealsForSite(offers) {
	if(offers.length == 0) {
		hideListAndLabel('topSkiDeals');
		hideListAndLabel('departFromList');
		hideListAndLabel('countryList');
		hideListAndLabel('monthList');
		
		displayErrorMsg(document.getElementById('topSkiDeals').parentNode.parentNode, NO_OFFERS_FOR_SITE);
		return;
	}
	displayDealsAsGrid('topSkiDeals', offers, true);
}

function displayDealsAsGrid(component, offers, countryAsHeader) {
	var trackingCode = '';
	var parentNode = document.getElementById(component);
	var textToReplace = '';
	document.getElementById(component).innerHTML = textToReplace;
	
	for(var i=0; i<offers.length; i++) {
		
		if(!countryAsHeader)
		{
			trackingCode = "goingto";
		}

		textToReplace += '<li>';
		textToReplace += '<div class="insideOfferAd">';
		textToReplace += '<div class="text">';
		if(countryAsHeader) {
			textToReplace += '<h4><span>'+ offers[i].country + '<br/>' + offers[i].resort +'</span></h4>';
		} else {
			textToReplace += '<h4><span>'+ offers[i].resort +'</span></h4>';
		}
		textToReplace += '<p class="price"><span>from </span><a href="'+ getUrl(offers[i], trackingCode) +'">' + priceSymbol + offers[i].price + '</a></p>';
		textToReplace += '<p class="depart">'+ offers[i].airportName +'</p>';
		textToReplace += '<p class="date">' + formatDate(offers[i].departureDateAsDate) + '</p>';
		textToReplace += '</div>';
		textToReplace += '</div>';
		textToReplace += '</li>';
	}
	document.getElementById(component).innerHTML = textToReplace;
}

function displayDealsForSmallCountry(offers, args) {
	if(offers.length == 0) {
		var errMsg = NO_OFFERS.replace("{placeholder}", args.errorMsgPlaceHolder);
		hideComponent('specialoffersTable');
		displayErrorMsg(document.getElementById('specialoffersTable').parentNode, errMsg);
		return;
	}
	
	displayDealsAsTable('specialoffersTable', offers, args, 'goingto');
}

function displayDealsForBigCountry(offers, args) {
	if(offers.length == 0) {
		hideListAndLabel('topSkiDeals');
		hideListAndLabel('resortListPart1');
		hideListAndLabel('resortListPart2');
		document.getElementById('resortListPart1').parentNode.parentNode.style.display = 'none';
		
		var errMsg = NO_OFFERS.replace("{placeholder}", args.errorMsgPlaceHolder);
		displayErrorMsg(document.getElementById('topSkiDeals').parentNode.parentNode, errMsg);
	}
	displayDealsAsGrid('topSkiDeals', offers, false);
}

function displayCheapestPriceForAllAirportsBySite(offers) {
	displayAbstractOfferList('departFromList', offers);	
}

function displayCheapestPriceForAllCountriesBySite(offers) {
	displayAbstractOfferList('countryList', offers);	
}

function displayCheapestPriceForAllMonthsBySite(offers) {
	displayAbstractOfferList('monthList', offers);
}

function displayCheapestPriceForAllResortsByCountry(offers) {
	displayAbstractOfferList('resortListPart1', offers);
	displayAbstractOfferList('resortListPart2', offers);
}

function displayDealsByDeparturePoint(offers, args) {
	if(offers.length == 0) {
		var errMsg = NO_OFFERS.replace("{placeholder}", args.errorMsgPlaceHolder);
		hideComponent('specialoffersTable');
		displayErrorMsg(document.getElementById('specialoffersTable').parentNode, errMsg);
		return;
	}
	
	displayDealsAsTable('specialoffersTable', offers, args, 'flyingfrom');
}

function displayDealsByMonth(offers, args) {
	if(offers.length == 0) {
		var errMsg = NO_OFFERS.replace("{placeholder}", args.errorMsgPlaceHolder);
		hideComponent('specialoffersTable');
		displayErrorMsg(document.getElementById('specialoffersTable').parentNode, errMsg);
		return;
	}
	
	if(args.errorMsgPlaceHolder == 'easter')
	{
		displayDealsAsTable('specialoffersTable', offers, args, 'easter');
	}else
	{
		displayDealsAsTable('specialoffersTable', offers, args, 'departingin');
	}
}

function displayDealsByCountryAndResort(offers, args) {
	if(offers.length == 0) {
		var errMsg = NO_OFFERS.replace("{placeholder}", args.errorMsgPlaceHolder);
		hideComponent('specialoffersTable');
		displayErrorMsg(document.getElementById('specialoffersTable').parentNode, errMsg);
		return;
	}
	displayDealsAsTable('specialoffersTable', offers, args, 'goingto');
}

function displayAbstractOfferList(component, offers) {
	var parentDoc = document.getElementById(component);
	var childNodes = parentDoc.getElementsByTagName('li');
	for(var node = 0; node < childNodes.length; node++) {
		var found = false;
		if(childNodes[node].id != null) {
			for(var i = 0; i<offers.length; i++) {
				if(offers[i].code == childNodes[node].id) {
					childNodes[node].getElementsByTagName('span')[2].innerHTML = priceSymbol + offers[i].price;
					found = true;
				}
			}
		}
		
		if(!found) {
			childNodes[node].style.display="none";
		}
	}
}

function displayDealsAsTable(component, specialOffers, args, dealOf) {	
	var SITE_ID = getSiteId();
	var table = document.getElementById(component).getElementsByTagName('tbody')[0];
	var rowCntr = table.rows.length;

	for(var x=specialOffers.length-1; x>=0; x--) {
		var row = table.insertRow(rowCntr);

		var accomRating = specialOffers[x].accommodationRating;
		var isAccomRatingNullOREmpty;
		if(accomRating == null || accomRating == '') {
			isAccomRatingNullOREmpty = true;
		} else {
			isAccomRatingNullOREmpty = false;
		}

		var accomRatingInText = new Array();
		if(isAccomRatingNullOREmpty == false) {
			var accomRatingSplitted = new Array();
			accomRatingSplitted = accomRating.split('/');
			
			var accomRatingWithNoDecimalPoint = new Array();
			for(var l=0;l<accomRatingSplitted.length;l++) {
				accomRatingWithNoDecimalPoint[l] = String(parseFloat(accomRatingSplitted[l])).replace('.','');
											
				if(accomRatingSplitted[l].indexOf('.')!=-1 && accomRatingSplitted[l].charAt(accomRatingSplitted[l].indexOf('.')+1)=='0') {
					accomRatingInText[l] = accomRatingSplitted[l].substring(0,accomRatingSplitted[l].indexOf('.'));
				} else if(accomRatingSplitted[l].indexOf('.')!=-1 && accomRatingSplitted[l].charAt(accomRatingSplitted[l].indexOf('.')+1)=='5') {
					accomRatingInText[l] = accomRatingSplitted[l].substring(0,accomRatingSplitted[l].indexOf('.'))+'  and a half';
				} else {
					accomRatingInText[l] = accomRatingSplitted[l];
				}
			}
		}
		if(isAccomRatingNullOREmpty == false) {
			var rating = "";
			for(var l=0;l<accomRatingSplitted.length;l++) {
				rating +='<span class="rating crystalRate'+ accomRatingWithNoDecimalPoint[l] +'"><span>(Crystal rating '+ accomRatingInText[l] +') </span></span>'					  
			}
		}
		if(isAccomRatingNullOREmpty == true){
			var rating = "";
			rating +='';
		}
		
		var priceCol = row.insertCell(0);
		priceCol.innerHTML = '<a href="'+getUrl(specialOffers[x], dealOf)+'"><span class="price">' + priceSymbol + ("" + specialOffers[x].price) + ' </span><span class="deal">('+ specialOffers[x].nights + ' nights)</span></a>';
		priceCol.setAttribute("sorttable_customkey", specialOffers[x].price);
		if(args.importantColumn == COL_PRICE) {
			priceCol.setAttribute("class", "price importantColumn");
		} else {
			priceCol.setAttribute("class", "price");
		}
		
		var airportCol = row.insertCell(0);
		airportCol.innerHTML = specialOffers[x].airportName;
		if(args.importantColumn == COL_FLYING_FROM) {
			airportCol.setAttribute("class", "departure importantColumn");
		} else {
			airportCol.setAttribute("class", "departure");
		}
		
		var locationCol = row.insertCell(0);
		locationCol.innerHTML = getLocationName(specialOffers[x], args, rating);
		locationCol.setAttribute("sorttable_customkey", getSortableLocationName(specialOffers[x], args));
		if(args.importantColumn == COL_GOING_TO) {
			locationCol.setAttribute("class", "destination importantColumn");
		} else {
			locationCol.setAttribute("class", "destination");
		}
		
		var departureDateCol = row.insertCell(0);
		departureDateCol.setAttribute("sorttable_customkey", getSortableDate(specialOffers[x].departureDateAsDate));
		if(args.importantColumn == COL_DEPARTURE_DATE) {
			departureDateCol.setAttribute("class", "date importantColumn");
		} else {
			departureDateCol.setAttribute("class", "date");
		}
		departureDateCol.innerHTML = formatDate(specialOffers[x].departureDateAsDate);
	}
}

function getSortableDate(dateObj) {
	var jsDate = new Date(dateObj.getTime());
	var curr_date = jsDate.getDate() + "";
	var curr_month = jsDate.getMonth() + "";
	var curr_year = jsDate.getFullYear() + "";

	if(curr_date.length < 2) {
		curr_date = "0" + curr_date;
	}

	if(curr_month.length < 2) {
		curr_month = "0" + curr_month;
	}
	
	return (curr_year  + "" + curr_month + "" + curr_date);
}

function formatDate(dateObj) {
	var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var jsDate = new Date(dateObj.getTime());
	var curr_date = jsDate.getDate();
	var curr_month = jsDate.getMonth();
	var curr_year = jsDate.getFullYear();
	
	return (curr_date + " " + m_names[curr_month] + " " + (curr_year + ""));
}

function getUrl(offer, trackingCode) {

	var link = "links";
	var airportName = offer.airportName;

	if(trackingCode == 'goingto')
	{
		trackingCode = "_s_icmp=" + trackingCode + (offer.country).toLowerCase() + link;

	}else if(trackingCode == 'flyingfrom')
	{
		if(airportName != null)
		{ 
			if(airportName.indexOf(' ') != -1)
			{
				airportName = airportName.replace(" ","");
			}
			
			if(airportName.indexOf('/') != -1)
			{
				airportName = airportName.replace("/","");
			}

			if(airportName.lastIndexOf('London') != -1)
			{
				airportName = airportName.replace("London","");
			}			
		}

		trackingCode = "_s_icmp=" + trackingCode + airportName.toLowerCase() + link;

	}else if(trackingCode == 'departingin')
	{		
		trackingCode = "_s_icmp=" + trackingCode + getMonth(offer.departureDateAsDate) + link;

	}else if(trackingCode == 'easter')
	{		
		trackingCode = "_s_icmp=departingin" + trackingCode + link;
	}
	else
	{		
		trackingCode = '_s_icmp=ourbestdeals';
	}

		var spurl ='';
	    spurl = '/crystalskiSelectSpecialOffer.do?' + trackingCode;
		spurl += '&siteId=' + getSiteId();
		spurl += '&packageType=OfferOnly';
		spurl += '&pageType=deals';
		spurl += '&departureDate=' + offer.departureDate;
		spurl += '&country=' + offer.country;
		spurl += '&countryCode=' + offer.countryCode;
		spurl += '&resortCode=' + offer.resortCode;
		spurl += '&accomCode=' + offer.accomCode;
		spurl += '&nights=' + offer.nights;
		spurl += '&board=' + offer.board;
		spurl += '&resort=' + encodeURIComponent(offer.resort);
		spurl += '&accommodation=' + encodeURIComponent(offer.accommodation);
		spurl += '&departureAirport=' + encodeURIComponent(offer.departureAirport);
		spurl += '&airportName=' + encodeURIComponent(offer.airportName);
		spurl += '&countryList=' + offer.resortCode;
		spurl += '&accommodationList=' + offer.accomCode;

		return spurl;
}

function hideComponent(componentId) {
	document.getElementById(componentId).style.display = 'none';
}

function displayErrorMsg(parentElem, errorMsg) {
	var newdiv = document.createElement('div'); 
	newdiv.innerHTML = errorMsg; 
	parentElem.insertBefore(newdiv, parentElem.childNodes[0]);
}

function hideListAndLabel(component) {
	var obj = document.getElementById(component);
	obj.style.display = 'none';
	obj.parentNode.style.display = 'none';
}

function getMonth(dateObj) {
	var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var jsDate = new Date(dateObj.getTime());
	var curr_month = jsDate.getMonth();	
	return m_names[curr_month].toLowerCase();
}