var language;

window.addEvent('domready', function(){
	$('large').addEvent('click', function(e){
		$$('.main-content p, .main-content td, .main-content li').each(function(el){
			el.setStyles({
				fontSize:'16px',
				lineHeight:'1.4em'
			})
		});
		$$('.main-content h2').each(function(el){
			el.setStyles({
				fontSize:'18px',
				lineHeight:'1.2em',
				color:'#333333 !important'
			})
		});
		$$('.panel-text').each(function(el){
			el.setStyles({
				fontSize:'14px',
				lineHeight:'1.2em'
			})
		});
		$$('*').each(function(el){
			el.setStyles({
				fontStyle:'normal !important'
			})
		});
		$$('#main-menu li a').each(function(el){
			el.setStyles({
				fontSize:'16px',
				marginRight:'10px'
			})
		});
	});
	$('normal').addEvent('click', function(e){
		$$('.main-content p, .main-content td, .main-content li').each(function(el){
			el.setStyles({
				fontSize:'12px',
				lineHeight:'1.2em'
			})
		});
		$$('.main-content h2').each(function(el){
			el.setStyles({
				fontSize:'16px',
				lineHeight:'1.2em',
				color:''
			})
		});
		$$('.panel-text').each(function(el){
			el.setStyles({
				fontSize:'12px',
				lineHeight:'1.2em'
			})
		});
		$$('*').each(function(el){
			el.setStyles({
				fontStyle:''
			})
		});
		$$('#main-menu li a').each(function(el){
			el.setStyles({
				fontSize:'',
				marginRight:''
			})
		});
	});
	wParts=new String(window.location.href);
	wParts=wParts.split('/');
	language='cy';
	for(var i=0; i<wParts.length; i++){
		if(wParts[i]=='english'){
			language='en';
		}
	}
	
	$$('#body a').each(function(el){
		if(!el.href.contains('http://'+document.domain)){
			el.set('target', '_blank');
			el.addEvent('click', function(){
				switch(language){
					case 'en':
						$msg='This is a link to an external site. As such, Mid-Wales Housing Association is not responsible for the content you are about to view. Do you wish to continue?';
						break;
					case 'cy':
						$msg="Mae hon yn ddolen i safle allanol, ac o'r herwydd nid yw Cymdeithas Tai Canolbarth Cymru yn gyfrifol am y cynnwys yr ydych ar fin edrych arno. Ydych chi'n dymuno parhau?";
						break;
				}
				if(confirm($msg)){
					return true;
				} else {
					return false;
				}
			})
		}
		if(el.href=='http://www.direct.gov.uk/en/Diol1/DoItOnline/DoItOnlineByCategory/DG_172666'){
			if(language=='cy'){
				el.href='http://www.direct.gov.uk/cy/Diol1/DoItOnline/DoItOnlineByCategory/DG_172666CY';
			}
		}
	});
});
function validateFile(el, allowed){
	el=$(el);
	if(el.value){
		var fileParts=el.value.split('.');
		var fileType=fileParts[fileParts.length-1].toLowerCase();
		if(!allowed.contains(fileType)){
			if(language=='en'){
				alert("The file is not of the correct type.");
			} else {
				alert("Nid yw'r ffeil yn y math cywir.");
			}
		}
	}
}
function doLanguagePicker(){
	if($$('body.home').length>0){
		cover=new Element('DIV');
		cover.setStyles({
			width:'100%',
			height:'100%',
			backgroundColor:'#00311c',
			opacity:0,
			position:'fixed',
			left:0,
			top:0
		})
		cover.injectInside(document.body);
		new Fx.Tween(cover).start('opacity', .8);
		lang=new Element('IMG');
		lang.src='static/images/framework/language-panel.png';
		lang.set('usemap','#languagemap');
		lang.setStyles({
			width:500,
			height:340,
			marginLeft:-250,
			marginTop:-170,
			position:'fixed',
			left:'50%',
			top:'50%',
			opacity:0
		});
		new Fx.Tween(lang).start('opacity', 1);
		lang.injectInside(document.body);
	}
}

window.addEvent('load', function(){

	// CHECK THE PAGE AND LOAD IN GOOGLE MAPS API IF NECESSARY
	if($('google-map-holder-list')){
		sMaps=new Element('SCRIPT');
		sMaps.set('type', 'text/javascript');
		sMaps.set('src', 'http://maps.google.com/maps/api/js?sensor=false&callback=initMapForListPage');
		sMaps.injectInside(document.head);
	}
	if($('google-map-holder-location')){
		sMaps=new Element('SCRIPT');
		sMaps.set('type', 'text/javascript');
		sMaps.set('src', 'http://maps.google.com/maps/api/js?sensor=false&callback=loadTownForLocationPage');
		sMaps.injectInside(document.head);
	}

	if($('rolling-container')){
		$('rolling-container').setStyles({
			height:'100%'
		});
		allImages=$$('a.rolling');
		allImages.each(function(el){
			el.setStyles({
				display:'block',
				position:'absolute',
				left:0,
				top:0
			});
			el.fader=new Fx.Morph(el, {duration:2000, onComplete:function(){
				doFade.delay(5000);
			}});
		});
		doFade.delay(5000);
	}
	SB=$('search-box');
	SB.setStyles({
		opacity:0,
		display:'block'
	});
	SB.fader=new Fx.Tween(SB);
	$('search-link').addEvent('click', function(){
		SB.fader.start('opacity', 1);
	});
	SB.addEvent('mouseleave', function(){
		SB.fader.start('opacity', 0);
	});
});


function doFade(){
	allImages=$$('a.rolling');
	if(allImages[allImages.length-1].getStyle('opacity')=='0'){
		allImages[allImages.length-1].dispose().inject('rolling-container', 'top').setStyles({
			opacity: 1
		});
		allImages=$$('a.rolling');
	}
	allImages[allImages.length-1].fader.start({
		opacity:0
	})
}






// #################   FUNCTIONS FOR PROPERTIES LIST PAGE   #######################
// Create map centered on Newtown and place it into the holder
function initMapForListPage(){
	loaderBox=new Element('DIV');
	loaderBox.set('html', '<img style="vertical-align:middle; padding-right:5px" src="/static/images/framework/loader.gif"> Please wait while the properties load');
	loaderBox.setStyles({
		backgroundColor:'#FFFFFF',
		padding:10,
		position:'absolute',
		top:150,
		left:270,
		border:'solid 1px #000',
		fontFamily:'arial, helvetica, sans-serif',
		fontWeight:'bold',
		opacity:.7
	});
	loaderBox.injectAfter($('google-map-holder-list'));
	
	var myLatlng = new google.maps.LatLng(52.5132, -3.3141);
	var myOptions = {
		zoom: 8,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map($('google-map-holder-list'), myOptions);
	//Create geocoder instace
	gc=new google.maps.Geocoder();
	markers=[];
	propertiesCounter=0;
	//start geocoding each property
	geocodePropertyForListPage(propertiesCounter);
}

function geocodePropertyForListPage(pCounter){
	//console.log(pCounter);
	//Create an address from the property details
	var gcOpts={
		address:properties[pCounter].location+', '+properties[pCounter].region,
		region:'GB'
	}
	//Geocode the address and send th result to addToMarkers
	//console.log(properties[pCounter].location+', '+properties[pCounter].region);
	gc.geocode(gcOpts, addToMarkersForListPage);
}

function addToMarkersForListPage(response){
	//console.log(response);
	//Add a marker to the list
	if(response){
		var marker={};
		//Create latlng object from geocode response
		marker.latLng=response[0].geometry.location; //new google.maps.LatLng(response[0].geometry.location.lat(),response[0].geometry.location.lng());
		//add details to marker object
		marker.details=properties[propertiesCounter];
		//add marker to list
		markers.push(marker);
		plotMarkersForListPage(markers.length-1);
		propertiesCounter++;
	}
	//check if all the markers are loaded and coded, if so plot them, if not then code the next one
	//console.log(propertiesCounter+' of '+properties.length+' loaded');
	if(propertiesCounter<properties.length-1){
		setTimeout('geocodePropertyForListPage('+propertiesCounter+')', 300);
	} else {
		finishLoadingList();
	}
}
function plotMarkersForListPage(gI){
	//for(gI=0; gI<markers.length; gI++){
		pDetails="<div class=\"main-content\"><h2>"+markers[gI].details.location+"</h2>";
		pDetails+=markers[gI].details.content+'<br/>';
		pDetails+="<a href=\""+markers[gI].details.link+"\">More information</a></div>";
		//Dirty workaround to get functions tied to markers...sorry about using eval()
		if(markers[gI].details.region=='Powys'){
			icon=ROOT+'/static/images/framework/map/powys.png';
		} else if(markers[gI].details.region=='Ceredigion'){
			icon=ROOT+'/static/images/framework/map/ceredigion.png';
		} else {
			icon=ROOT+'/static/images/framework/map/shropshire.png';
		}
		//document.body.innerHTML=pDetails;
		eval("pIcon_"+gI+"=new google.maps.MarkerImage(icon,new google.maps.Size(41, 60),new google.maps.Point(0, 0),new google.maps.Point(20, 53));");
		eval("pMarker_"+gI+" = new google.maps.Marker({position:markers[gI].latLng,map:map,title:markers[gI].details.location,clickable:true, icon:pIcon_"+gI+"});");
		eval("infoWindow_"+gI+"=new google.maps.InfoWindow({content: '"+pDetails+"'});");
		eval("goToLocation_"+gI+"=function(){window.location.href=markers["+gI+"].details.link;}");
		eval("showLocation_"+gI+"=function(){infoWindow_"+gI+".open(map, pMarker_"+gI+");}");
		eval("google.maps.event.addListener(pMarker_"+gI+", 'click', function(event){showLocation_"+gI+"();});");
	//}
}

function finishLoadingList(){
	loaderBox.dispose();
}




// #################   FUNCTIONS FOR PROPERTIES LOCATION PAGE   #######################
// Create map centered on Newtown and place it into the holder
function loadTownForLocationPage(){
	var gcOpts={
		address:lMarker.location+', '+lMarker.region,
		region:'GB'
	}
	//Geocode the address and send th result to addToMarkers
	gc=new google.maps.Geocoder();
	gc.geocode(gcOpts, initMapForLocationPage);
}
function initMapForLocationPage(response){
	var myLatLng = response[0].geometry.location; //new google.maps.LatLng(response[0].geometry.location.b,response[0].geometry.location.c);
	var myOptions = {
		zoom: 14,
		center: myLatLng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map($('google-map-holder-location'), myOptions);
	townMarker=new google.maps.Marker({position:myLatLng, map:map, title:PARAMS[1]});
	markers=[];
	streetCount=0;
	//console.log(streets);
	createMarkerForLocationPage(streets[streetCount]);
}
function createMarkerForLocationPage(street){
	var gcOpts={
		address:street.name,
		region:'GB'
	}
	//console.log(street.name);
	gc.geocode(gcOpts, addToMarkersForLocationPage);
}
function addToMarkersForLocationPage(response){
	//console.log(response);
	if(response){
		for(var i=0; i<markers.length; i++){
			if(markers[i].b==response[0].geometry.location.b && markers[i].c==response[0].geometry.location.c){
				//console.log('match');
				response[0].geometry.location.b-=0.00001;
				response[0].geometry.location.c+=0.00001;
			}
		}
		markers.push({b:response[0].geometry.location.b,c:response[0].geometry.location.c});

		var latLng=response[0].geometry.location;//new google.maps.LatLng(response[0].geometry.location.b,response[0].geometry.location.c);
		var image = new google.maps.MarkerImage(ROOT+'/static/images/framework/map/bungalows.png',
			new google.maps.Size(23, 23),
			new google.maps.Point(0, 0),
			new google.maps.Point(12, 12)
		);
	  var marker = new google.maps.Marker({
			position: latLng,
			map: map,
			icon: image,
			title: streets[streetCount].name
		});
		streetCount++;
	}
	if(streetCount<streets.length){
		setTimeout('createMarkerForLocationPage(streets[streetCount])', 300);
	}
}


