var currentYaw = 180;
var currentPitch = 0;
var timer;
var svp;
svc = new google.maps.StreetViewService();
var lat = 53;
var lon = -2;
var panoramaOptions;
var map;
var mapLocate;
var info;
var cluster;
var markersArray;
var currentOpinions;
var currentInfoWindow;
var urlmarker;
var randomMarker;

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


function initialize() {

	var options = {
		zoom: 3,
		center: new google.maps.LatLng(lat, lon),
		mapTypeId: google.maps.MapTypeId.TERRAIN,
		streetViewControl: false,
		mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        position: google.maps.ControlPosition.TOP_CENTER
    }
	};
	map = new google.maps.Map(document.getElementById("mapDiv"),options);
	var locatemapoptions = {
		zoom: 4,
		center: new google.maps.LatLng(lat, lon),
		mapTypeId: google.maps.MapTypeId.TERRAIN,
		mapTypeControl: false,
		streetViewControl: false
	};
	mapLocate = new google.maps.Map(document.getElementById("mapLocate"),locatemapoptions);
	scapeMarker = new google.maps.Marker({'position' : new google.maps.LatLng(lat, lon),'draggable' : true});
	
	google.maps.event.addListener(mapLocate, "idle", function() {
		scapeMarker.setMap(null);
		scapeMarker = new google.maps.Marker({'position' : mapLocate.getCenter(),'draggable' : true});
		scapeMarker.setMap(mapLocate);
		var pos = scapeMarker.getPosition();
		document.getElementById("latitude").value = pos.lat();
		document.getElementById("longitude").value = pos.lng();
		google.maps.event.addListener(scapeMarker, "dragend", draggedEnd);
	});
	
	google.maps.event.addListener(scapeMarker, "dragend", draggedEnd);
	
	scapeMarker.setMap(mapLocate); 
	
	panoramaOptions = { latlng:new google.maps.LatLng(lat, lon) };
	svp = new google.maps.StreetViewPanorama(document.getElementById("panorama"), panoramaOptions);
	document.getElementById("panorama").style.zIndex= -6;
	svp.setVisible(false);
	timer = window.setInterval(spiral, 100);
	/*
if (google.loader.ClientLocation != null){
		lat = google.loader.ClientLocation.latitude;
		lon = google.loader.ClientLocation.longitude;
	}
	*/
	downloadUrl("site/js/genXML.php", function(data) {
		//var xml = xmlParse(data);
		var markers = data.documentElement.getElementsByTagName("marker");
		
		markersArray=[];
		var sampleID;
		var quality;
		var overallQuality;
		var time;
		var date;
		var model;
		var pleasant;
		var exciting;
		var eventful;
		var chaos;
		var fileName;
		var opinion;
		var point;
		var marker;
		var flagged;
		var positive;
		var negative;
		var randomNumber = Math.floor(Math.random()*markers.length);
		
		for (var i = 0; i < markers.length; i++) {
			positive = markers[i].getAttribute("positive");
			negative = markers[i].getAttribute("negative");
			flagged = markers[i].getAttribute("flagged");
			sampleID = markers[i].getAttribute("sampleID");
			quality = markers[i].getAttribute("quality");
			overallQuality = markers[i].getAttribute("overallQuality");
			time = markers[i].getAttribute("time");
			date = markers[i].getAttribute("date");
			model = markers[i].getAttribute("model");
			pleasant = markers[i].getAttribute("pleasant");
			exciting = markers[i].getAttribute("exciting");
			eventful = markers[i].getAttribute("eventful");
			chaos = markers[i].getAttribute("chaos");
			fileName = markers[i].getAttribute("fileName");
			opinion = markers[i].getAttribute("opinion");
			point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
			if(flagged == 0){
				
				info = createHTML(sampleID,fileName,quality,overallQuality,time,date,model,pleasant,exciting,eventful,chaos,opinion);
				var opinions = createOpinions(sampleID,quality,overallQuality,time,date,model,pleasant,exciting,eventful,chaos,positive,negative);
				marker = createMarker(point, info, fileName,sampleID,opinions);
				markersArray.push(marker);
				if(i == randomNumber){
					randomMarker = marker;
				}
				var urlid = gup('id');
				if(urlid!="" && fileName==urlid){
					urlmarker = marker;
				}
				
			}
		}
		//var mcOptions = {gridSize: 50, maxZoom: 15};
		//cluster=new MarkerClusterer(map,markersArray,mcOptions);
		cluster=new MarkerClusterer(map,markersArray);
		document.getElementById("panorama").style.zIndex= -6;
		svp.setVisible(false);
		if(urlmarker){
			setTimeout("openMarker()",1000);
		}
		
		});
		document.getElementById("panorama").style.zIndex= -6;
		svp.setVisible(false);
	
	document.getElementById("panorama").style.zIndex= -6;
	svp.setVisible(false);
}
//initialise end point

function openMarker(){
var urlid = gup('id');
		if(urlid!=""){
			map.setZoom(16);
			google.maps.event.trigger(urlmarker, "click");
		}
}

function nextRandomScape(){
	var randomNumber = Math.floor(Math.random()*markersArray.length);
	//google.maps.event.trigger(markersArray[randomNumber], "click");
	document.getElementById("panorama").style.visibility = "hidden";
	document.getElementById("panorama").style.zIndex= -6;
	svp.setVisible(false);
	
	map.setCenter(markersArray[randomNumber].position);
	google.maps.event.addListenerOnce(map, 'idle', function(){
		
		map.setZoom(16);
		
	});
	google.maps.event.addListenerOnce(map, 'idle', function(){
		
		google.maps.event.trigger(markersArray[randomNumber], "click");
		
	});
	//zoomIn();
	//map.setZoom(16);
}

function zoomIn(){
	if(map.getZoom() != 16){
		map.setZoom(16);
		setTimeout("openShuffleMarker();",1000);
	}else{
		openShuffleMarker();
	}
}

function openShuffleMarker(){
var randomNumber = Math.floor(Math.random()*markersArray.length);
	google.maps.event.trigger(markersArray[randomNumber], "click");
}

function createRandomScape(text,uniqueCode){
return;
document.getElementById('randomDiv').innerHTML = "Random soundscape:<p></p><object type=\"application/x-shockwave-flash\" data=\"http://www.soundaroundyou.com/wp-content/themes/QuikTab/jsfiles/player.swf\" id=\"audioplayer1\" height=\"24\" width=\"290\"><param name=\"movie\" value=\"http://www.soundaroundyou.com/wp-content/themes/QuikTab/jsfiles/player.swf\"><param name=\"FlashVars\" value=\"playerID=1&amp;soundFile=http://www.soundaroundyou.com/Soundscapes/"+uniqueCode+".mp3\"><param name=\"quality\" value=\"high\"><param name=\"menu\" value=\"false\"><param name=\"wmode\" value=\"transparent\"></object><img src=\"http://www.soundaroundyou.com/wp-content/themes/QuikTab/jsfiles/x.gif\" alt=\"http://www.soundaroundyou.com/Soundscapes/"+uniqueCode+".mp3\"/><p style=\"padding:10px 10px 10px 10px; width:300px; font-style:italic;\">\""+text+"\"</p>";
}

function spiral() {
		if(svp.getVisible()){
			currentYaw += 1.0;
			svp.setPov({heading: currentYaw, pitch: 0, zoom: 1});
		}
}

  var moveListener;
  var currentMarker;
  var curentInfo;
  var currentID;
  
function createMarker(point, info, fileName,ID,opinions) {
	marker = new google.maps.Marker({'position' : point});
	google.maps.event.addListener(marker, 'click', function(point)
	{
		map.panBy(1,1);
		var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.		clientHeight;
		var helper = new google.maps.OverlayView();
		helper.setMap(map);
		helper.draw = function () { 
		if (!this.ready) { 
			this.ready = true; 
			google.maps.event.trigger(this, 'ready'); 
			} 
		}; 
		var projection = helper.getProjection();
		var pxlocation = projection.fromLatLngToContainerPixel(this.getPosition());
		
		var pxdest = (x*0.75);
		var pydest = (y*0.95);
		
		var xShift = -(pxdest-pxlocation.x);
		var yShift = -(pydest-pxlocation.y);
		//map.panTo(projection.fromContainerPixelToLatLng(new google.maps.Point(pxlocation.x+offsetx,pxlocation.y+offsety)));
		if(currentInfoWindow){
			currentInfoWindow.close();
		}
		//map.panTo(point.latLng);
		map.panBy(xShift,yShift);
		currentID = ID;
		currentMarker = this;
		currentInfo = info;
		currentOpinions = opinions;
		google.maps.event.addListenerOnce(map, 'idle', function(){
			var infowindow = new google.maps.InfoWindow({content: currentInfo});
			google.maps.event.addListenerOnce(infowindow, "closeclick", function() {
			if(svp){
				svp.setVisible(false);
				document.getElementById("panorama").style.zIndex= -6;
				}
			}); 
			currentInfoWindow = infowindow;
			infowindow.open(map,currentMarker);
			
			document.getElementById("phpFrame").innerHtml = currentID;
			
			svc.getPanoramaByLocation(currentMarker.getPosition(), 50, function(StreetViewPanoramaData, StreetViewStatus){
			if(StreetViewStatus == google.maps.StreetViewStatus.OK){
				svp.setPosition(StreetViewPanoramaData.location.latLng);
				svp.setPov({heading: 0, pitch: 0, zoom: 1});
				document.getElementById("panorama").style.visibility = "visible";
				document.getElementById("panorama").style.zIndex= 6000;
				svp.setVisible(true);
			}else{
			document.getElementById("panorama").style.visibility = "hidden";
				document.getElementById("panorama").style.zIndex= -6;
				svp.setVisible(false);	
			}
		});
		});

		
		
	});
	
	return marker;
}


function createOpinions(sampleID,quality,overallQuality,time,date,model,pleasant,exciting,eventful,chaos,positive,negative){

if (model=="")
	{
	model = "No device info";
	}
if (positive.length > 25){
	positive = positive.substr(0,25);
}
if (negative.length > 25){
	negative = negative.substr(0,25);
}
var opins = "<div class='infoTextData'><span>Soundscape "+sampleID+" responses</span><br>";
opins = opins  + "<img src='http://www.soundaroundyou.com/wp-content/themes/QuikTab/images/swirl.png' alt=''/><br>";
	opins = opins  + "Overall location quality:&nbsp&nbsp&nbsp"+overallQuality+"<br>";
	opins  = opins  + "Soundscape quality:&nbsp&nbsp&nbsp"+quality +"<br>";
	opins  = opins  + "Time captured:&nbsp&nbsp&nbsp"+time +"<br>";
	opins  = opins  + "Date Captured:&nbsp&nbsp&nbsp"+date +"<br>";
	opins  = opins  + "Device used:&nbsp&nbsp&nbsp"+model +"<br>";
	opins  = opins + "How pleasant:&nbsp&nbsp&nbsp"+pleasant +"<br>";
	opins  = opins  + "How exciting:&nbsp&nbsp&nbsp"+exciting +"<br>";
	opins  = opins  + "How eventful:&nbsp&nbsp&nbsp"+eventful +"<br>";
	opins  = opins  + "How tranquil:&nbsp&nbsp&nbsp"+chaos +"<br>";
	opins  = opins  + "Positive sound:&nbsp&nbsp&nbsp"+positive +"<br>";
	opins  = opins  + "Negative sound:&nbsp&nbsp&nbsp"+negative +"<br>";
	opins = opins + "<img style='z-index:-1;' src='http://www.soundaroundyou.com/wp-content/themes/QuikTab/images/miniLogo.png' alt=''/>";
	return opins +"</div>";
}

function FileExists(strURL)
{
    oHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");    
    oHttp.open("HEAD", strURL, false);
	oHttp.send();
	return (oHttp.status==404) ? false : true;
}

function createHTML(sampleID,fileName,quality,overallQuality,time,date,model,pleasant,exciting,eventful,chaos,opinion) {
	var newLine  = "<br style='line-height:20px;'>";
	
	var html = "<div class ='infoText' style='width:450px; height:400px; overflow:hidden;'>";
	html = html + "<div style='width:450px; height:200px;'>";
	//html = html + "<span>Recorded at "+time+" on "+date+"</span>";
	//html = html + newLine;
	//html = html + newLine;
	html = html + "<span>Reason for capturing:</span>";
	html = html + newLine;
	html = html + newLine;
	html = html + "<span><i>&nbsp&nbsp&nbsp\""+opinion+"\"</i></span>";
	html = html + newLine;
	html = html + newLine;
	html = html +"<a href=\"http://www.soundaroundyou.com/Soundscapes/" +fileName+ ".mp3\" target=\"_blank\">Download soundscape<br>(right click & save as)</a>";
	html = html + newLine;
	//html = html + newLine;
	//html = html + newLine;
	html = html + "<span><a style='text-decoration:underline;' onclick='abuseWindow("+sampleID+")'>Report an issue</a></span>";
	html = html + newLine;
	urlencoded = escape("http://www.soundaroundyou.com?id=" +fileName);
	twurlencoded = escape("http://platform.twitter.com/widgets/tweet_button.html?url="+urlencoded+"&text=Interesting Soundscape on the Sound Around You Project %23soundscape&count=horizontal");
	html = html + "<iframe src=\"http://www.facebook.com/plugins/like.php?href=http://www.soundaroundyou.com?id=" +fileName+ "&amp;layout=standard&amp;show_faces=false&amp;action=like&amp;data-send=true&amp;colorscheme=light\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; overflow:visible; width:65%; height:100px; margin-top:10px\"></iframe>";
	
	 html = html + "<iframe allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\" src=\"http://platform.twitter.com/widgets/tweet_button.html?url="+urlencoded+"&text=Interesting Soundscape on the Sound Around You Project %23soundscape&count=horizontal&related=say_project%counturl="+urlencoded+"\" style=\"width:35%; height:20px; float:right; margin-top:10px;\"></iframe>";
	
	tweet = "<a href=\"https://twitter.com/share\" class=\"twitter-share-button\" data-url=\"http://www.soundaroundyou.com?id=" +fileName+ "\" data-text=\"Interesting Sound Around You Project Soundscape!\" data-via=\"say_project\" data-hashtags=\"soundscape\">Tweet</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script>";
	
	html = html + "</div>";
addbuttons = "<div class=\"addthis_toolbox addthis_default_style\" addthis:url=\"http://www.soundaroundyou.com?id=" +fileName+ "\" addthis:title=\"Sound Around You Soundscape\" addthis:description=\"Capture reason: "+opinion+"\"><a class=\"addthis_button_facebook_like\" fb:like:layout=\"button_count\"></a><a class=\"addthis_button_tweet\"></a><a class=\"addthis_button_google_plusone\" g:plusone:size=\"medium\"></a><a class=\"addthis_counter addthis_pill_style\"></a></div>";
	
	var rating ="<span id=\"rateStatus\">Rate this soundscape</span><span id=\"ratingSaved\">Rating Saved!</span><div id=\"rateMe\" title=\"Rate Me...\"><a onclick=\"rateIt(this)\" id=\"_1\" title=\"1\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_2\" title=\"2\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_3\" title=\"3\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_4\" title=\"4\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_5\" title=\"5\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_6\" title=\"6\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_7\" title=\"7\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_8\" title=\"8\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a><a onclick=\"rateIt(this)\" id=\"_9\" title=\"9\" onmouseover=\"rating(this)\" onmouseout=\"off(this)\"></a></div>";
	
		html = html + "<div style=\"margin-top:150px;\">";
		//html = html + rating;
		html = html + "<img style='float:right; left:260px; margin-top:-80px; z-index:-1;' src='http://www.soundaroundyou.com/wp-content/themes/QuikTab/images/miniLogo.png' alt=''/>";
	
	var audio = "<object type=\"application/x-shockwave-flash\" data=\"http://www.soundaroundyou.com/wp-content/themes/QuikTab/jsfiles/player.swf\" id=\"audioplayer1\" height=\"40\" width=\"450\"><param name=\"movie\" value=\"http://www.soundaroundyou.com/wp-content/themes/QuikTab/jsfiles/player.swf\"><param name=\"FlashVars\" value=\"playerID=1&amp;soundFile=http://www.soundaroundyou.com/Soundscapes/"+fileName+".mp3\"><param name=\"quality\" value=\"high\"><param name=\"menu\" value=\"false\"><param name=\"wmode\" value=\"transparent\"></object></div>";
	/*
	var audio = "<div id=\"jquery_jplayer_1\" class=\"jp-jplayer\"></div>\
  <div id=\"jp_container_1\" class=\"jp-audio\">\
    <div class=\"jp-type-single\">\
      <div class=\"jp-gui jp-interface\">\
        <ul class=\"jp-controls\">\
          <li><a href=\"javascript:;\" class=\"jp-play\" tabindex=\"1\">play</a></li>\
          <li><a href=\"javascript:;\" class=\"jp-pause\" tabindex=\"1\">pause</a></li>\
          <li><a href=\"javascript:;\" class=\"jp-stop\" tabindex=\"1\">stop</a></li>\
        </ul>\
        <div class=\"jp-progress\">\
          <div class=\"jp-seek-bar\">\
            <div class=\"jp-play-bar\"></div>\
          </div>\
        </div>\
        <div class=\"jp-time-holder\">\
          <div class=\"jp-current-time\"></div>\
          <div class=\"jp-duration\"></div>\
        </div>\
      </div>\
      <div class=\"jp-no-solution\">\
        <span>Update Required</span>\
        To play the media you will need to either update your browser to a recent version or update your <a href=\"http://get.adobe.com/flashplayer/\" target=\"_blank\">Flash plugin</a>.\
      </div>\
    </div>\
  </div>";
  */
	html = html + audio;
	html = html + "</div>";
	return html;
}

function abuseWindow(id){
	var message = "If you think this soundscape entry is inappropriate in any way, click OK and it'll be removed for review";
	if(confirm(message)){
		//Abuse confirmed
		
		var serverScript = "http://www.soundaroundyou.com/wp-content/themes/QuikTab/jsfiles/flagScape.php?scapeID=" + id;
		
		// update server
	
		document.getElementById("phpFrame").src = serverScript;
		setTimeout("clearSRC()",6000);
		alert("Scape flagged: "+id);
		//document.write("<script type='text/javascript' src='"+serverScript+"'></script>");

		
		map.closeInfoWindow();
		currentMarker.hide();
	}else{
		//Abuse cancelled
		
	}
}
function clearSRC(){
document.getElementById("phpFrame").src = "";
reloadMarkers();
}

function reloadMarkers(){
var options = {
		zoom: 3,
		center: new google.maps.LatLng(lat, lon),
		mapTypeId: google.maps.MapTypeId.HYBRID,
		streetViewControl: false,
		mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        position: google.maps.ControlPosition.TOP_CENTER
    }
	};
	map = new google.maps.Map(document.getElementById("mapDiv"),options);

	downloadUrl("site/js/genXML.php", function(data) {
		//var xml = xmlParse(data);
		var markers = data.documentElement.getElementsByTagName("marker");
		
		markersArray=[];
		var sampleID;
		var quality;
		var overallQuality;
		var time;
		var date;
		var model;
		var pleasant;
		var exciting;
		var eventful;
		var chaos;
		var fileName;
		var opinion;
		var point;
		var marker;
		var flagged;
		var positive;
		var negative;
		var randomNumber = Math.floor(Math.random()*markers.length);
		
		for (var i = 0; i < markers.length; i++) {
			positive = markers[i].getAttribute("positive");
			negative = markers[i].getAttribute("negative");
			flagged = markers[i].getAttribute("flagged");
			sampleID = markers[i].getAttribute("sampleID");
			quality = markers[i].getAttribute("quality");
			overallQuality = markers[i].getAttribute("overallQuality");
			time = markers[i].getAttribute("time");
			date = markers[i].getAttribute("date");
			model = markers[i].getAttribute("model");
			pleasant = markers[i].getAttribute("pleasant");
			exciting = markers[i].getAttribute("exciting");
			eventful = markers[i].getAttribute("eventful");
			chaos = markers[i].getAttribute("chaos");
			fileName = markers[i].getAttribute("fileName");
			opinion = markers[i].getAttribute("opinion");
			point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
			if(flagged == 0){
				if(i == randomNumber){
					createRandomScape(opinion,fileName);
					}
				info = createHTML(sampleID,fileName,quality,overallQuality,time,date,model,pleasant,exciting,eventful,chaos,opinion);
				
				var opinions = createOpinions(sampleID,quality,overallQuality,time,date,model,pleasant,exciting,eventful,chaos,positive,negative);
				
				marker = createMarker(point, info, fileName,sampleID,opinions);
				markersArray.push(marker);
				var urlid = gup('id');
				if(urlid!="" && fileName==urlid){
					urlmarker = marker;
				}
				
			}
		}
		
		cluster=new MarkerClusterer(map,markersArray);

		});
}
