var COMMERCE_URL = "/Commerce.html";
var CHECK_PRICES_BUTTON = 1;
var BOOK_IT_BUTTON = 2;

var querywords = "";
var channel = "";
var isdev = "";
var action = "";

/**
 * Fetches commerces for search results pages
 * @param queryWords String The query
 * @return Boolean
 */
function getCommerceForSearch(queryWords)
{
	action = "search";
	var url = COMMERCE_URL;
	var data = "action="+action+"&querywords=" + escape(queryWords);
	
	$.ajax({
			   type: "GET",
			   url: url,
			   data: data,
			   success: function(msg)
			   {
					var results = eval ('(' + msg + ')');
					
					if(results['success'] == 'false')
					{
						
					}
					else
					{
						var locationcommercelist = new LocationCommerceList(results['commerce']['locationcommerces']);
						querywords = results['commerce']['querywords'];
						channel = results['commerce']['channel'];
						isdev = results['commerce']['isdev'];
						
						var locationcommerce = locationcommercelist.getLocationCommerceAt(0);
						
						if (locationcommerce) //locationcommerce is NULL is commerce is disabled on server
						{
							var packagelist = locationcommerce.getPackageList();
							
							if(packagelist)
							{
								$('#trip_commercebox_search_page').empty();
								$('#trip_commercebox_search_page').append(packagelist.toHTML(0, 4));
							}
						}
						else
						{
							$('#trip_commercebox_search_page').hide();
						}
					}
				}
			 });
	
	return true;
}

/**
* Fetches commerces for Geo City Pages.
* 
* @param _locationid Integer the location ID
* @param _action String The action, so far "city"
* @return Boolean
*/
function getCommerceForGeoCity(_locationid, _action)
{
	action = _action;
	var url = COMMERCE_URL;
	var data = "locationid=" + _locationid + "&action="+action;
	
	for(var i = 0; i < accommodationids.length; i++)
	{
		data += "&accommodationids[]=" + accommodationids[i];
	}
	
	$.ajax({
			   type: "GET",
			   url: url,
			   data: data,
			   success: function(msg)
			   {
					var results = eval ('(' + msg + ')');
					
					if(results['success'] == 'false')
					{
						
					}
					else
					{
						var locationcommercelist = new LocationCommerceList(results['commerce']['locationcommerces']);
						querywords = results['commerce']['querywords'];
						channel = results['commerce']['channel'];
						isdev = results['commerce']['isdev'];
						
						var locationcommerce = locationcommercelist.getLocationCommerceAt(0);
						
						if (locationcommerce) //locationcommerce is NULL is commerce is disabled on server
						{
							var packagelist = locationcommerce.getPackageList();
							
							if(packagelist)
							{
								$('#trip_commercebox_1').empty();
								$('#trip_commercebox_2').empty();
								$('#trip_commercebox_1').append(packagelist.toHTML(0, 4));
								$('#trip_commercebox_2').append(packagelist.toHTML(4, 8));
							}
	
							var aimlinks = new LocationCommerceList(results['aimlinks']['locationcommerces']);
	
							if(aimlinks != null)
							{
								for(var i = 0; i < accommodationids.length; i++)
								{
									var locationCommerce = aimlinks.getLocationCommerceByID(accommodationids[i]);
									
									if(locationCommerce != null)
									{
										var locationid = locationCommerce.getLocationId();
										var content = locationCommerce.getPackageList().getContent();
										
										$('#trip_commercelinks_' + locationid).empty();
										$('#trip_commercelinks_' + locationid).append(content.toHTML());
										content.replaceAccommThumbnail($('#trip_rates_img_' + locationid));
									}
								}
							}
						}
						else
						{
							$('#trip_commercebox_1').hide();
							$('#trip_commercebox_2').hide();
						}
					}
				}
			 });
	
	return true;
}

/**
* Fetches commerces for Geo Country Pages.
* 
* @param locationid Integer the location ID
* @return Boolean
*/
function getCommerceForGeoCountry(locationid)
{
	action = "country";
	var url = COMMERCE_URL;
	var data = "locationid=" + locationid + "&action="+action;
	
	$.ajax({
			   type: "GET",
			   url: url,
			   data: data,
			   success: function(msg)
			   {
					var results = eval ('(' + msg + ')');
					
					if(results['success'] == 'false')
					{
						
					}
					else
					{
						var locationcommercelist = new LocationCommerceList(results['commerce']['locationcommerces']);
						querywords = results['commerce']['querywords'];
						channel = results['commerce']['channel'];
						isdev = results['commerce']['isdev'];
						
						var locationcommerce = locationcommercelist.getLocationCommerceAt(0);
						
						if (locationcommerce) //locationcommerce is NULL is commerce is disabled on server
						{
							var packagelist = locationcommerce.getPackageList();
						
							if(packagelist)
							{
								$('#trip_commercebox_1').empty();
								$('#trip_commercebox_1').append(packagelist.toHTML(0, 3));
							}
						}
						else
						{
							$('#trip_commercebox_1').hide();
						}
					}
				}
			 });
	
	return true;
}

function getAdwordsCommerce(locationid, action)
{
	var url = COMMERCE_URL;
	var data = "locationid=" + locationid + "&action="+action;

	$.ajax({
			   type: "GET",
			   url: url,
			   data: data,
			   success: function(msg)
			   {
					var results = eval ('(' + msg + ')');

					if(results['success'] == 'false')
					{

					}
					else
					{
						var locationcommercelist = new LocationCommerceList(results['commerce']['locationcommerces']);
						querywords = results['commerce']['querywords'];
						channel = results['commerce']['channel'];
						isdev = results['commerce']['isdev'];

						var locationcommerce = locationcommercelist.getLocationCommerceAt(0);

						if (locationcommerce) //locationcommerce is NULL is commerce is disabled on server
						{
							var packagelist = locationcommerce.getPackageList();

							if(packagelist)
							{
								$('#trip_commercebox_1').empty();
								$('#trip_commercebox_1').append(packagelist.toHTML(0, 4));

								if ($('#trip_commercebox_2').length > 0)
								{
									$('#trip_commercebox_2').empty();
									$('#trip_commercebox_2').append(packagelist.toHTML(4, 8));
						}
							}
						}
						else
						{
							$('#trip_commercebox_1').hide();
						}
					}
				}
			 });

	return true;
}

/**
* Fetches commerces for Geo Hotel Pages.
* 
* @param accommodationid Integer the accommodationid ID
* @param action Integer The action
* @return Boolean
*/
function getCommerceForAccommodation(accommodationid, action)
{
	var url = COMMERCE_URL;
	var data = "accommodationid=" + accommodationid + "&action="+action;
	
	$('.affiliate_links').hide();
	
	$.ajax({
			   type: "GET",
			   url: url,
			   data: data,
			   success: function(msg)
			   {
					var results = eval ('(' + msg + ')');
					
					if(results['success'] == 'false')
					{
						
					}
					else
					{
						var locationcommercelist = new LocationCommerceList(results['commerce']['locationcommerces']);

						var tripcheckratesenabled = results['commerce']['tripcheckratesenabled'] == "true";
						var tripid = 0;
						querywords = results['commerce']['querywords'];
						channel = results['commerce']['channel'];
						isdev = results['commerce']['isdev'];
						
						var locationcommerce = locationcommercelist.getLocationCommerceAt(0);
						
						if (locationcommerce) //locationcommerce is NULL is commerce is disabled on server
						{
							var packagelist = locationcommerce.getPackageList();
						
							if(packagelist)
							{
								$('#trip_commercebox_1').empty();
								$('#trip_commercebox_2').empty();
								$('#trip_commercebox_1').append(packagelist.toHTML(0, 4));
								$('#trip_commercebox_2').append(packagelist.toHTML(4, 8));
								
								tripid = packagelist.getTripadvisorid();
								
								$('.hotel_aim').empty();
								
								var content = packagelist.getContent();
								$('.hotel_aim').each(function(i, e) 
								{
									$(e).append(content.toHTML(!$(e).hasClass('no_amenities')));
								});
								
								content.replaceAccommThumbnail($('.trip_rates_img'));
								
								if(tripcheckratesenabled && packagelist.getQuickCheckHotelCount() > 0)
								{
									addBookItButtons(tripid, accommodationid);
								}
							}
						}
						else
						{
							$('.trip_commercelinks').hide();
							$('#trip_commercebox_1').hide();
							$('#trip_commercebox_2').hide();
						}
						
						if(tripcheckratesenabled && hasHotelProviders)
						{
							getTripCheckRates();
						}
						else
						{
						 	$('.checkrates_container').hide();
						}

						if (results['commerce']['supplierdirect'] != null)
						{
							var supplierDirect = new SupplierDirect(results['commerce']['supplierdirect']);
							$('#hotel_official_website').html(supplierDirect.toHTML());
							$('#hotel_official_website').show();
						}
					}
				}
			 });
	
	return true;
}

/**
 * Fetches coomerce for popup under.
 * 
 * This is called when an EEW could not be found. This popup
 * is the default popunder.
 * 
 * @param accommodationid Integer The accommodation ID
 * @return Boolean
 */
function getCommerceForPopunder(accommodationid)
{
	action = "accommodation";
	var url = COMMERCE_URL;
	var data = "accommodationid=" + accommodationid + "&action="+action;
	
	$('.affiliate_links').hide();
	
	$.ajax({
			   type: "GET",
			   url: url,
			   data: data,
			   success: function(msg)
			   {
					var results = eval ('(' + msg + ')');
					
					if(results['success'] == 'false')
					{
						
					}
					else
					{
						var locationcommercelist = new LocationCommerceList(results['commerce']['locationcommerces']);
						querywords = results['commerce']['querywords'];
						channel = results['commerce']['channel'];
						isdev = results['commerce']['isdev'];
						
						var locationcommerce = locationcommercelist.getLocationCommerceAt(0);
						
						if (locationcommerce) //locationcommerce is NULL is commerce is disabled on server
						{
							var packagelist = locationcommerce.getPackageList();
						
							if(packagelist)
							{
								$('#trip_commercebox_1').empty();
								$('#trip_commercebox_1').append(packagelist.toHTML(0, 8));
							}
						}
						else
						{
							$('#trip_commercebox_1').hide();
						}
					}
				}
			 });
	
	return true;
}

/**
 * Adds bookit buttons in between in review and next
 * to the hotel description on the Geo Hotel Pages
 * 
 * @return Boolean
 */
function addBookItButtons(tripid, accommodationid)
{
	var useGreyBox = vIE == 6  ? false : true;
	//Top Check Rates Button
	var checkPricesButton = $('#bookit_main_container');
	var a = checkPricesButton.children('a');
	
	if (a.length == 1)
	{
		createBookitButton(CHECK_PRICES_BUTTON, a, tripid, accommodationid, useGreyBox);
	}
	
	$('.review_bookit a, .ta_review .bookit_button').each(function (i, e) // for each review button holder on page, one per review div
	{
		createBookitButton(BOOK_IT_BUTTON, $(e), tripid, accommodationid, useGreyBox);
	});
}

/**
 * Creates the DOM button
 * @param imgSrc String Image URL
 * @return DOM Object
 */
function createBookitButton(buttonType, buttonLink, tripid, accommodationid, useGreyBox)
{
	buttonLink.attr('title', 'Check Rates and Availability for ' + querywords);
	buttonLink.attr('href', '#');

	var logger = null;
	var data = {'accommodationid':accommodationid, 'section': getSection(), 'poolid': poolid};

	switch(buttonType)
	{
		case CHECK_PRICES_BUTTON:
			logger = new CheckRatesBookItPopupOpen(data);
			break;
		case BOOK_IT_BUTTON:
		default:
			logger = new CheckRatesCheckPricesPopupOpen(data);
			break;
	}
	
	buttonLink.data('logger', logger);
	
	/*IE6 Has problems with fixed css so for now we display the normal check rates for IE6 Users*/
	if(!useGreyBox){
		var url = "http://www.tripadvisor.com/HotelDateSearch?lnf=travellibrary&d=" + tripid;
		buttonLink.click(function ()
		{
			window.open(url,'NewWindow' + accommodationid,'toolbar=0,scrollbars=1,location=0,status=0,menubar=0,resizable=1,width=255,height=700');
			buttonLink.data('logger').Log();
			return false;
		});
	}
	else
	{
		buttonLink.click(function () 
		{
			var cRGB = new CheckRatesGB();
			$('body').append(cRGB.toHTML());
			buttonLink.data('logger').Log();
		   	return false; 
		});
	}
}

/**
 * Constructs a "Read More Reviews From Tripadvisor" link
 * 
 * @param readmorereviews JSON Link data
 * @return DOM Object
 */
function addMoreReviewLink(readmorereviews)
{
	$('.readmorereviews').empty();
	
	var span = new jQuery('<span />');
	span.addClass('ta_reviews');
	
	var a = new jQuery('<a />');
	a.attr('target', '_blank');
	a.attr('title', 'Tripadvisor Reviews of ' + querywords);
	a.addClass('trip_commercelink');
	a.addClass('no_cpu');
	a.text('View ' + readmorereviews['nbreviews']);
	a.attr('href', readmorereviews['url']);
	
	span.append(a);
	span.append(' Reviews of ' + querywords + ' on TripAdvisor');

	var span2 = new jQuery('<span />');
	span2.addClass('ta_reviews_image');
	
	var p = new jQuery('<p />');
	p.text('TripAdvisor Traveller Rating');
	span2.append(p);
	
	var a2 = new jQuery('<a />');
	a2.attr('target', '_blank');
	a2.attr('title', 'Tripadvisor Reviews of ' + querywords);
	a2.addClass('trip_commercelink');
	a2.addClass('no_cpu');
	a2.attr('href', readmorereviews['url']);
	span2.append(a2);
	
	var img = new jQuery('<img />');
	img.attr('border', '0');
	img.attr('src', readmorereviews['ratingImage']);
	a2.append(img);

	$('.readmorereviews').append(span);
	$('.readmorereviews').append(span2);
}

function LocationCommerceList(locationcommerces)
{
	this.locationCommerces = Array();

	var i = 0;
	for (obj in  locationcommerces)
	{
		this.locationCommerces[this.locationCommerces.length] = new LocationCommerce(locationcommerces[i++]);
	}
}

LocationCommerceList.prototype.getLocationCommerceByID = function(id)
{ 
	for ( var i = 0; i < this.locationCommerces.length; i++) 
	{
		if(this.locationCommerces[i].getLocationId() == id) return this.locationCommerces[i];
	}
	
	return null;
};
LocationCommerceList.prototype.getLocationCommerceAt = function(index) 
{ 
	if(index >=0 && index <= this.locationCommerces.length - 1)
	{
		return this.locationCommerces[index];
	}
	else return null;
};

LocationCommerceList.prototype.getNbCommercesLinks = function()
{
	var nb = 0;
	
	for (locationcommerce in this.locationCommerces)
	{
		nb += this.locationCommerces[ locationcommerce ].getNbCommercesLinks();
	}
	
	return nb;
}

LocationCommerceList.prototype.hasCommerce = function()
{
	return this.getNbCommercesLinks() > 0;
}

function LocationCommerce(locationcommerce)
{
	this.locationid = locationcommerce['locationid'];
	this.triplocationid = locationcommerce['triplocationid'];
	this.packagelist = new PackageList(locationcommerce['packagelist'], this);
}

LocationCommerce.prototype.getLocationId = function() {return this.locationid;};
LocationCommerce.prototype.getTripLocationId = function() {return this.triplocationid;};
LocationCommerce.prototype.getPackageList = function() {return this.packagelist;};
LocationCommerce.prototype.toHTML = function()
{
	return this.getPackageList().toHTML(0,8);
};

LocationCommerce.prototype.getNbCommercesLinks = function()
{
	return this.packagelist.getNbCommercesLinks();
}

function PackageList(packagelist, _parent)
{
	this.showcascadesearch = packagelist['showcascadesearch'];
	this.quickcheckhotelcount = packagelist['quickcheckhotelcount'];
	this.count = packagelist['count'];
	this.tripadvisorid = packagelist['tripadvisorid'];
	this.matchingoffers = new Offers(packagelist['matchingoffers']);
	this.nonMatchingoffers = new Offers(packagelist['nonMatchingoffers']);
	this.parent = _parent;
	
	this.content = new Content(packagelist['content'], this);

	hasTripAdvisorAds = this.matchingoffers.getOffers().length > 0;
}

PackageList.prototype.getShowCascadeSearch = function() {return this.showcascadesearch;};
PackageList.prototype.getQuickCheckHotelCount = function() {return this.quickcheckhotelcount;};
PackageList.prototype.getCount = function() {return this.count;};
PackageList.prototype.getTripadvisorid = function() {return this.tripadvisorid;};
PackageList.prototype.getMatchingOffers = function() {return this.matchingoffers;};
PackageList.prototype.getNonMatchingOffers = function() {return this.nonMatchingoffers;};
PackageList.prototype.getContent = function() {return this.content;};
PackageList.prototype.getLocationId = function() {return this.parent.getLocationId();};

PackageList.prototype.getNbCommercesLinks = function()
{
	return this.getMatchingOffers().getNbCommercesLinks();
}

PackageList.prototype.toHTML = function(start, stop)
{
	var div = new jQuery('<div />');
	div.addClass("trip_commercebox");
	
	var dl = new jQuery('<dl />');
	div.append(dl);
	
	if (this.matchingoffers != null && this.matchingoffers.getOffer(0) != null)
	{
		var offer = this.matchingoffers.getOffer(0);
		var dt = new jQuery('<dt />');

		if(isdev) dt.append("<em>("+channel+")</em>");
		
		if (offer.isTripAdvisor() && this.getQuickCheckHotelCount() > 0)
		{
			var url = "http://www.tripadvisor.com/HotelDateSearch?lnf=travellibraryhds&d=" + this.getTripadvisorid();
			var a = new jQuery('<a />');
			a.addClass("cpc_box_link");
			a.addClass("no_cpu");
			a.attr('href', url);
			a.attr('target', "_blank");
			a.attr('title', "Click here for best prices on " + accommodationName);
			
			a.append(a.attr('title'));

			var data = {'accommodationid':getAccommodationId(), 'section': getSection(), 'poolid': poolid};
			var logger = new CheckRatesCPCPopupOpen(data);
			
			a.data('logger', logger);
			
			a.click(function () 
			{ 
				openCheckRateWindow(url);
				$(this).data('logger').Log();
			   	return false; 
			});
			
			dt.append(a);
		}
		else
		{
			dt.append(querywords);
		}
		
		dl.append(dt);
	}
	
	dl.append(this.getMatchingOffers().toHTML(start, stop));
	
	var dd = new jQuery('<dd />');
	dd.addClass('trip_commercesponsered');
	dd.append("Sponsored links");
	dl.append(dd);
	
	return div;
};

function Offers(offers)
{
	this.rootlocationid = offers['rootlocationid'];
	this.rootlocationname = offers['rootlocationname'];
	this.geolocationid = offers['geolocationid'];
	this.geolocationname = offers['geolocationname'];
	this.nbgoogleads = offers['nbgoogleads'];
	this.nbtripadvisorads = offers['nbtripadvisorads'];
	
	this.offers = new Array();
	
	var i = 0;
	for (obj in offers['offers'])
	{
		this.offers[this.offers.length] = new Offer(offers['offers'][i], i);
		i++;
	}
}

Offers.prototype.getRootLocationId = function() {return this.rootlocationid;};
Offers.prototype.getRootLocationName = function() {return this.rootlocationname;};
Offers.prototype.getGeoLocationId = function() {return this.geolocationid;};
Offers.prototype.getGeoLocationName = function() {return this.geolocationname;};
Offers.prototype.getNbGoogleOffers = function() {return this.nbgoogleads;};
Offers.prototype.getNbTripAdvisorOffers = function() {return this.nbtripadvisorads;};
Offers.prototype.getOffers = function() {return this.offers;};
Offers.prototype.getOffer = function(index) {return this.offers[index];};

Offers.prototype.getNbCommercesLinks = function()
{
	return this.getNbGoogleOffers() + this.getNbTripAdvisorOffers();
}

Offers.prototype.toHTML = function(start, stop)
{
	var dd = new jQuery('<dd />');
	
	for (var i = start; i < stop; i++)
	{
		if (this.getOffer(i) != null)
			dd.append(this.getOffer(i).toHTML());
	}
	
	return dd;
};

function Offer(offer, index)
{
	if(!offer) return;

	this.url = offer['url'];
	this.status = offer['status'];
	this.offerlocationname = offer['offerlocationname'];
	this.offerLocationId = offer['offerLocationId'];
	this.parentofferlocationname = offer['parentofferlocationname'];
	this.parentofferlocationid = offer['parentofferlocationid'];
	this.teaser = offer['teaser'];
	this.subteaser = offer['subteaser'];
	this.subteaser2 = offer['subteaser2'];
	this.vendor = offer['vendor'];
	this.issmartdealhotel = offer['issmartdealhotel'];
	this.position = offer['position'];
	this.source = offer['source'];
	this.index = index;
}

Offer.prototype.getURL = function() {return this.url;};
Offer.prototype.getStatus = function() {return this.status;};
Offer.prototype.getOfferLocationName = function() {return this.offerlocationname;};
Offer.prototype.getOfferLocationId = function() {return this.offerLocationId;};
Offer.prototype.getParentOfferLocationName = function() {return this.parentofferlocationname;};
Offer.prototype.getParentOfferLocationId = function() {return this.parentofferlocationid;};
Offer.prototype.getTeaser = function() {return this.teaser;};
Offer.prototype.getSubTeaser = function() {return this.subteaser;};
Offer.prototype.getSubTeaser2 = function() {return this.subteaser2;};
Offer.prototype.getVendor = function() {return this.vendor.toLowerCase();};
Offer.prototype.getIsSmartDealHotel = function() {return this.issmartdealhotel;};
Offer.prototype.getPosition = function() {return this.position;};
Offer.prototype.getSource = function() {return this.source;};
Offer.prototype.isGoogle = function() {return this.source == "Google";};
Offer.prototype.isTripAdvisor = function() {return this.source == "Tripadvisor";};
Offer.prototype.toHTML = function()
{
	var ul = new jQuery('<ul />');
	
	var li = new jQuery('<li />');
	
	if (this.isGoogle()) li.addClass('google_ad');
	if (this.isTripAdvisor()) li.addClass('tripadvisor_ad');
	
	var span = new jQuery('<span />');
	var a = new jQuery('<a />');
	
	var url = this.getURL();
	a.addClass('cpc_box_link');
	a.addClass("no_cpu");
	a.attr('target', "_blank");
	a.attr('href', url);

	var data = {'accommodationid':getAccommodationId(), 'section': getSection(), 'provider': this.isTripAdvisor() ? "tripadvisor" : "google",
			'poolid': poolid, 'position': this.index, 'vendor': this.getVendor(), 'locationid': window.locationid};

	var logger = new CpcOpen(data);
	
	a.data('logger', logger);
	
	var index = this.index;
	a.click(function () 
	{ 
		openCommerceWindow(url, "NewWindow" + index);
		$(this).data('logger').Log();
	   	return false; 
	});
	
	if (this.isTripAdvisor())
	{
		a.mouseover(function () 
		{ 
			 window['status'] = url;
		   	return false; 
		});
	}
	else if (this.isGoogle())
	{
		var vendor = this.getVendor();
		
		a.mouseover(function () 
		{ 
			 window['status'] = vendor;
		   	return false; 
		});
	}
	
	var b = new jQuery('<b />');
	
	if (this.isTripAdvisor())
	{
		b.append(this.getOfferLocationName());
		b.append(": ");
	}
	
	b.append(this.getTeaser());
	b.append("<br />");
	
	var span2 = new jQuery('<span />');
	
	span2.append(this.getSubTeaser() + " " + this.getSubTeaser2());
	
	a.append(b);
	if(isdev) a.append("<em>("+this.getSource()+")</em>");
	a.append(span2);
	
	if (this.isGoogle()) a.append("<br />");

	var cite = new jQuery('<cite />');
	
	if (this.isTripAdvisor()) cite.append("www.");
	
	cite.append(this.getVendor());
	a.append(cite);

	span.append(a);
	li.append(span);
	
	ul.append(li);
	
	return ul;
};

SupplierDirect.prototype = new Offer;

function SupplierDirect(offer, index)
{
	this.inheritFrom = Offer;
	this.inheritFrom(offer, index);
}
SupplierDirect.prototype.toHTML = function()
{
	var span = new jQuery('<span />');
	
	var strong = new jQuery('<strong />');
	strong.html('Official Website: ')
	span.append(strong);

	var url = this.getURL();

	var a = new jQuery('<a />');
	a.html(url ? this.getOfferLocationName() : 'n/a');
	a.attr('href', url);
	a.attr('target', '_blank');
	a.addClass("no_cpu");


	a.click(function ()
	{
		openCommerceWindow(url, "NewWindowOfficialWebsite");
	   	return false;
	});

	span.append(a);

	return span;
}

function Content(content, _parent)
{
	if(content != null)
	{
		this.amenity = content['amenity'];
		this.map = content['map'];
		this.picture = content['picture'];
		this.thumbnail = content['thumbnail'];
		this.virtual = content['virtual'];
		this.video = content['video'];
		this.parent = _parent;
	}
}

Content.prototype.getAmenityURL = function() {return this.amenity;};
Content.prototype.getMapURL = function() {return this.map;};
Content.prototype.getPictureURL = function() {return this.picture;};
Content.prototype.getThumbnailURL = function() {return this.thumbnail;};
Content.prototype.getVirtualURL = function() {return this.virtual;};
Content.prototype.getVideoURL = function() {return this.video;};
Content.prototype.getLocationId = function() {return this.parent.getLocationId();};

Content.prototype.replaceAccommThumbnail = function(target) 
{
	var pictureURL = this.getPictureURL();
	var thumbnailURL = this.getThumbnailURL();

	var accommid = this.getLocationId(); 
	
	if (thumbnailURL != "")
	{
		var img = new jQuery('<img />');
		img.attr('src', thumbnailURL != "" ? thumbnailURL : localThumbnailURL);
		img.attr('width', '150');
		img.attr('height', '101');
		img.attr('border', '0');
		img.attr('alt', querywords + ' Holiday Reviews');

		/* If loading remote thumbnail image fails, we put but our local thumbnail */
		img.error(function ()
		{
			img.attr('src', localThumbnailURL);
			return false;
		});
		
		$(target).empty();

		if (pictureURL != "")
		{
		    var data = {'accommodationid': accommid, 'section': getSection(), 'poolid': poolid, 'aimtype': "hotelphoto"};
		    var logger = new AIMOpen(data);

		    /* Lets keep a reference to our local thumbnail path. Sometimes Expedia's (or else) are broken */
		    var DEFAULT_THUMBNAIL_PLACEHOLDER = '/images/300X225Nophoto.gif';
		    var localThumbnailImages = target.find('img');
		    var localThumbnailURL = localThumbnailImages.length > 0 ? $(localThumbnailImages[0]).attr('src') : DEFAULT_THUMBNAIL_PLACEHOLDER;

		    var a = new jQuery('<a />');
		    a.addClass('trip_commercelink');
		    a.addClass('no_cpu');
		    a.attr('href', pictureURL);
		    a.attr('target', '_blank');
		    a.attr('title', 'View the ' + querywords + " Photographs");

		    a.data('logger', logger);

		    a.click(function ()
		    {
			    openCommerceWindow(pictureURL, "NewWindow");
			    $(this).data('logger').Log();
			    return false;
		    });

		    
		    a.append(img);
		    $(target).append(a);

		    var data = {'accommodationid': accommid, 'section': getSection(), 'poolid': poolid, 'aimtype': "morephotos"};
		    var logger = new AIMOpen(data);

		    var morePhotosa = jQuery('<a />');
		    morePhotosa.addClass('morephotos');
		    morePhotosa.addClass('no_cpu');
		    morePhotosa.attr('id','commerce_aim_morephotos');
		    morePhotosa.attr('href', pictureURL);
		    morePhotosa.attr('target', '_blank');
		    morePhotosa.attr('title', "View more photos");
		    morePhotosa.append("More Photos");
		    morePhotosa.data('logger', logger);

		    morePhotosa.click(function ()
		    {
			    openCommerceWindow(pictureURL, "NewWindow");
			    $(this).data('logger').Log();
			    return false;
		    });

		    $(target).append(morePhotosa);
		}
		else
		{
		    $(target).append(img);
		}
	}
};

Content.prototype.toHTML = function(with_amenities)
{
	var ul = new jQuery('<div />');
	
	var accommid = this.getLocationId();
	
	var data = {'accommodationid': accommid, 'section': getSection(), 'poolid': poolid};
	var logger = new AIMOpen(data);
	
	var purl = this.getPictureURL();
	if(purl)
	{
		var li = new jQuery('<li />');
		
		var a = new jQuery('<a />');
		a.addClass('trip_commercelink');
		a.addClass('no_cpu'); 
		a.addClass('aim_hotel_photos'); 
		a.attr('href', purl);
		a.attr('target', '_blank');
		a.attr('title', "Hotel Photographs");
		a.text('Hotel Photos');
		
		a.data('logger', logger);
		
		a.click(function ()
		{ 
			openCommerceWindow(purl, "NewWindow1");
			data['aimtype'] = "photos";
			$(this).data('logger').Log();
		   	return false; 
		});
		
		ul.append(a);
	}
	
	var murl = this.getMapURL();
	if(murl)
	{
		var li = new jQuery('<li />');
		
		var a = new jQuery('<a />');
		a.addClass('trip_commercelink');
		a.addClass('no_cpu');
		a.addClass('aim_hotel_map');
		a.attr('href', murl);
		a.attr('target', '_blank');
		
		a.attr('title', 'See Hotel on Map');
		a.text('See Hotel on Map');
		a.data('logger', logger);

		a.click(function () 
		{ 
			openCommerceWindow(murl, "NewWindow2");
			data['aimtype'] = "map";
			$(this).data('logger').Log();
		   	return false; 
		});
		
		ul.append(a);
	}

	if (with_amenities)
	{
		var aurl = this.getAmenityURL();
		if(aurl)
		{
			var li = new jQuery('<li />');

			var a = new jQuery('<a />');
			a.addClass('trip_commercelink');
			a.addClass('no_cpu');
			a.addClass('aim_hotel_amenities');
			a.attr('href', aurl);
			a.attr('target', '_blank');
			a.attr('Amenities');
			a.text('Amenities');

			a.data('logger', logger);

			a.click(function ()
			{
				openCommerceWindow(aurl, "NewWindow3");
				data['aimtype'] = "amenities";
				$(this).data('logger').Log();
				return false;
			});

			ul.append(a);
		}
	}
	
	var vurl = this.getVirtualURL();
	if(vurl)
	{
		var li = new jQuery('<li />');
		
		var a = new jQuery('<a />');
		a.addClass('trip_commercelink');
		a.addClass('no_cpu');
		a.attr('href', vurl);
		a.attr('target', '_blank');
		a.attr('title', 'Virtual Tour');
		a.text('Virtual Tour');
		
		a.data('logger', logger);
		
		a.click(function () 
		{ 
			openCommerceWindow(vurl, "NewWindow4");
			data['aimtype'] = "virtualtour";
			$(this).data('logger').Log();
		   	return false; 
		});
		
		ul.append(a);
	}
	
	return ul;
};

PhotoContent.prototype = new Content;
PhotoContent.prototype.constructor = PhotoContent;

function PhotoContent(content, _parent)
{
	this.inheritFrom = Content;
	this.inheritFrom(content, _parent);
}

PhotoContent.prototype.toHTML = function()
{
	var purl = this.getPictureURL();
	if(purl)
	{
		var a = new jQuery('<a />');
		a.addClass('trip_commercelink');
		a.addClass('no_cpu');
		a.attr('href', purl);
		a.attr('target', '_blank');
		a.attr('title', "Professional Photos");
		a.text('Professional Photos >');
		
		a.click(function () 
		{ 
			openCommerceWindow(purl, "NewWindow1");
		   	return false; 
		});
		
		return a;
	}
	
	return null;
};

/**
 * Opens a commerce popup, from the ICR
 * @param url The commerce URL
 * @param name The window name
 * @return Boolean false
 */
function openCommerceWindow(url, name)
{
	window.open(url, name, makeOptions());
	return false;
}

/**
 * Opens the check rate window
 * @param url The CheckRate URL
 * @return Boolean false
 */
function openCheckRateWindow(url)
{
	window.open(url,'NewWindow','toolbar=0,scrollbars=1,location=0,status=0,menubar=0,resizable=1,width=255,height=700');
	return false;
}

/**
 * Get ICR for Traveller's photo window
 * @return void
 */
function getTripCheckRatesPhoto()
{
	var url = "/ICR.html";
	var data =  "accommodationid=" + accommodationid;
	
	$.ajax({
	   type: "POST",
	   url: url,
	   data: data,
	   success: function(msg)
	   {
	   		$('.checkrates_container').empty();
	   		$('.checkrates_container').append(msg);
	   		$('.checkrates_container').show();
	   		
	   		window.resizeTo(815,861);
	   		
	   		return true;
	   }
	 });
}
