//Variables
var mouseX = 1;
var mouseY = 1;
var map = null;
var setlan = 0;
var setlon = 0;
var bgpos = 0;
var recpoint = false;
var contest_sendmarketing = true;

//Set Mouse Move and Load jQuery API
document.onmousemove = mouseXY;
google.load("jquery", "1.4.2");

//Run On Page Load
google.setOnLoadCallback(function() {
	// Bind To When Resize Window
	$(window).bind('resize', function() { elementResize(); });
	// Start Google Maps
	mapInit();	
	//Set Button (link) Functions
	$('a').click(function(){ buttonHandle(this); return false; });
	$('#google').fadeOut(10000);
	//Load Markers
	$.getJSON('http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/markers.php?r='+Math.random(), function(data) {																	  
		for (i=0;i<=100000;i++) {
			if (data.markers[i][0]) {
				mapMarker(data.markers[i][0],data.markers[i][1],data.markers[i][2],data.markers[i][3],data.markers[i][4]);
			} else { break; } 
		}
	});
	//Resize Elements to Fit Window
	elementResize();
});

//Button Handler
function buttonHandle(that) {
	//Layout Buttons
	if(that.id == 'toggler') {
		barToggle();
		$('#footer').fadeIn(500);
	}
	if(that.id == 'twitter') {
		window.open('http://twitter.com/home?status=Haluu hehkuttaa Vyötin vinkkejä osoitteessa http://www.rukankampanjat.fi/kesakartta/','tweet','toolbar=0,status=0,width=626,height=436');
	}
	if(that.id == 'rss') {
		window.location = '?feed=rss2';
	}	
	if(that.id == 'info') {
		$("#sidebar").animate({marginLeft:'0px'},'slow');
		$('#sidebarcontent').html('<img style="margin:75px 0px 0px 35px;" src="http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/image/txt_info.png" />');
		makeRoom();		
	}
	if(that.id == 'new') {
		$("#sidebar").animate({marginLeft:'0px'},'slow');
		$('#sidebarcontent').load('http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/newest.php');
	}
	if(that.id == 'tab1') {
		contest_sendmarketing = true;
		$("#sidebar").animate({marginLeft:'0px'},'slow');
		$('#sidebarcontent').load('http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/contest.php');
		makeRoom();
	}	
	if(that.id == 'tab2') {
		showSummerPackets();
	}
	//Contest Buttons
	if(that.id == 'contest_marketing') {
		if(contest_sendmarketing) {
			contest_sendmarketing = false;
			$(that).css('background-image','url()');
		} else {
			contest_sendmarketing = true;
			$(that).css('background-image','url(http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/image/checked.png)')
		}
	}
	if(that.id == 'contest_submit') {
		var name = escape($('[name=name]').val());
		var address = escape($('[name=address]').val());
		var postalcode = escape($('[name=postalcode]').val());
		var postalarea = escape($('[name=postalarea]').val());
		var email = escape($('[name=email]').val());
		var cansendmarketing = 'SUORAMARKKINOINTI_OK';
		if (!contest_sendmarketing) { cansendmarketing = 'EI_SUORAMARKKINOINTIA'; }
		$('#sidebarcontent').load('http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/contest_post.php?name='+name+'&address='+address+'&postalcode='+postalcode+'&postalarea='+postalarea+'&email='+email+'&cansendmarketing='+cansendmarketing+'');
	}	
}

//Make Room For Small Screens
function makeRoom() {
	var reheight = $("#canvas").height();
	if ($(window).height() < 700) {
		//$('#footer').fadeOut(500);
	}
}

//Resize Elements To Fit Window
function elementResize() {
	var canvas = $('#canvas');
	var mapcanvas = $('#map');
	var action = $('#action');
	var actionbg = $('#actionbg');
	//Resize Canvas
	canvas.css('width',$(window).width()+'px');
	canvas.css('height',$(window).height()+'px');	
	actionbg.css('width',$(window).width()+'px');
	actionbg.css('height',$(window).height()+'px');		
	//Resize Map Canvas
	mapcanvas.css('width',canvas.width()+'px');
	mapcanvas.css('height',canvas.height()+'px');
	action.css('left',((canvas.width()/2)-(action.width()/2))+'px');
	action.css('top',((canvas.height()/2)-(action.height()/2))+'px');	
}

//Initialize Google Maps
function mapInit() {	
	map = new GMap2(document.getElementById("map"));	
	map.setCenter(new GLatLng(66.164396,29.121709),8);  
	var topLeft= new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(15,160));
	var topRight2= new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0));
  	//map.addControl(new GSmallMapControl(), topLeft);
    //map.addControl(new GMapTypeControl(), topRight2);	
	GEvent.addListener(map, "click", mapCoord);	
	map.enableScrollWheelZoom();	
}

//Add Marker to Map
function mapMarker(lat,lon,name,desc,id) {
	var point = new GLatLng(lat, lon);
	map.setCenter(point);

	var customIcon = new GIcon();
	customIcon.image = 'http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/image/marker.png';
	customIcon.shadow = '';
	customIcon.iconSize = new GSize(33,48);
	customIcon.shadowSize = new GSize(0,0);
	customIcon.iconAnchor = new GPoint(16,43);
	customIcon.infoWindowAnchor = new GPoint(16,24);
	markerOptions = { icon:customIcon };
	var marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);
	GEvent.addListener(marker, "click", function() { mapMarkerInfo(lat,lon,name,desc,id); }); 	
	GEvent.addListener(marker, "mouseover", function() { mapMarkerHover(name);}); 	
	GEvent.addListener(marker, "mouseout", function() { $('#mouseover').fadeOut(150);}); 		
}

function mapMarkerHover(name) {
	$('#mouseover').html(name);
	$('#mouseover').fadeIn(150);
}

//Center Map To Coordinates
function mapCenterMap(lat,lon) {
	map.panTo(new GLatLng(lat,lon),13);  
}

//Show Map Marker Info
function mapMarkerInfo(lat,lon,name,desc,id) {
	var action = $('#action');
	var actionbg = $('#actionbg');
	var html = '';	
	//Do With Action Canvas
	action.removeClass();
	action.addClass('mapShowMarker');
	action.css('background-position','0px 0px');
	//Build The HTML
	html = html+'<div style="padding:5px;position:absolute;top:75px;left:45px;overflow:auto;height:470px;width:710px;font-size:15px;"><h2>'+name+'</h2><p style="margin-top:0px;">'+desc+'</p></div>';
	html = html+'<a href="#" style="color:transparent;display:block;position:absolute;width:50px;height:45px;top:25px;right:25px;text-indent:-9999px;" onclick="actionHide(); return false;">Sulje</a>';
	action.html(html);
	elementResize()	;
	actionbg.fadeIn(500,function(){action.fadeIn(500);});
}


//Add New Marker Point
function mapCoord(overlay, point) {
	if (point) { 
		var action = $('#action');
		var actionbg = $('#actionbg');
		var html = '';
		setlon = point.lng();
		setlat =  point.lat();
		//Do With Action Canvas
		action.removeClass();
		action.addClass('mapAddMarker');
		action.css('background-position','0px 0px');
		//Build The HTML
		html = html+'<input type="text" id="mapAddMarker_title" name="mapAddMarker_title" style="border:none;background-color:#fff;position:absolute;left:65px;top:127px;width:605px;" />';
		html = html+'<textarea id="mapAddMarker_desc" name="mapAddMarker_desc" rows="5" cols="20" style="border:none;background-color:#fff;position:absolute;left:65px;top:175px;width:605px;height:60px;"></textarea>';		
		html = html+'<input type="text" id="mapAddMarker_link" name="mapAddMarker_link" style="border:none;background-color:#fff;position:absolute;left:65px;top:268px;width:605px;" />';		
		html = html+'<a href="#" style="color:transparent;display:block;position:absolute;width:102px;height:36px;bottom:10px;right:132px;text-indent:-9999px;" onclick="mapMarkerAdd('+setlat+','+setlon+'); return false;">Tallenna</a>';
		html = html+'<a href="#" style="color:transparent;display:block;position:absolute;width:76px;height:36px;bottom:10px;right:50px;text-indent:-9999px;" onclick="actionHide(); return false;">Peru</a>';
		action.html(html);
		actionbg.fadeIn(500,function(){action.fadeIn(500);});
		elementResize();
		}
} 

//Show Summerpackets 
function showSummerPackets() {
		var action = $('#action');
		var actionbg = $('#actionbg');
		var html = '';
		//Do With Action Canvas
		action.removeClass();
		action.addClass('showSummerPackets');
		action.css('background-position','0px 0px');
		//Build The HTML
		html = html+'<a href="#" style="color:transparent;display:block;position:absolute;width:50px;height:70px;top:25px;right:25px;text-indent:-9999px;" onclick="actionHide(); return false;">Sulje</a>';
		html = html+'<a href="#" style="color:transparent;display:block;position:absolute;width:50px;height:45px;top:175px;right:10px;text-indent:-9999px;" onclick="scrollSummerPackets(-786); return false;">Seuraava</a>';	
		html = html+'<a href="#" style="color:transparent;display:block;position:absolute;width:50px;height:45px;top:175px;left:10px;text-indent:-9999px;" onclick="scrollSummerPackets(786); return false;">Seuraava</a>';	
		
		action.html(html);
		actionbg.fadeIn(500,function(){action.fadeIn(500);});
		elementResize();
}

//Scroll Summerpackets 
function scrollSummerPackets(direction) {
	var action = $('#action');	
	bgpos = bgpos+direction;
	//if (bgpos <= -4000) { bgpos = 0; }
	action.animate({backgroundPosition:(bgpos)+'px'},1000);
}

//Toggle Sidebar
function barToggle() {
	if(parseInt($("#sidebar").css('marginLeft'))>-1) {
		$("#sidebar").animate({marginLeft:'-390px'},'slow');
	} else {		
		$("#sidebar").animate({marginLeft:'0px'},'slow');				
	}
}


//Save Marker to Database
function mapMarkerAdd(lat,lon,title,desc) {
	var action = $('#action');
	var actionbg = $('#actionbg');
	var html = '';
	
	var rec_lat = escape(setlat);
	var rec_lon = escape(setlon);
	var rec_title = escape($('[name=mapAddMarker_title]').val());
	var rec_desc = escape($('[name=mapAddMarker_desc]').val());
	var rec_link = escape($('[name=mapAddMarker_link]').val());
	
	$('[name=mapAddMarker_title]').val('');
	$('[name=mapAddMarker_desc]').val('');	
	$('[name=mapAddMarker_link]').val('');	
	
	action.animate({backgroundPosition:(-738)+'px'},'fast');
	action.load('http://www.rukankampanjat.fi/kesakartta/wp-content/themes/kesakartta/save.php?lat='+rec_lat+'&lon='+rec_lon+'&title='+rec_title+'&desc='+rec_desc+'&link='+rec_link);
}


//Hide Action Layer
function actionHide() {
	var action = $('#action');
	var actionbg = $('#actionbg');	
	action.fadeOut(500,function(){actionbg.fadeOut(500);});
}

//Get Mouse Coordinates
function mouseXY(e) {
	try {
		if (!e) var e = window.event||window.Event;
		if('undefined'!=typeof e.pageX) {
			mouseX = e.pageX;
			mouseY = e.pageY;
		} else {
			mouseX = e.clientX + document.body.scrollLeft;
			mouseY = e.clientY + document.body.scrollTop;
		}	
		elementResize();	
		$('#mouseover').css('top',(mouseY+10)+'px');
		$('#mouseover').css('left',(mouseX+10)+'px');
	} catch(err) {
		/* Do Nothing And Wonder What's Happening */
	}
}
