if(typeof(TRENDERO) == 'undefined' ){
    TRENDERO = {};
}
//module pattern
TRENDERO.map = function(){
    var geocoder = null;
    var whereVal = "";
    var mapId = null;
    var domainKeys = {
       	"192.168.1.50:9000" : "ABQIAAAAcoYFzpVJrbQGegTmM6a2GxSIxxZ8gS94VsQaquyGXf1LoaHY9RSOfC8OXGLOJHgPUAiqYdT-tKJWMA",
       	"76.22.239.54:9000" : "ABQIAAAAcoYFzpVJrbQGegTmM6a2GxQDkmBiALXud8EO2iPl_K_RVh9SMxQLdqM40f_DIvb9eT3HcyyuQVA7xw",
       	"localhost:9000" : "ABQIAAAA_tNJxbuOTVP9zXIOWA8SKRTneACZCPyRKHrLBh9DasPkWTJK_RToLpTV-TZqRGCIU6GHN31zNL5X9A",
    	"localhost:8080" : "ABQIAAAA_tNJxbuOTVP9zXIOWA8SKRTwM0brOpm-All5BF6PoaKBxRWWERQCOAQ99V8prqNz_FnIiFTqM-DbVA",
    	"localhost:8000":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxQCULP4XOMyhPd8d_NrQQEO8sT8XBQE5wKQ4flw5hVY1RufSAtiosCLzA",
        "trendero.pentura.ca":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxQyI8dxR43Gd3tDj6Zn_z1zPf7yghTlVgezgoYvxcSNG5hFUOSZHwmr6A",
        "devtest.pentura.ca":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxRMW56qwuPaajxd8c-yoMTjxi3oZhRp4fs1_bAI4qK2RUel9_5vK9giTg",
        "dev.trendero.com.s3.amazonaws.com":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxQGJZ1XlP4QzdZyesNDurYlopisKBR2jCyz7Df0A7SO5hckYwBr5kAvYg",
        "72.32.11.11":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxR21qKAMjrs2Q0zOYqzGNslPEd7oRReGvYs5DDWIaUY68S8W2iRm1if0g",
        "trendero.com":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxRNdquucztpla-5bBqq10eZhAjlQBQ9lcDsMaD82pvr-STvCSfkesw1oQ",
        "www.trendero.com":"ABQIAAAAq6EMMcEDwuvTtKeFgSl6YxSU9Vcrm-NEtBirkSj-XHNbNQX0KRRhENt2OMt3QIy6QZLHAc1upf_8pA",
	"184.106.169.200":"ABQIAAAAqa5GFVJY4GbQ6UMK34XNLRRGi5SYH4wTO14Q_sKe0bTrNSWTbxQjoyTcmxYXeFKYlxSnM3mFe_4FhQ"
    }

    function initMapEvents() {
        $(".change_location_submit").bind('click', TRENDERO.map.changeLocation);
        //create a geocoder
        if (GBrowserIsCompatible()) {
            geocoder = new GClientGeocoder();
        }
    }

    function getFlashMovie(movieName) {
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        return (isIE) ? window[movieName] : document[movieName];
    }

    function createFlashMap(opts) {
            var src = opts.src;
            var id = opts.id;
            var minVersion = opts.minVersion;
            var width = opts.width;
            var height = opts.height;
			var domain = "http://" + window.location.host;
			var idx = domain.indexOf("?");
			if (idx != -1)
				domain = domain.substring(0, idx);
            
            var flashVars = "key="+domainKeys[window.location.host]+"&domainName="+domain;
            if(opts.lat){
                flashVars += "&lat="+opts.lat;
            }
            if(opts.lon){
                flashVars += "&lon="+opts.lon;
            }
            if(opts.trendId){
                flashVars += "&trendId="+opts.trendId;
            }
            if(opts.category){
                categoryId = opts.category.id;
                flashVars += "&categoryName="+ opts.category.name + "&categoryId="+opts.category.id;
            }
            if(opts.tag){
                tagId = opts.tag.id;
                flashVars += "&tagName="+opts.tag.name + "&tagId="+opts.tag.id;
            }
            var src = opts.src;
            var params = {menu:"false", wmode:"opaque", flashVars: flashVars, allowScriptAccess:"always"};
            var attrs = {id:opts.id, name:opts.id};
            swfobject.embedSWF(src, id, width, height, minVersion, "expressInstall.swf", flashVars, params, attrs);
    }

    //public
    return {
        getDomainKeys: function(){return domainKeys},
        init: function(opts){
            // save the trend id
            mapId = opts.id;
            //create the flash map
            createFlashMap(opts)
            initMapEvents();
        },
        changeLocation: function() {
            //whereVal = $('#change_location').get(0).value;
            whereVal = $('#id_where').get(0).value;
            if (whereVal != "" && whereVal != "Where?")
                geocoder.getLocations(whereVal, TRENDERO.map.getLocationAndMap);
            else alert ("Please enter a location");
        },
		getLocationAndMap: function(response){
            if (!response || response.Status.code != 200) {
                var html = "<div class='lightbox_message'>Sorry, we were unable to geocode that address. Try being more specific ie. Paris, France instead of just Paris.</div><table class='lightbox_buttons'><tr><td><img id='lightbox_ok' class='lightbox_button' src='/static/img/button_yes.jpg'></td></tr><tr><td>Ok</td></tr></table>";
                LIGHTBOX.show(html , {'lightbox_ok':LIGHTBOX.hide});
                return;
            } 
            else {
                place = response.Placemark[0];
                var lat = place.Point.coordinates[1];
                var lon = place.Point.coordinates[0];
                var country = place.AddressDetails.Country.CountryName;
                var state;
                var city;
                var aa = place.AddressDetails.Country.AdministrativeArea;
                if(aa != undefined) {
                    state = aa.AdministrativeAreaName;
                    var locality = aa.Locality;
                    if(locality != undefined) {
                        city = locality.LocalityName;
                    }
                    else {
                        city = "Unknown";
                    }
                }
                else {
                    state = "Unknown";
                    city = "Unknown";
                }
                var sighting_confirm = false;
                // get the trend form or the user form and save the location data
                var form = $('#edit_trend_form').get(0);
                if (!form) {
                    // for edit_user
                    form = $('#edit_user_form').get(0);
                    if (!form) {
                        // for sighting
                        form = $("#add_sighting_form").get(0);
                        if (form) sighting_confirm = true;
                        else {
                            alert ("Error finding form to save location information");
                            return;
                        }
                    }
                }
                // fill in the hidden values
                form.lat.value = lat;
                form.lon.value = lon;
                form.city.value = city;
                form.state.value = state;
                form.country.value = country;

                // show the result on the map
                // note that ie6 finds an object for getFlashMovie("confirm_map") even before it is created
                // but (getFlashMovie("confirm_map").jsRequest == undefined) always fails so it creates a new map each time
                if (sighting_confirm && (!getFlashMovie("confirm_map") || getFlashMovie("confirm_map").jsRequest == undefined)) {
                    // make confirmation map visible
                    $('#confirm_sighting_map').get(0).style.display = "block";
                    // load the swf
                    createFlashMap({src:"/static/swf/SightingsMap.swf", id:"confirm_map", minVersion:"8", width:"100%", height:"100%", lat:lat, lon:lon});
                }
                else {
				    var req = '{"requestType":"confirm","lat":'+lat+',"lon":'+lon+'}';
				    getFlashMovie("confirm_map").jsRequest(req);
                }
			}
		}
    }
}();

