/* Global Containers: Should be in sync with the database. */
var HOME_PAGE			= 1;
var SPECIAL_OFFER_PAGE	= 2;
var ACTIVE_BEACH_GREECE	= 4;
var ACTIVE_BEACH_TURKEY	= 8;
var ACTIVE_MOUNTAIN 	= 16;

var currentGroupId='';
var currentGroupTitle='';
var currentGroupIntroText='';
var currentGroupOutroText='';
var groupcount=1;
var urlArray=new Array();
var urlArrayIntro=new Array();
var urlArrayOutro=new Array();
var groupNames=new Array();
var groupIDs = new Array();

/*
   Dummy error handler to catch all the error reported by DWR.
*/
DWREngine.setErrorHandler(DWRErrorHandler);
function DWRErrorHandler(v) {
	return false;
}

// Call backend to get special offer groups.
function getSpecialOfferGroups(displayParam){
	var site_id_hid = document.getElementById('SITEID_SO').value;
	
	if(displayParam == HOME_PAGE) {
		specialOfferFacade.getSpecialOfferGroups(site_id_hid, displayParam, populateSpecialOfferGroups);
	} else if(displayParam == SPECIAL_OFFER_PAGE) {
		specialOfferFacade.getSpecialOfferGroups(site_id_hid, displayParam, populateSpecialOfferGroupsOnOffersPage);
	} else if(displayParam == ACTIVE_BEACH_GREECE || displayParam == ACTIVE_BEACH_TURKEY || displayParam == ACTIVE_MOUNTAIN) {
		var callbackProxy = function(dataFromServer) {
			  processSpecialOfferGroups(dataFromServer, displayParam);
		};
		var callMetaData = { callback:callbackProxy };
		specialOfferFacade.getSpecialOfferGroups(site_id_hid, displayParam, callMetaData);
	}
}

// Call backend to get special offers by country
function getSpecialOffersByCountry(groupId, index, displayParam){
	specialOfferFacade.getSpecialOffersByCountry(groupId, displayParam, populateSpecialOffersByCountry);
	currentGroupId=groupId;
	currentGroupTitle=groupNames[index];
	currentGroupIntroText=urlArrayIntro[index];
	currentGroupOutroText=urlArrayOutro[index];


}

// Call backend to get special offers
function getSpecialOffers(tabId,groupId,displayParam,groupno){
	currentGroupId=groupId;
 // Remove style class from all offer tabs
	anchorslist = document.getElementsByTagName('a');
	for(i=0;i<anchorslist.length;i++) {
	 if (anchorslist[i].id.indexOf('offergrouptab') > -1) {
		anchorslist[i].className = '';
	 }
	}
 // add style class to current tabs
	document.getElementById('offergrouptab' + groupId).className = 'cstabactive';	
	specialOfferFacade.getSpecialOffers(groupId, displayParam, populateSpecialOffers);
	if (parseInt(groupno) == 1) { groupno = ''; }
 //	displayTeaserForGroup(groupno);
}

// CALLBACK FUNCTIONS BEGIN - PLEASE PUT ALL BACK END INTERACTION FUNCTIONS ABOVE THIS

// Function to populate special offer groups on special offers page
function populateSpecialOfferGroupsOnOffersPage(specialOfferGroups) 
{
	// specify the special offer to show at page load.
	// to use append an anchor to the url with the index of the specialOffer eg. crystalski.co.uk/specialoffers/#2
	// it uses a single digit only 0 - 9
	if (specialOfferGroups == null ) {
		return false;
	}
	// If special offers present...
	var offersTabs=new Array(); 
	var url = window.location.toString();
	 var index = 0;
      if(url.indexOf('?') > -1) {
      index = parseInt(url.substring(url.indexOf('?')+1));
      }
 
      if (isNaN(index)){ index = 0;}
      if(index >= specialOfferGroups.length) {
      index = 0;
      }
	if(specialOfferGroups.length > 0)
	{
		for(p=0;p<=1;p++)
		{
			offersTabs[p] = '<ul>';
			for(i = 0; i < specialOfferGroups.length; i++) 
			{
				urlArrayIntro[i]= specialOfferGroups[i].introText;
				urlArrayOutro[i]= specialOfferGroups[i].outroText;
				groupIDs[i] = specialOfferGroups[i].groupId;
				groupNames[i]=specialOfferGroups[i].groupName;
				offersTabs[p] += '<li';
				if(i==0)
					offersTabs[p] += ' class="first"';
				offersTabs[p] += '>';
				offersTabs[p] += '<a  id="' + specialOfferGroups[i].groupId + 'link' + p + '" href="javascript:getSpecialOffersByCountry(\'' 
						+ specialOfferGroups[i].groupId 
						+ '\',\'' 
						+ i 
						+ '\',\'' 
						+ SPECIAL_OFFER_PAGE
						+ '\');highlightSelectedTab(\'' + specialOfferGroups[i].groupId + '\')"><span>' + specialOfferGroups[i].groupName; + '</span></a></li>';
			}
			offersTabs[p] += '</ul>';
		}
		document.getElementById('tabs').innerHTML = offersTabs[0];
		document.getElementById('specialoffersnav').innerHTML = offersTabs[1];
		getSpecialOffersByCountry(specialOfferGroups[index].groupId, index, SPECIAL_OFFER_PAGE);
	}
}

function highlightSelectedTab(grpid) {
	for(i=0; i<groupIDs.length; i++) {
		if(grpid == groupIDs[i]) {
			document.getElementById(groupIDs[i]+'link0').className= "selected";
			document.getElementById(groupIDs[i]+'link1').className= "selected";
		}
		else {		
			document.getElementById(groupIDs[i]+'link0').className = "";
			document.getElementById(groupIDs[i]+'link1').className = "";
		}
	}
}
// This function populates the special offers by country on special offers page.
function populateSpecialOffersByCountry(specialOffersByCountry)
{
	// Set the class for selected group's link and disable the class for others
	for(x=0;x<groupIDs.length;x++)
	{
		document.getElementById(groupIDs[x] + 'link0').className = 'normal';
		document.getElementById(groupIDs[x] + 'link1').className = 'normal';
	}
	document.getElementById(currentGroupId + 'link0').className = 'selected';
	document.getElementById(currentGroupId + 'link1').className = 'selected';
	
	// Display the offers
	var SITE_ID = document.getElementById('SITEID_SO').value;
	var offersContent = '<h3>' +  currentGroupTitle + '</h3>' + '<p class="introText">' + currentGroupIntroText + '</p>';
	for (i = 0; i < specialOffersByCountry.length; i++)
	{
		urlArray[i]= new Array();
		var specialOfferCountryList = specialOffersByCountry[i];
		offersContent += '<h4>' + specialOfferCountryList[0].country + '</h4>'+ '<ul>';
						for (j = 0; j < specialOfferCountryList.length ; j++ )
						{
							var spurl ='';
							var k = j+1;
						    spurl = '/firstchoiceskiSelectSpecialOffer.do?';
							spurl += 'siteId=';
							spurl +=  SITE_ID;
							spurl += '&packageType=OfferOnly';
							spurl += '&departureDate='+specialOfferCountryList[j].departureDate;
							spurl += '&airportName=' + encodeURIComponent(specialOfferCountryList[j].airportName);
							spurl += '&country='+specialOfferCountryList[j].country;
							spurl += '&countryCode='+specialOfferCountryList[j].countryCode;
							spurl += '&resortCode='+specialOfferCountryList[j].resortCode;
							spurl += '&accomCode='+specialOfferCountryList[j].accomCode;
							spurl += '&nights='+specialOfferCountryList[j].nights;
							spurl += '&board='+specialOfferCountryList[j].board;
							spurl += '&groupId='+currentGroupId;	  
							spurl += '&resort='+encodeURIComponent(specialOfferCountryList[j].resort);
							spurl += '&accommodation='+encodeURIComponent(specialOfferCountryList[j].accommodation);
							urlArray[i][j+1] = spurl;
							
							var accommodationRating = specialOfferCountryList[j].accommodationRating;
							var ratings = '';
							if ((accommodationRating != '') && (accommodationRating != null))
							{
								ratings = accommodationRating.split('.');
							}

							var fullRating = ratings[0];
							var ratingString = '';
							for(x=0;x<fullRating;x++)
							{
								ratingString += '<img alt="full rating" src="/images/snowrating.gif"/>';
							}
							if(ratings.length > 1)
							{
								ratingString += '<img alt="half rating" src="/images/snowhalfrating.gif"/>';
							}
							offersContent += '<li>'
										  +				'<a href="javascript:submitForm(' + i + ',' + k + ','
										  +					'\'' + specialOfferCountryList[j].resortCode + '\','
										  +					'\'' + specialOfferCountryList[j].accomCode + '\')'
										  +				'">' 
  										  + 	'<span class="locationInfo">'
										  +		'<span class="accommodationName">' + specialOfferCountryList[j].accommodation + ' </span>'
										  + 	'<span class="countryAndResortName">(' + specialOfferCountryList[j].resort + ', ' + specialOfferCountryList[j].country + ') </span>'
										  + 	'<span class="rating">' + ratingString + ' </span>'
										  +		'</span>'
  										  + 	'<span class="holidayInfo">'
										  + 		'<span class="date">' + getFormattedDate(specialOfferCountryList[j].departureDate) + ', </span>'
										  +			'<span class="duration">' + specialOfferCountryList[j].nights + ' nights </span>'
										  +			'<span class="board">' + specialOfferCountryList[j].board + ' </span>'
										  +			'<span class="price">'
										  +				'&pound;' 
										  +					specialOfferCountryList[j].price
										  +		'</span>'
  										  +		'</span>'
  										  +		'</a>'
										  +	 '</li>';
										  
						}
					  + '</ul>';
		
	}
	offersContent += '<p class="outroText">' + currentGroupOutroText + '</p>';
	document.getElementById('tabContent').innerHTML = offersContent;
}

// Function to populate special offer groups
function populateSpecialOfferGroups(specialOfferGroups) {
	if (specialOfferGroups == null ) 
	{
		document.getElementById("sploffers").style.display='none';
		return false;
	} 
	if(specialOfferGroups.length > 0)
	{
		var text = '';
		text += '<a id="offergrouptab';
		text += specialOfferGroups[0].groupId;
		text += '"';
		text += ' href="javascript:getSpecialOffers(\'offergrouptab'+specialOfferGroups[0].groupId+'\',';
		text += '\''+specialOfferGroups[0].groupId+'\'';
		text += ',';
		text += '\''+HOME_PAGE+'\'';
		text += ',' + groupcount + ')"';
		text += ' class="cstabactive" >';
		text += '<span>';
		text += specialOfferGroups[0].groupName;
		text += '</span>';
		text += ' </a>';
	
		for(i = 1; i < specialOfferGroups.length; i++) {
			groupcount++;
			text += '<a';
			text += ' href="javascript:getSpecialOffers(\'offergrouptab'+specialOfferGroups[i].groupId+'\',';
			text += '\''+specialOfferGroups[i].groupId+'\'';
			text += ',';
			text += '\''+HOME_PAGE+'\'';
			text += ',' + groupcount + ')"';
			text += ' id="offergrouptab';
			text += specialOfferGroups[i].groupId;
			text += '">';
			text += '<span>';
			text += specialOfferGroups[i].groupName;
			text += '</span>';
			text += '</a>';
		}
		document.getElementById('offernav').innerHTML = text;

		// Fire off special offers fetch.
		getSpecialOffers('offergrouptab'+specialOfferGroups[0].groupId, specialOfferGroups[0].groupId, HOME_PAGE,1);
	}
	else
	{
		document.getElementById("sploffers").style.display='none';
	}
}

// Function to populate special offers
function populateSpecialOffers(specialOffers) {
	var SITE_ID = document.getElementById('SITEID_SO').value;
	var offersContent = '<div class="insideOffers"><table cellspacing="0" class="specialOffersTable">';
	for (j = 0; j < specialOffers.length ; j++ )
	{
		var spurl ='';
		var k = j+1;
	    spurl = '/firstchoiceskiSelectSpecialOffer.do?';
		spurl += 'siteId=';
		spurl +=  SITE_ID;
		spurl += '&packageType=OfferOnly';
		spurl += '&departureDate='+specialOffers[j].departureDate;
		spurl += '&airportName=' + encodeURIComponent(specialOffers[j].airportName);
		spurl += '&country='+specialOffers[j].country;
		spurl += '&countryCode='+specialOffers[j].countryCode;
		spurl += '&resortCode='+specialOffers[j].resortCode;
		spurl += '&accomCode='+specialOffers[j].accomCode;
		spurl += '&nights='+specialOffers[j].nights;
		spurl += '&board='+specialOffers[j].board;
		spurl += '&groupId='+currentGroupId;	  
		spurl += '&resort='+encodeURIComponent(specialOffers[j].resort);
		spurl += '&accommodation='+encodeURIComponent(specialOffers[j].accommodation);
		urlArray[j] = spurl;
		
		offersContent += '<tr>'
					  + '<td>'
					  + 	'<div class="location">'
					  +				'<a href="javascript:submitForm(' + j + ',\'\','
					  +					'\'' + specialOffers[j].resortCode + '\','
					  +					'\'' + specialOffers[j].accomCode + '\')'
					  +				'">' 
  					  +			'<span class="holiday">'
					  + 		'<span class="date">' + getFormattedDate(specialOffers[j].departureDate) + ' </span>'
					  +			'<span class="price">'
					  +				'&pound;' 
					  + 				specialOffers[j].price
					  + 		'</span>'
  					  + 		'</span>'
					  + 	'<span class="accommodationName">' + specialOffers[j].accommodation + ' </span>'
					  + 	'<span class="countryAndResortName">' + specialOffers[j].resort + ', ' + specialOffers[j].country + ' </span>'
					  + 			'</a>'
					  + 	'</div>'
					  +	 '</td>'
					  + '</tr>';
					  
	}
  	offersContent += '</table></div>';
	document.getElementById('offers').innerHTML = offersContent;
}

//Submit the form
function submitForm(urlindex1,urlindex2, counres,accom){

if (urlindex2 == '')

{

	this.document.spoffers.action=urlArray[urlindex1];
} else{
	
	this.document.spoffers.action=urlArray[urlindex1][urlindex2];
}
    	
	this.document.spoffers.method='POST';
	this.document.getElementById("countryList").value = counres ;
	this.document.getElementById("accommodationList").value = accom ;
	this.document.spoffers.submit();
}

// Return the formatted date.
function getFormattedDate(date) {
var firstDash = date.indexOf("-");
var secondDash = date.lastIndexOf("-");
var year = date.substring(0,firstDash);
var month = date.substring(firstDash+1,secondDash);
var day = date.substring(secondDash+1);

var monthName='';

switch(month)
{
case '1':
case '01':
	monthName="Jan"
	break
case '2':
case '02':
	monthName="Feb"
	break
case '3':
case '03':
	monthName="Mar"
	break
case '4':
case '04':
	monthName="Apr"
	break
case '5':
case '05':
	monthName="May"
	break
case '6':
case '06':
	monthName="Jun"
	break
case '7':
case '07':
	monthName="Jul"
	break
case '8':
case '08':
	monthName="Aug"
	break
case '9':
case '09':
	monthName="Sep"
	break
case '10':
	monthName="Oct"
	break
case '11':
	monthName="Nov"
	break
case '12':
	monthName="Dec"
	break

}

return day+' '+monthName+' '+year;
}

function displayTeaserForGroup(groupno)
{
	for (i=1; i<=10; i++)
	{
		if (i == groupno) {
			document.getElementById("cmscontent").rows[i-1].style.display=""; 
		}else{
			document.getElementById("cmscontent").rows[i-1].style.display="none"; 
		}
	}
}