/**
 * Main Public Javascript
 *
 * @copyright   Copyright (C) 2011, Stuart Silvester
 * @author      Stuart Silvester
 * @package     Member Map
 * @version     1.0.6
 */

var _membermap 	= window.IPBoard,
	storedLat 	= [],
	storedLong 	= [],
	url			= '',
	licount		= 0;

_membermap.prototype.membermap =
{
	popups: {},
	type: '',

	init: function()
	{
		Debug.write("Initializing ips.membermap.js");

		document.observe("dom:loaded", function()
			{
				/* Is there a map on this page? */
				if( $('memberMapCanvasWrapper') )
				{
					ipb.membermap.loadEvents();
				}

				/* Is there a map on this page? */
				if( $('pinPointMap') )
				{
					/* Need to make sure everything is loaded before the map is */
					ipb.membermap.loadPinPointMap();
				}
			}
		);
	},

	addPinPointMapMarker: function(lat, lon)
	{
		myLatLng = new google.maps.LatLng(lat, lon);

		mkr =	new google.maps.Marker({
				position: myLatLng,
				map: ipb.membermap.pinPointMap
		});
		ipb.membermap.pinPointMap.setCenter( mkr.position );
		ipb.membermap.pinPointMap.setZoom( 12 );
	},

	loadEvents: function()
	{
		/* Icon Defaults */
		ipb.membermap.homeIcon				= new GIcon(G_DEFAULT_ICON);
		ipb.membermap.homeIcon.image		= "http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=home|0099FF";
		ipb.membermap.homeIcon.iconSize		= new GSize(20, 33);
		ipb.membermap.homeIcon.iconAnchor	= new GPoint(10, 33);
		ipb.membermap.friendIcon			= new GIcon(G_DEFAULT_ICON);
		ipb.membermap.friendIcon.image		= "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=F|00E141|000000";
		ipb.membermap.friendIcon.iconSize	= new GSize(20, 33);
		ipb.membermap.friendIcon.iconAnchor	= new GPoint(10, 33);

		['memberMapUpdate','memberMapDelete','memberMapAdd'].each(
			function(element)
			{
				if ( $(element) )
				{
					$(element).observe( 'click',
						function(e)
						{
							Event.stop(e);

							if( $(element+'_popup') )
							{
								ipb.membermap.popups[element].show();
							}
							else
							{
								switch( element )
								{
									case 'memberMapAdd':
										var template = addForm;
									break;

									case 'memberMapUpdate':
										var template = updateForm;
									break;

									case 'memberMapDelete':
										var template = deleteForm;
									break;
								}

								ipb.membermap.popups[element] = new ipb.Popup( element,
									{
										type: 'pane',
										modal: true,
										w: '550px',
										h: 'auto',
										initial: template.evaluate(),
										hideAtStart: false,
										close: '.cancel'
									},
									{
										afterShow: function()
										{
											switch( element )
											{
												case 'memberMapAdd':
													ipb.membermap.type = 'add';
													$('addMapLocation').observe( 'submit', ipb.membermap.formObserve );
												break;

												case 'memberMapUpdate':
													ipb.membermap.type = 'update';
													$('updateMapLocation').observe( 'submit', ipb.membermap.formObserve );
												break;
											}
										}
									}
								);
							}
						}
					);
				}
			}
		);
	},

	createMarker: function(point, html, markerOptions)
	{
	  var marker = new GMarker(point, markerOptions);
	  GEvent.addListener(marker, "click", function()
	  {
		marker.openInfoWindowHtml(html);
	  });
	  return marker;
	},

	formObserve: function(e)
	{
		licount = 0;
		type 	= ipb.membermap.type;
		Event.stop(e);
		$( type + 'MapLocation').request(
			{
				evalJSON: 'force',
				onComplete: function(s)
				{
					var li = "<li><strong>Here are the locations that matched your search, please click one of them.</strong></li>";

					if ( typeof(s.responseJSON['error']) != 'undefined' )
					{
						alert( s.responseJSON['message'] );
						return;
					}

					s.responseJSON.each(
						function(i)
						{
							if ( typeof( i['address'] ) != 'undefined' || ( in_array( i['latitude'], storedLat ) && in_array( i['longitude'], storedLong ) ) )
							{
								licount = licount + 1;

								storedLat[i['latitude']] 	= i['latitude'];
								storedLong[i['longitude']] 	= i['longitude'];

								li += "<li><a href='" + ipb.vars['base_url'] + "app=membermap&module=membermap&section=map&action=" + type + "&lat=" + i['latitude'] + "&lon=" + i['longitude'] + "' title='" + i['address'] + "'>" + i['address'] + "</a></li>";
							}
						}
					);

					$( type + 'MapList').update(li);

					/* Auto click attempt */
					if ( licount == 1 )
					{
						window.location = $( type + 'MapList').down().next().down('a').readAttribute('href');
					}
					else
					{
						$( type + 'MapList').show();
					}
				}
			}
		);
		return false;
	},

	loadPinPointMap: function()
	{
		/* actual center point of Great Britain */
		var latlng = new google.maps.LatLng(54.00366,-2.547855);
		var myOptions = {
						zoom: 6,
						center: latlng,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						disableDefaultUI: true
						};
		ipb.membermap.pinPointMap = new google.maps.Map(document.getElementById("pinPointMap"), myOptions);
	}
}

ipb.membermap.init();

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array
    //
    // version: 911.718
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}
