var popups = new Popups();
var xPos = 300;
var yPos = 300;

/**
* Options for Inline CheckRates (ICR) popups
* 
* @return string the options
*/
function makeICROptions(xPos, yPos)
{
    return "toolbar=1,resizable=1,menubar=1,location=1,status=1,scrollbars=3,width=780,height=550,screenX="+xPos+",screenY="+yPos+",left="+xPos+",top="+yPos;
}

/**
 * Open Commerce popups
 * @param source The DIV element from which the click originated
 * @return void
 */
function openPopups(source)
{
	popups.resetWindows();
	
	if(greyboxDisplayed && "checkrates_hidden" != source.attr('id')) return false;
	
	/**
	 * for each selected checkbox of the ICR form, we
	 * try to open a popup.
	 */
	source.find('input[type=checkbox]:checked').each(function (i, e) {
			var inDate = source.find('input[name=checkin_date]').val();
			var inDateElts = inDate.split("/");
			
			var nbAdults = source.find('select[name=adults]').val();
			
			var outDate = source.find('input[name=checkout_date]').val();
			var outDateElts = outDate.split("/");
			
			//The popup URL
			
			var url = "";
			
			url += "http://www.tripadvisor.com";
	
			/**
			* If booking dates are next year (d.getFullYear() != inDateElts[2])
			* then the trip ICR API takes in the year appended to the month
			*/
			var d = new Date();
			var inMonth = (d.getFullYear() == inDateElts[2]) ? inDateElts[1] : inDateElts[1] + " " + inDateElts[2];
			var outMonth = (d.getFullYear() == outDateElts[2]) ? outDateElts[1] : outDateElts[1] + " " + outDateElts[2];
			
			url += $(e).val();
			url += "&inMonth=" + inMonth + "&inDay=" + inDateElts[0];
			url += "&outMonth=" + outMonth + "&outDay=" + outDateElts[0];
			url += "&adults=" + nbAdults;
			
			var provider = $(e).attr('provider');
			var position = $(e).attr('position');

			var data = {'accommodationid': accommodationid, 'provider': provider, 'position': position,
					'section': getSection(),  'poolid': poolid};

			var logger = new CheckRatesProviderOpen(data);

			logger.Log();
			
			/**
			 * If a popup blocker is enabled, usually only the first window opens up.
			 * The other tries return null.
			 */
			var winOpen = window.open(url, "NewWindow" + i, makeICROptions(xPos, yPos));
			if(winOpen == null)
			{			
				icrGreyBox = new TlibICRGreyBox(source);
				$('body').append(icrGreyBox.toHTML());
				return false;
			}
			else //adds popup to the list of opened child windows
			{
				popups.addPopup('vendor_blocked_'+i, winOpen);
			}
			
			//shifts windows slightly to the lower left corner
			xPos += 30;
			yPos += 30;

                        return true;
	});
	
	return false;
}

/**
 * Opens Commerce Popup via the Grey overlay box.
 * 
 * Does almost the same thing as openPopups()
 * except for 1 window only, and it also takes care of greying 
 * out the opened links. 
 * 
 * @param link Popup URL
 * @param source The DIV element from which the click originated
 * @return Boolean True if popup opened
 */
function openBlockedPopup(link, source)
{
	var id = $(link).attr('id');
	var imageId = '#' + id + '_img';
	
	var inDate = source.find('input[name=checkin_date]').val();
	var inDateElts = inDate.split("/");
		
	var nbAdults = source.find('select[name=adults]').val();
		
	var outDate = source.find('input[name=checkout_date]').val();
	var outDateElts = outDate.split("/");
		
	var url = "";
	
	if (!logCommerceEnabled) url += "http://www.tripadvisor.com";
	
	url += $(link).attr('name');
	
	/**
	* If booking dates are next year (d.getFullYear() != inDateElts[2])
	* then the trip ICR API takes in the year appended to the month
	*/
	var d = new Date();
	var inMonth = (d.getFullYear() == inDateElts[2]) ? inDateElts[1] : inDateElts[1] + " " + inDateElts[2];
	var outMonth = (d.getFullYear() == outDateElts[2]) ? outDateElts[1] : outDateElts[1] + " " + outDateElts[2];
	
	url += "&inMonth=" + inMonth + "&inDay=" + inDateElts[0];
	url += "&outMonth=" + outMonth + "&outDay=" + outDateElts[0];
	url += "&adults=" + nbAdults;
	
	url += "&accommodationid=" + getAccommodationId();
	url += "&position=" + $(link).attr('position');
	url += "&section=" + getSection();
	url += "&logaction=checkratesprovideropen";

	popups.focusAll(); // brings all windows to the front
	
	var p = popups.findPopup(id);
	
	if(p == null || !p.isValid())
	{	
		var winOpen = window.open(url, "NewWindow" + popups.getNbOpenedPopups() , makeICROptions(xPos, yPos));
		popups.addPopup(id, winOpen);
		
		if (!$(link).data('alreadyVisited'))
		{
			$(link).css('color', '#f0f0f0');
			$(imageId).animate({opacity: "0.4"}, 500);
		}
		else $(link).data('alreadyVisited', true);
	}

	popups.focus(id); //new popup in front
	
	xPos += 30;
	yPos += 30;
	
	/*
	 * when all the requested popups have been opened, we remove the overlay
	 */
	if( popups.getNbOpenedPopups() >= source.find('input[type=checkbox]:checked').length ) 
	{
		var closeGB = icrGreyBox.closeGreyBox();
		closeGB();
	}
	return true;
}

/**
 * Holders for opened popups.
 * 
 * First version os this was a simple associative array of references to
 * windows. IE6/7 did manage to not like it.
 * 
 * This holder is therefore not associative and less optimum (assuming
 * associative arrays in IE, if they work, are coded efficiently). 
 * However, it contains at most 8 elements, that's small enough to not care.
 * 
 * @return void
 */
function Popups()
{
	this.popups = new Array();
}

/**
 * Adds a popup
 * 
 * @param _id string The popup ID
 * @param _w Object A reference to the window object
 */
Popups.prototype.addPopup = function(_id, _w) 
{
	var p = this.findPopup(_id);
	
	if (p == null)//add
	{
		p = new Popup(_id, _w);
		this.popups[this.popups.length] = p;
	}
	else //replace
	{
		p.setWindow(_w);
	}
};

/**
 * Loops thru the array of windows and
 * looks for that with ID _id
 * 
 * @param string _id The ID
 * @return Popup
 */
Popups.prototype.findPopup = function(_id) 
{
	for(var i = 0; i < this.popups.length; i++)
	{
		if (this.popups[i].getId() == _id) return this.popups[i]; 
	}
	
	return null;
};

/**
 * Brings all popups to front
 */
Popups.prototype.focusAll = function() 
{
	for(var i = 0; i < this.popups.length; i++)
	{
		if (	this.popups[i] != null 
				&& this.popups[i].isValid())
		{
			this.popups[i].getWindow().focus(); 
		}
	}
};

/**
 * Returns the number of opened windows
 * 
 * @return int The number of popups
 */
Popups.prototype.getNbOpenedPopups = function() 
{
	var nb = 0;
	for(var i = 0; i < this.popups.length; i++)
	{
		if (	this.popups[i] != null 
				&& this.popups[i].isValid()) 
			nb++; 
	}
	return nb;
};

/**
 * Brings a popup to the front.
 * 
 * @param string _id The popup ID
 */
Popups.prototype.focus = function(_id) 
{
	var p = this.findPopup(_id);
	
	if (p != null && p.getWindow() != null)
	{
		p.getWindow().focus();
	}
};

/**
 * Returns the list of popups
 * 
 * @return <Popup>
 */
Popups.prototype.getPopups = function() 
{
	return this.popups;
};

/**
 * A popup holder
 * 
 * @param _id string The popup ID
 * @param _w Object A reference to the window object
 */
function Popup(_id, _w)
{
	this.id = _id;
	this.w = _w;
}

/**
 * Returns the ID
 * 
 * @return string The ID
 */
Popup.prototype.getId = function() 
{
	return this.id;
};

/**
 * Return the window object
 * 
 * @return The window
 */
Popup.prototype.getWindow = function() 
{
	return this.w;
};

/**
 * Sets the window
 * 
 * @param _w Object A reference to the window object
 */
Popup.prototype.setWindow = function(_w) 
{
	this.w = _w;
};

/**
 * Sets the ID
 * 
 * @param _id string The popup ID
 */
Popup.prototype.setId = function(_id) 
{
	this.id = _id;
};

/**
 * Tests whether a popup is valid.
 * 
 * A popups is valid if its reference is not null
 * and the window had not been closed.
 * 
 * @return boolean
 */
Popup.prototype.isValid = function(_id) 
{
	return this.w != null && !this.w.closed; 
};

/**
 * Resets the array of popups
 */
Popups.prototype.resetWindows = function() 
{
	 this.popups = new Array();
};

/**
 * Updates the arrival date
 * @param div DOM The source DIV
 * @return void
 */
function updateOutDate(date, intputElement)
{
	var checkratesContainer = intputElement.input.parents('div.checkrates_container');
	
	var inDateElts = date.split("/");
	inDate = new Date();
	inDate.setFullYear(inDateElts[2]);
	inDate.setMonth((inDateElts[1]) - 1);
	inDate.setDate(inDateElts[0]);

	var outDateElts = checkratesContainer.find('input[name=checkout_date]').val().split("/");
	outDate = new Date();
	outDate.setFullYear(outDateElts[2]);
	outDate.setMonth((outDateElts[1]) - 1);
	outDate.setDate(outDateElts[0]);

	if (inDate.getTime() >= outDate.getTime()) // arrival date after departure date
	{
		//let's change arrival date to inDate + 2 days
		var newOutDate = new Date();
		newOutDate.setFullYear(inDateElts[2]);
		newOutDate.setMonth(inDateElts[1] - 1);
		newOutDate.setDate(parseInt(inDateElts[0]) + 2);
		
		checkratesContainer.find('input[name=checkout_date]').datepicker("setDate", newOutDate);
	}
}

/**
* Updates the departure date
* @param div DOM The source DIV
* @return void
*/

function updateInDate(date, intputElement)
{
	var checkratesContainer = intputElement.input.parents('div.checkrates_container');
	
	var outDateElts = date.split("/");
	outDate = new Date();
	outDate.setFullYear(outDateElts[2]);
	outDate.setMonth((outDateElts[1]) - 1);
	outDate.setDate(outDateElts[0]);
	
	var inDateElts = checkratesContainer.find('input[name=checkin_date]').val().split("/");
	inDate = new Date();
	inDate.setFullYear(inDateElts[2]);
	inDate.setMonth(inDateElts[1] - 1);
	inDate.setDate(inDateElts[0]);

	if (inDate.getTime() >= outDate.getTime()) // arrival date after departure date
	{
		//let's change departure date to outDate - 2 days
		var newInDate = new Date();
		newInDate.setFullYear(outDateElts[2]);
		newInDate.setMonth((outDateElts[1]) - 1);
		newInDate.setDate(outDateElts[0] - 2);
		
		checkratesContainer.find('input[name=checkin_date]').datepicker("setDate", newInDate);
	}
}
