if(typeof(TRENDERO) == 'undefined' ){
    TRENDERO = {};
}
TRENDERO.form = function(){

    var form = null;
    var geocoder = null;
    var mapped = false;

    function initFormEvents(){
        //clear forms on first focus 
        $(".clear_on_click").find("input[type='text'], textarea").bind('focus', function(e){
            var ele = $(this);
            if(!ele.hasClass("datepicker")){
                this.value = "";
                ele.unbind('focus');
            }
        });
        //datepicker
        $('.datepicker').datepicker({showOn: "both" , yearRange: "-100:+0", maxDate:"+0", buttonImageOnly:true, buttonImage:'/static/img/icon_calendar.jpg'});
        $('.trend_form_submit').bind('click', submitTrend); 
        $('.sighting_form_submit').bind('click', submitIfLoggedIn); 
        $('.trend_detail_submit').bind('click', submitIfLoggedIn); 
        $('.comment_form_submit').bind('click', submitIfLoggedIn); 
        $('.message_form_submit').bind('click', submitIfLoggedIn); 
        //add media button hover effects
        $(".media_buttons > img").bind('mouseover', function(e){
            this.src = this.src.replace("_grey.gif", "_black.gif");
        });
        $(".media_buttons > img").bind('mouseout', function(e){
            this.src = this.src.replace("_black.gif","_grey.gif") ;
        });
        $(".media_buttons > img").bind('click', function(e){
			$("." + this.className + "_form").show();
        });
        $(".close_media").bind('click', function(e){
			$(this.parentNode).hide();
        });
        $(".find_trends_submit").bind('click', TRENDERO.form.findTrends);
    }
        //geocode then submit in the callback 
        function submitTrend(){
            if (typeof(TRENDERO.ajax) != 'undefined'){
                if (TRENDERO.ajax.requiresLogin(this)) return;
            }
            form = this.form;
            var whereVal = form.where.value;
            geocoder.getLocations(whereVal, fillInLocationsAndSubmit);
        }
        function submitIfLoggedIn(){
            if (typeof(TRENDERO.ajax) != 'undefined'){
                if (TRENDERO.ajax.requiresLogin(this)) return;
            }
            this.form.submit();
        }
        function fillInLocationsAndSubmit(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>Okay</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";
                }
                form.lat.value = lat;
                form.lon.value = lon;
                form.country.value = country;
                form.state.value = state;
                form.city.value = city;
            }
            // if this is a sighting confirmation, close the map
            $('#confirm_sighting_map').css("display", "none");
            form.submit();
       }
    return {
        init: function(){
            //create a geocoder
            if (GBrowserIsCompatible()) {
                geocoder = new GClientGeocoder();
            }

            TitleTip.init();
            initFormEvents();
            //create the datepicker widget
        },
        //go to map with selected filters, geocode if necessary
        findTrends: function(){
            var whereVal = $('#find_trends_location').get(0).value;
			if (whereVal != "Location" && whereVal != "") {
	            geocoder.getLocations(whereVal, TRENDERO.form.getLocationAndGoToMap);
				return;
			}
			var selectCat = $('#find_trends_category').get(0);
            var category = selectCat.options[selectCat.selectedIndex].text;
            if (category == "Film & TV") {
            	category = "Film";
            }
			if (category != "Select a Category") {
				location.href = "/trends/category/" + category;
				return;
			}
            location.href = "/";
        },
        getLocationAndGoToMap: 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>Okay</td></tr></table>";
                LIGHTBOX.show(html, 'auto', {'lightbox_ok':LIGHTBOX.hide});
                return;
            } 
            place = response.Placemark[0];
            var lat = place.Point.coordinates[1];
            var lon = place.Point.coordinates[0];
			location.href = "/trends/location/?lat=" + lat + "&lon=" + lon;
		}
    }
}();

