var Try = {
    these: function() {
        var returnValue;

        for (var i = 0; i < arguments.length; i++) {
            var lambda = arguments[i];
            try {
                returnValue = lambda();
                break;
            } catch (e) {}
        }

        return returnValue;
    }
}

function LokiAPI()
{
    return Try.these(
    function() {return new ActiveXObject("Loki.LocationFinder.1")},
    function() {return new Loki()}
    ) || false;
}

var Connector_FindMe = new Class({

    lat:false,
    lon:false,
    icon:false,
    map:false,
    person_id:false,
    window:false,

    initialize: function( mapContainer, lat, lng, user_id )
    {
        if( $( mapContainer ) ){
            this.setupLocationForm();
            this.person_id = user_id;
            this.initMap( mapContainer, lat, lng );
            this.setupIcon();
            this.setLocation( lat, lng );

            var locationButtons = $$('a.saveLocationButton');
            if( locationButtons.length > 0 ){
                for( var i = 0; i < locationButtons.length; i++ ){
                    locationButtons[i].addEvent( 'click', this.locationButtonClick.bind(this) );
                }
            }

            if( $( 'loki-findme' ) ){
                $( 'loki-findme' ).addEvent( 'click', this.lokiButtonClick.bind(this) );
            }

        } else {
            alert( 'Please provide a valid container for the map!' );
        } // end if
    },

    pingLocation:function()
    {
        if( this.lat && this.lon ){
            var src = '/findme/ping.php?service=loki&acc=0&lat=' + this.lat + '&lon=' + this.lon
            if( this.person_id != 0 ) src += '&cpid=' + this.person_id;
            new Image().src = src;
            var point = new GLatLng( Number( this.lat ), Number( this.lon ) );
            this.marker.setPoint( point );
            alert( 'Your location has been updated using Loki!' );
        }
    },

    lokiButtonClick:function( event )
    {
        new Event(event).stop();
        var loki = LokiAPI();
        if (loki) {
            loki.onSuccess = function(location) {
                this.lat = location.latitude;
                this.lon = location.longitude;
                this.pingLocation();
            }.bind(this);
            loki.onFailure = function(error) {
                var message = 'Your Location could no be determined using Loki!';
                alert( message );
            }.bind(this);
            loki.setKey('staging.connectorlocal.com');
            loki.requestLocation(true,loki.NO_STREET_ADDRESS_LOOKUP);
        }else{
            alert( 'Loki couldn\'t be found! Please install it and try again!' );
        }
    },

    locationButtonClick:function( event )
    {

        new Event(event).stop();
        var target = event.target || event.srcElement;
        var myid = target.id;
        // make sure we have the right id
        if( myid.test('myid-') ){
            myid = Number( myid.substring(5).toInt() );
            // city id was found
            this.showSaveLocationPopUp( myid );
        }
    },

    showSaveLocationPopUp:function( id )
    {
        new Ajax("/js/functions/getLocationForm.php",{
            method:'post',
            data:'myid=' + id ,
            onComplete:this.SaveLocationPopResponse.bind(this),
            onFailure:function( response ){ this.updateCurrentPointResponseError.bind(this); }
        }).request();
    },

    SaveLocationPopResponse:function( response )
    {

        this.openWindow( response );
        if( $('save-location-form') ){
            $('save-location-form').addEvent( 'submit', this.saveLocationText.bind(this) );
        }

    },

    saveLocationText:function( event )
    {
        if( $('cl_myl_label') && $('cl_myid') ){
            if( $('cl_myl_label').value.length == 0 ){
                alert( 'You need to enter a label to continue!' );
                new Event( event ).stop();
            }
            if( $('cl_myid').value.length == 0 ){
                alert( 'Missing Location Id!' );
                new Event( event ).stop();
            }
        } else {
            new Event( event ).stop();
        }
    },

    closeWindow:function()
    {
        if( this.window ){
            this.window.close();
        }
    },

    openWindow:function( str )
    {

        if( !$('cl_save_location_win') ){
            var element = new Element('div',{'id': 'cl_save_location_win', 'styles': {'display': 'none'}}).setHTML( str );
            element.injectInside(document.body);
        } else {
            $('cl_save_location_win').setHTML( str );
        }

        this.window = ModalBox.init( 'cl_save_location_win', {initialWidth:300,initialHeight:300} );

        this.window.show();

    },

    setupLocationForm:function()
    {
        if( $('findme-form') && $( 'location_q' ) ){
            $('findme-form').addEvent( 'submit', this.submitFindMe.bind(this));
        } else {
            alert( 'find me form is missing!' );
        }
    },

    submitFindMe:function( event )
    {
        if( $( 'location_q' ).value.length == 0 ){
            new Event( event ).stop();
            alert('Please enter a place into the location field!');
        }
    },

    setLocation:function( lat, lng )
    {
        var point = new GLatLng( lat, lng );
        var marker = new GMarker(point, {icon:this.setupIcon('red'), draggable: true});
        if( this.marker ){
            this.marker = false;
            this.map.clearOverlays();
        }
        this.marker = marker;
        this.map.addOverlay( this.marker );
        GEvent.addListener(this.marker,'dragend',function() {
            this.updateCurrentPoint();
        }.bind(this));
    },

    updateCurrentPoint:function()
    {

        var lat = this.marker.getPoint().lat();
        var lng = this.marker.getPoint().lng();

        new Ajax("/js/functions/setMyLocation.php",{
            method:'post',
            data:'latitude=' + lat + '&longitude=' + lng ,
            onComplete:this.updateCurrentPointResponse.bind(this),
            onFailure:function( response ){ this.updateCurrentPointResponseError.bind(this); }
        }).request();

    },

    updateCurrentPointResponse:function()
    {

    },

    updateCurrentPointResponseError:function()
    {

    },

    setupLocalIcon:function()
    {
        var icon = new GIcon();
        icon.image = "/theme/connectorlocal/i/icons/sponsor/local.png";
        icon.iconSize = new GSize(16, 16);
        icon.iconAnchor = new GPoint(8, 16);
        icon.infoWindowAnchor = new GPoint(5, 1);
        this.icon = icon;
    },

    setupIcon:function(colorName) {
        var icon = new GIcon();
        icon.image = "http://labs.google.com/ridefinder/images/mm_20_" + colorName + ".png";
        icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        icon.iconSize = new GSize(12, 20);
        icon.shadowSize = new GSize(22, 20);
        icon.iconAnchor = new GPoint(6, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);
        return icon;
    },

    initMap:function( mapContainer, lat, lng )
    {
        if (GBrowserIsCompatible()) {
            this.map = new GMap2($( mapContainer ));
            connectorGlobalDirectoryMap = this.map;
            this.map.setCenter(new GLatLng( lat, lng ), 14);
            this.map.addControl(new GSmallMapControl());
            this.map.addControl(new GMapTypeControl());
        } else{
            alert('Your browser is not compatible with Google Maps.');
        } // end if
    }

});

var cl_FindMe = false;

function cl_mylocation_close(  ){
    cl_FindMe.closeWindow();
}
