function preloadImage(src) {
	var tmpImage = new Image();
	tmpImage.src = src;
}
function swapImage(id, src) {
	$(id).attr("src", src);
}

function popupWindow(e){
	e.stop();
	window.open(e.target.href, e.target.title, 'width=1000,scrollbars=1');
}

$(document).ready(function() {

	var expanderOdd = false;
	// check if we have any anchor in the url, and if it matches an id.
	var hasHash = location.hash.length > 0;
	$('div[class="expander"]').each(function(index) {
		if (expanderOdd) {
			$(this).addClass("expander-odd");
		}
		$(this).find('a[class="expander-anchor"]').click(function(e) {
			e.preventDefault();
			$(this).parent().next().slideToggle();
			$(this).parent().parent().toggleClass("expander-open");
			return false;	
		});
		expanderOdd = !expanderOdd;
		
		if (hasHash) {
			if (location.hash == ("#"+$(this).attr("id"))) {
				$(this).toggleClass("expander-open");
				$(this).find(".expander-content").toggle();
			}
		}
	});
	
});

function calculatePrice(startDate, nights, pricePerNight, monthLookup) {
	var now = new Date();
	var fromDate = startDate;
	var totalNights = nights || 2;
	var oneDayMS = 24.0 * 60.0 * 60.0 * 1000.0;

	if (fromDate == null) {
		fromDate = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1, 12, 0, 0, 0);
	} else {
		// Make sure we are on the same hour.
		fromDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), 12, 0, 0, 0);
	}
	// End date.
	var toDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate()+totalNights, 12, 0, 0, 0);
	// Extract day numbers.
	var fromDateDay = Math.floor(fromDate.getTime() / oneDayMS);
	var toDateDay = Math.floor(toDate.getTime() / oneDayMS);

	$(".price_data_json").each(function(i, item) { 
		var myData = $.parseJSON(item.innerHTML);
		var total = 0;
		var discount = 0;
		var error = false;
		var foundDays = 0;
		var lookingForCurrentDay = fromDateDay;
		var info = new Array();
				
		for (var i=0; i<myData.length; i++) {
			var r = myData[i];
			var tmpFromDate = new Date(parseInt(r.from.substr(0,4), 10), parseInt(r.from.substr(5,2),10)-1, parseInt(r.from.substr(8,2),10), 12, 0, 0, 0);
			var tmpToDate = new Date(parseInt(r.to.substr(0,4),10), parseInt(r.to.substr(5,2),10)-1, parseInt(r.to.substr(8,2),10), 12, 0, 0, 0);
			var tmpFromDay = Math.floor(tmpFromDate.getTime() / oneDayMS);
			var tmpToDay= Math.floor(tmpToDate.getTime() / oneDayMS);
			var tmpPrice = 0;
			var explanationStartDay = 0;
			var explanationEndDay = 0;
			var tmpCurrentDay = 0;
			
			for (var i_day=tmpFromDay; i_day<tmpToDay; i_day++) {
				if (i_day == lookingForCurrentDay) {
					if (tmpPrice == 0) {
						explanationStartDay = i_day;
					}
					tmpPrice += r.rate;
					tmpCurrentDay = i_day;
					foundDays++;
					if (lookingForCurrentDay >= toDateDay-1) break;
					lookingForCurrentDay++;
				} else if (i_day >= fromDateDay && i_day < toDateDay) {
					error = true;
					break;
				}
			}
			if (error) break;
			if (foundDays > 0) {
				explanationEndDay = tmpCurrentDay+1;
				
				// Calculate discount.
				var tmpDiscountPercentage = 0;
				for (var i_disc=0; i_disc<r.discounts.length; i_disc++) {
					if (totalNights >= r.discounts[i_disc].minNights && r.discounts[i_disc].discount > tmpDiscountPercentage) {
						tmpDiscountPercentage = r.discounts[i_disc].discount;
					}
				}
				// Add to the pot.
				var tmpDiscountPrice = (tmpPrice * ((100-tmpDiscountPercentage)/100)) - tmpPrice;
				discount += Math.abs(tmpDiscountPrice);
				total += tmpPrice;
				
				// debug.
				if (tmpCurrentDay != 0) {
					var eStartDate = new Date(explanationStartDay * oneDayMS);
					var eEndDate = new Date(explanationEndDay * oneDayMS);
					var str = "from:" + eStartDate.getFullYear()+"-"+(eStartDate.getMonth()+1)+"-"+eStartDate.getDate();
					str += " to:" + eEndDate.getFullYear()+"-"+(eEndDate.getMonth()+1)+"-"+eEndDate.getDate();
					str += " totalNights: "+totalNights;
					str += " total:" + tmpPrice;
					str += " discount("+tmpDiscountPercentage+"%):";
					str += tmpDiscountPrice;
					str += " grandTotal:";
					str += (tmpPrice-Math.abs(tmpDiscountPrice));
					info.push(str);
				}
			}
		}

		if (foundDays != totalNights) {
			error = true;
		}
		
		// Update.
		if (!error)	{
			var grandTotal = Math.round(total - discount);
			if (pricePerNight === true) {
				var perNight = Math.round(grandTotal / totalNights);
				$(item).parent().find(".price .rate").text(perNight);
			} else {
				var parent = $(item).parent();
				parent.find(".nights-count").text(totalNights);
				parent.find(".price .rate").text(grandTotal);				
				parent.find(".dates-from").text(fromDate.getDate() + " " + monthLookup(fromDate.getMonth()));
				parent.find(".dates-to").text(toDate.getDate() + " " + monthLookup(toDate.getMonth()));
			}
			
//			console.log("---------");
//			console.log(info.join("\n"));
//			console.log("Grand Total: "+grandTotal);
//			console.log("*********");
			
		} else {
			$(item).parent().find(".price .rate").text("N/A");
		}
	});
}	
