var bookedDates = [];
var calCount = 0;
var calFx = {};
var calFxCount = 0;

window.addEvent('domready', function(){
	var main = $('main');
	
	//multibox
	new multiBox('mb', {overlay: new overlay(), openFromLink:false});
	
	if(main.hasClass('map')){
		//GSearch.setOnLoadCallback(initialize);
		initialize(main);
	}
	
	if(main.hasClass('video')){
		new Swiff('_common/swf/player.swf', {
			id: 'player',
			container: main,
			width: '100%',
			height: '100%',
			params: {
				wmode: 'transparent',
				bgcolor: '#2d3239'
			}
		});
	}
	
	if($('calendarHolder')){
		new Request({
			url:'/_common/data/proxy.php?url=http://www.google.com/calendar/ical/sarnbadrig@googlemail.com/public/basic.ics',
			onSuccess: function(txt, xml){
				//console.log(txt);
				var response = txt.split('\n');
				//console.log(response);
				response.each(function(el,i){

					var a = el.split(';');
					if(a[0] == 'DTSTART'){
						var bs = a[1].split(':');
						//var ss = bs[1].substr(0,4)+','+bs[1].substr(4,2)+','+bs[1].substr(6,2);
						//var dts = new Date(ss);
						//console.log(bs[1]);
						var dts = new Date(bs[1].substr(0,4), Number(bs[1].substr(4,2))-1, bs[1].substr(6,2));
						//console.log(dts);

						var be = response[i+1].split(':');
						//var se = be[1].substr(0,4)+','+be[1].substr(4,2)+','+be[1].substr(6,2);
						//var dte = new Date(se);
						var dte = new Date(be[1].substr(0,4), Number(be[1].substr(4,2))-1, be[1].substr(6,2));
						//alert(dte);
						do {
							bookedDates.push(dts.toString());
							//console.log(dts);
							dts = getNextDate(dts);
						} while (dts < dte);

					}
				});
				//console.log(bookedDates);
				$('loading').destroy();
				createCalendar(calCount++);
				createCalendar(calCount++);
				createCalendar(calCount++);
				createCalendar(calCount++, true);
			}
		}).send();
		
		$('calendarControls').setStyle('display', 'block');
		$('next').addEvent('click', function(e){
			e = new Event(e);
			e.stop();
			nextCalendars();
		});
		$('prev').addEvent('click', function(e){
			e = new Event(e);
			e.stop();
			prevCalendars();
		}).setStyle('display', 'none');
		
		calFx = new Fx.Tween($('calendarHolder'), {link:'cancel', duration: 1000});
	}
});

function getNextDate(date){
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();
	
	var newDate = new Date(y, m, (d+1));
	return newDate;
}

window.addEvent('unload', function(){
	if($('main').hasClass('map')){GUnload();}
});


function initialize(container) {
	if (GBrowserIsCompatible()) {
		
		var iconRed = new GIcon(); 
		iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
		iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
		iconRed.iconSize = new GSize(12, 20);
		iconRed.shadowSize = new GSize(22, 20);
		iconRed.iconAnchor = new GPoint(6, 20);
		iconRed.infoWindowAnchor = new GPoint(5, 1);
		
		var iconBlue = new GIcon(); 
		iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
		iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
		iconBlue.iconSize = new GSize(12, 20);
		iconBlue.shadowSize = new GSize(22, 20);
		iconBlue.iconAnchor = new GPoint(6, 20);
		iconBlue.infoWindowAnchor = new GPoint(5, 1);
		
		
		// Create and Center a Map
		var map = new GMap2(container);
		map.setMapType(G_HYBRID_MAP);
		map.setCenter(new GLatLng(52.846262261407496, -4.117212295532227), 13);
		
		var sarnbadrig = new GMarker(new GLatLng(52.846262261407496, -4.117212295532227), {title:'Sarn Badrig', draggable:false});
		/*GEvent.addListener(sarnbadrig, "dragend", function() {
		  console.log(sarnbadrig.getLatLng())
		});
		GEvent.addListener(sarnbadrig, "click", function() {
		  console.log(sarnbadrig.getLatLng())
		});*/
		sarnbadrig.bindInfoWindowHtml('<div class="mapInfo"><h2>Sarn Badrig</h2><p>Harlech Holiday Home</p></div>');
		map.addOverlay(sarnbadrig);
		//map.openInfoWindow(sarnbadrig);
		
		var castle = new GMarker(new GLatLng(52.85997123167059, -4.109208583831787), {title:'Harlech Castle', icon:iconBlue});
		castle.bindInfoWindowHtml('<div class="mapInfo"><h2>Harlech Castle</h2><p></p></div>');
		map.addOverlay(castle);
		
		var golf = new GMarker(new GLatLng(52.85882466427131, -4.1136932373046875), {title:"Royal St. David's Golf Course", icon:iconBlue});
		golf.bindInfoWindowHtml("<div class='mapInfo'><h2>Royal St. David's Golf Course</h2><p></p></div>");
		map.addOverlay(golf);
		
		var slate = new GMarker(new GLatLng(52.83926357548583, -4.113103151321411), {title:"Chwarel Hen Slate Caverns", icon:iconBlue});
		slate.bindInfoWindowHtml("<div class='mapInfo'><h2>Chwarel Hen Slate Caverns</h2><p>These are within half a mile of the house and were <br>used in the film 'First Knight' starring Sean Connery.</p></div>");
		map.addOverlay(slate);
		
		var theater = new GMarker(new GLatLng(52.85594839579436, -4.112963676452637), {title:"Theatre Ardudwy", icon:iconBlue});
		theater.bindInfoWindowHtml("<div class='mapInfo'><h2>Theatre Ardudwy</h2><p></p></div>");
		map.addOverlay(theater);
		
		var rail = new GMarker(new GLatLng(53.069276954920625, -4.0724945068359375), {title:"Mount Snowdon", icon:iconBlue});
		rail.bindInfoWindowHtml("<div class='mapInfo'><h2>Mount Snowdon</h2><p><a href='http://www.snowdonrailway.co.uk' target='_blank'>www.snowdonrailway.co.uk</a></p></div>");
		map.addOverlay(rail);
		
		var Portmeirion = new GMarker(new GLatLng(52.91635529577279, -4.093780517578125), {title:"Portmeirion", icon:iconBlue});
		Portmeirion.bindInfoWindowHtml("<div class='mapInfo'><h2>Portmeirion</h2><p>Portmeirion the Italianate village built by the architect Sir Clough Williams Ellis <br>and made famous by the T.V.programme 'The Prisoner'<br><a href='http://www.portmeirion-village.com' target='_blank'>www.portmeirion-village.com</a></p></div>");
		map.addOverlay(Portmeirion);
		
		var railway = new GMarker(new GLatLng(52.92918843878613, -4.134979248046875), {title:"The Ffestiniog Steam Railway and the Welsh Highland Railway", icon:iconBlue});
		railway.bindInfoWindowHtml("<div class='mapInfo'><h2>The Ffestiniog Steam Railway and the Welsh Highland Railway</h2><p>These are two narrow gauge railways based in Portmadoc.<br><a href='http://www.ffestiniograilway.co.uk' target='_blank'>www.ffestiniograilway.co.uk</a><br><a href='http://www.welshhighlandrailway.net' target='_blank'>www.welshhighlandrailway.net</a></p></div>");
		map.addOverlay(railway);
		
		var Yacht = new GMarker(new GLatLng(52.83015063303132, -4.119873046875), {title:"Pensarn Yacht Club", icon:iconBlue});
		Yacht.bindInfoWindowHtml("<div class='mapInfo'><h2>Pensarn Yacht Club</h2><p><a href='http://www.lpyc.org.uk' target='_blank'>www.lpyc.org.uk</a></p></div>");
		map.addOverlay(Yacht);
		
		var Yacht = new GMarker(new GLatLng(52.85962143465829, -4.107588529586792), {title:"Castle Cottage Restaurant", icon:iconBlue});
		Yacht.bindInfoWindowHtml("<div class='mapInfo'><h2>Castle Cottage Restaurant</h2><p>(In the Good Food Guide)<br><a href='http://www.castlecottageharlech.co.uk' target='_blank'>www.castlecottageharlech.co.uk</a></p></div>");
		map.addOverlay(Yacht);
		
		
		//map.openInfoWindow(map.getCenter(), new Element('div', {text:'hello world'}));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		

		// bind a search control to the map, suppress result list
		map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));
	}
}

function createCalendar(monthNum, onRight){
	//month = 8 - year = 2008
	var date = Date.today().moveToFirstDayOfMonth().addMonths(monthNum);
	//console.log(date);
	var monthName = date.getMonthName();
	var fullYear = date.getFullYear();
	var startDate = date.clone().last().monday();
	//console.log(startDate);
	var table = new Element('table', {'cellspacing': 1});
	if(onRight){
		table.addClass('last');
	}
	var caption = new Element('caption', {'html': monthName+' '+fullYear}).inject(table);
	var head = new Element('thead').inject(table);
	new Element('th', {'text': 'Mon'}).inject(head);
	new Element('th', {'text': 'Tue'}).inject(head);
	new Element('th', {'text': 'Wed'}).inject(head);
	new Element('th', {'text': 'Thu'}).inject(head);
	new Element('th', {'text': 'Fri'}).inject(head);
	new Element('th', {'text': 'Sat'}).inject(head);
	new Element('th', {'text': 'Sun'}).inject(head);
	var body = new Element('tbody').inject(table);
	var count = 0
	for(var i=0; i<6; i++){
		var tr = new Element('tr').inject(body);
		for(var j=0; j<7; j++){
			var d = startDate;
			var classname = '';
			//console.log(d.toString());
			//var nd = new Date(d.getFullYear(), d.getMonth(), d.getDate());
			//console.log(nd);
			if(bookedDates.contains(d.toString())){
				classname = 'booked ';
			};
			if(d.getMonth() < date.getMonth()){
				classname += 'past';
			}else if(d.getMonth() > date.getMonth()){
				classname += 'future';
			}
			new Element('td', {
				'text': d.getDate(),
				'class': classname
			}).inject(tr);
			startDate.add(1).days();
		}
	}
	table.inject($('calendarHolder'));
}

function nextCalendars(){
	calFxCount++;
	$('calendarHolder').setStyle('width', (calFxCount+1)*978);

	if(($('calendarHolder').getStyle('width').toInt() / 978) == calFxCount+1){
		createCalendar(calCount++);
		createCalendar(calCount++);
		createCalendar(calCount++);
		createCalendar(calCount++, true);
	}
	
	calFx.start('left', -(calFxCount*924));
	$('prev').setStyle('display', '');
}

function prevCalendars(){
	calFxCount--;
	calFx.start('left', -(calFxCount*924));
	if(calFxCount == 0){
		$('prev').setStyle('display', 'none');
	}
}

