/**
 * Author: Alan Hietala
 */

var searcher;
var geocoder;
var map;
var searchCache = new Array();
var isDragEnabled = false;  // do we let users drag the black star icon?
var latFieldId; // field to show the latitude in
var lngFieldId; // field to show the longitude in
var showAdditionalInformation = true;   // should we show the 'additional information box'?
var initialLat = 43;
var initialLng = -79;
var initialZoom = 5;

google.load('search', '1');


function getParameterByName( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

// Call this function when the page has been loaded
function initialize() {
    var searchControl = new google.search.SearchControl();
    searchControl.addSearcher(new google.search.LocalSearch());
        
    searchControl.draw(document.getElementById("sc"));
}


      
google.setOnLoadCallback(loadstuff);      



/**
 * Initialize.
 */
function loadstuff(){

    // see if there is a default latitude, longitude and zoom level to load by default.
    var qll = getParameterByName("ll");
    if (qll != "") {
        var z = getParameterByName("z");
        var ss = qll.split(',');
        initialLat = ss[0];
        initialLng = ss[1];
        if (z != "") {
            initialZoom = parseInt(z);
        }
    }

    //geocoder = new GClientGeocoder();
    map = new GMap2(document.getElementById("mymap"));
    map.setCenter(new GLatLng(initialLat,initialLng), initialZoom);
    map.addControl(new GSmallMapControl()); // zoom control
    map.addControl(new GMapTypeControl()); // types
    
    var sc = new google.search.SearchControl();
    var options = new google.search.SearcherOptions();
    options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
    
    
    searcher = new google.search.LocalSearch(options);
    searcher.setCenterPoint(map);
    searcher.setSearchCompleteCallback(null, placeSearchCallback);
    
    // hide more results initially
    $("#moreresults").css("display","none");
    $("#moreresults").click(function(){
        searcher.gotoPage(searcher.cursor.currentPageIndex+1);
        return false;
    });
    $(".searchresultscontainer").css("display","none");
    $("#findlink").click(function(){
        var query = $("#SearchText").val();
        doSearch(query);
        return false;
    });
}


/** execute the search */
function doSearch(query){
    searcher.execute(query);
}

/**
 * Called when the search is complete.
 */
function placeSearchCallback(){
        // clear the map
        map.clearOverlays();
        
        
        // clear error message
        $(".ssbus #searcherror").html("");
        // check if there are more results
       var nextPage = searcher.cursor!=null &&searcher.cursor.currentPageIndex <7 ? true : false;
        // hide instructions
        $(".instructions").css("display","none");
        $(".searchresultscontainer").css("display","block");
        // show more results
        if(nextPage){
            $("#moreresults").css("display","block");
        }
        searchResults = $("#searchresults");
        // clear search results if there are any
        searchResults.html("");
        if (!searcher.results || searcher.results.length == 0) {
               
                $("#searcherror").html('Sorry, we were unable to find "' + getSearchText() + '".  Hint: Try just an address, then add the name of the place after.');
        } else {
                var bb = null;
                
                

                // bounds to set the new map to.
                var bounds = new GLatLngBounds();

                for (var i=0; i < searcher.results.length; i++) {
                        bounds.extend(new GLatLng(searcher.results[i].lat,searcher.results[i].lng));
//                      
                        point = new GLatLng(searcher.results[i].lat, searcher.results[i].lng);


                        // make sure the marker has a letter on it
                        var letter = String.fromCharCode("A".charCodeAt(0) + i);
                        //searchCache[letter] = searcher.results[i];
                       
                        // first runthrough - display all the A,B,C,D markers on the map
                        var markerIcon = null;
                        markerIcon = new GIcon(G_DEFAULT_ICON, "/i/selfserve/pin"+letter+".png");
                        markerIcon.iconSize = new GSize(20,20);
                        markerIcon.iconAnchor = new GPoint(10,10);
                        markerIcon.shadowSize = new GSize(20,20);
                        markerOptions = { icon:markerIcon };
                      
                       
                        

                        // add the point to the map
                        marker = new GMarker(point, markerOptions);
                       
                        map.addOverlay(marker);
                        map.labelText = i.toString();
                        
                        // calculate the bounding box
                        if (bb == null) { bb = new GLatLngBounds(point, point); }
                        else { bb.extend(point); }


                        // if this is the default selected item, add the black star pin overtop of it
                        if (letter === 'A') {
                            addStarMarker(map, point, searcher.results[i]);
                            bb.extend(point);
                        }

                       
                   
                        var placeName = searcher.results[i].titleNoFormatting; //getPlaceName(place);
                        var placeAddress = searcher.results[i].addressLines.join(",");
                       
                        var results = $(document.createElement("div"));
                        results.addClass("k");
                        
                        var k1 = $(document.createElement("span"));
                        k1.addClass("k1");
                        var radiobtn;
                        if(letter == "A"){
                            try{
                                radiobtn = $(document.createElement("<input id='result"+i.toString()+"select' type='radio' name='radiogr' value='"+letter+"' checked='true'>"));
                            }catch(ex){
                                // lets do this the normal way. I hate IE
                                radiobtn = $(document.createElement("input"));
                                radiobtn.attr("type","radio");
                                radiobtn.attr("name","radiogr");
                                radiobtn.attr("id","result"+i.toString()+"select");
                                radiobtn.val(letter);
                                radiobtn.checked = true;
                            }
                        }else{
                            try{
                                radiobtn = $(document.createElement("<input id='result"+i.toString()+"select' type='radio' name='radiogr' value='"+letter+"' >"));
                            }catch(ex){
                                radiobtn = $(document.createElement("input"));
                                radiobtn.attr("type","radio");
                                radiobtn.attr("name","radiogr");
                                radiobtn.attr("id","result"+i.toString()+"select");
                                radiobtn.val(letter);
                                radiobtn.checked = false;
                            }
                        }
                        
                       
                        
                        
                        if(letter == "A"){
                            radiobtn.attr("checked","true");
                        }
                        k1.append(radiobtn);
                        
                        results.append(k1);
                        
                       results.append("<span class='k2'>"+letter+") </span>");
                       results.append("<span class='k3'>"+placeName+"</span>");
                        results.append("<span class='k4'>"+placeAddress+"</span>");
                    
                        // add the result to the searchCache. We need it later if this item is selected;
                        
                        searchCache[letter] = searcher.results[i];
                      
 
                      
                     searchResults.append(results);
                   
                     radiobtn.click(function(){
                        $(".additionalinfo").find("input").each(function(){
                            $(this).val("");
                        });
                        if (showAdditionalInformation === true) {
                            $(".additionalinfo").css("display","block");
                        }
                        // fill out the other fields in additional info section
                        
                        var dataItem = searchCache[$(this).val()];
                        updateLatLng(dataItem.lat, dataItem.lng);
                        $("#locationname").val(dataItem.titleNoFormatting);
                        $("#locationdescription").val("");
                        $("#locationaddress").val(dataItem.addressLines[0]+", "+dataItem.addressLines[1]);
                        $("#locationphone").val((dataItem.phoneNumbers!=null && dataItem.phoneNumbers.length > 0) ? dataItem.phoneNumbers[0].number : "");
                        $("#locationwebsite").val("");
                        
                        //redraw the map
                        redrawMap();
                     });
                     
                     // set the first object as the selected one
                     
                     $(".additionalinfo").find("input").each(function(){
                            $(this).val("");
                        });
                        if (showAdditionalInformation === true) {
                            $(".additionalinfo").css("display","block");
                        }
                        // fill out the other fields in additional info section
                        
                        // hide the first cancel button
                      $(".ssbus #closemap").css("display","none");
                        var dataItem = searchCache["A"];
                        $("#locationname").val(dataItem.titleNoFormatting);
                        $("#locationdescription").val("");
                        $("#locationaddress").val(dataItem.addressLines[0]+", "+dataItem.addressLines[1]);
                        
                        $("#locationphone").val((dataItem.phoneNumbers!=null && dataItem.phoneNumbers.length > 0) ? dataItem.phoneNumbers[0].number : "");
                        $("#locationwebsite").val("");
                     var sObject = searcher.results[i];
                   
                }
                
                
                // attach the edit in place code
               // setClickable();

                // bump out the default zoom by 1 for space...
                map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds) - 1);

    }

}

/**
 * Update the lat/lng fields on the bottom of the map if they exist
 */
function updateLatLng(lat, lng) {
    var latf = $('#' + latFieldId);
    var lngf = $('#' + lngFieldId);
    if (latf && lngf) {
        latf.html(lat);
        lngf.html(lng);
    }
}


function addStarMarker(map, point, searchresult) {
    markerIcon = new GIcon(G_DEFAULT_ICON, "/i/jsmap/pins/none-pin.png");
    markerIcon.iconSize = new GSize(24,32);
    markerIcon.iconAnchor = new GPoint(12,32);
    markerOptions = { icon:markerIcon, draggable:isDragEnabled };
    marker = new GMarker(point, markerOptions);
    updateLatLng(point.lat().toFixed(6), point.lng().toFixed(6)); 
    attachDragHooks(marker, searchresult);
    map.addOverlay(marker);
}

/**
 * Allow dragging of the marker
 */
function attachDragHooks(marker, searchresult) {
    if (isDragEnabled === true) {
        (function(marker, searchresult) {
            GEvent.addListener(marker, "dragstart", function() { });
            
            GEvent.addListener(marker, "dragend", function(latlong) {
                // update the lat/lng that will be cached..
                //var t = searchresult;
                //t.lat = latlong.lat();
                //t.lng = latlong.lng();
         
                updateLatLng(latlong.lat().toFixed(6), latlong.lng().toFixed(6)); 
//                $('#' + latFieldId).html(latlong.lat().toFixed(6));
//                $('#' + lngFieldId).html(latlong.lng().toFixed(6));
            });
        }) (marker, searchresult);
        
    }
}

function redrawMap(){
    var letter = $("#searchresults .k .k1 input:radio:checked").val();
    var numresults = $("#searchresults input:radio").size();
    // clear the map
    map.clearOverlays();
    
    
    for(var x = 0;x<numresults;x++){
        
        var arrayindexletter = String.fromCharCode("A".charCodeAt(0) + x);
      
        var item = searchCache[arrayindexletter];
        var point = new GLatLng(item.lat, item.lng);
        var markerIcon = null;
        markerIcon = new GIcon(G_DEFAULT_ICON, "/i/selfserve/pin"+arrayindexletter+".png");
        markerIcon.iconSize = new GSize(20,20);
        markerIcon.iconAnchor = new GPoint(10,10);
        markerIcon.shadowSize = new GSize(20,20);
        markerOptions = { icon:markerIcon };

        // add the point to the map
        marker = new GMarker(point, markerOptions);
        map.addOverlay(marker);
        
        if (letter == arrayindexletter) {
            addStarMarker(map, point, item);
        }
        
    }
    
    
}

function getPlaceForGooglePlaceSuccess(xhr,args){
   
    // add item to the dom 
   var title = $("#locationname").val();
   var category = "";
   var address = $("#locationaddress").val();
   var url = xhr.href;
   var description = $("#locationdescription").val();
   
   
   var addBlock = "<div class='ssbus_alock'>"
                  +  "<div class='placeid'><input type='hidden' value='"+xhr.placeId+"' /></div>"
                  +  "<div class='placeitemid'><input type='hidden' value='"+xhr.placeItemId+"' /></div>"
                 +"<div class='f1'>"
               + "<div class='q'></div>"
              +"</div> <!-- /f1 -->"
                +"<div class='f2'>"
                +"<div class='q'>"+title+"</div>"
                +"<div class='w'>"+category+"</div>"
                +"<div class='e'>"+address+"</div>"
                +"<div class='r'>"
                 +   "<a href='"+url+"'>PlanetEye Guide</a></div>"
              +"</div> <!-- /f2 -->"


              +"<div class='f3'>"
               + "<div class='q'>"+description+"</div>"
              +"</div> <!-- /f3 -->"


              +"<div class='f4'>"
               + "<div class='q'><a class='editlink' href='#'>edit</a></div>"
               + "<div class='w'><a class='removelink' href='#'>remove</a></div>"
              +"</div> <!-- /f4 -->"


              +"<div class='clear'></div>"
              +"</div> <!-- /ssbus_alock -->";
              
   // attach the block
   var container = $(".ssbus_locks");
   container.prepend(addBlock);
   
   // attach the click events
   container.find(".ssbus_alock").eq(0).find(".removelink").click(removeLinkClick);
   container.find(".ssbus_alock").eq(0).find(".editlink").click(editLinkClick);
   refreshMap();
   
   // close the block 
   
   closeSearchBox();
}



function getSearchText(){

return $("#SearchText").val();
}


/**
 * Function to bind to the remove button on the 
 * list of places contained in the map.
 */
function removeLinkClick(eventObject){
   
        // get the placeId 
        var parentDiv = $(this).parents(".ssbus_alock");
        var pId = parentDiv.find(".placeid input").val();
        var tpkId = $("#HiddenFieldTravelPackId").val();
        
        var args = new Object();
        args.removeDiv = parentDiv;
        
        planeteye.map.services.pointRemoveFromSet("map."+tpkId.toString(), "place."+pId,0, removePlaceSuccessHandler, function(){}, args)
        
        // remove the place
        return false;
    

}

function editLinkClick(eventObject){
    // get the placeId 
        
        
        
        
        var parentDiv = $(this).parents(".ssbus_alock");
        
        // hide the remove and edit buttons
        parentDiv.find(".f4").css("display","none");
        
        var titleDiv = parentDiv.find(".f2 .q");
        var descDiv = parentDiv.find(".f3 .q");
        
        parentDiv.find(".f2 .sub").css("display","none");
        
        var title = titleDiv.html();
        var desc = descDiv.html();
        
        titleDiv.html("<label>Title:</label> <input type='text' value='"+$.trim(title)+"' />");
        descDiv.html("<label>Your Note:</label><textarea rows='6' cols='50'>"+ $.trim(desc)+"</textarea><br />");
        
        var saveLink = $(document.createElement("a"));
        var cancelLink = $(document.createElement("a"));
        
        saveLink.html("save");
        saveLink.attr("href","#");
        saveLink.addClass("savelink");
        saveLink.click(function(){
                        saveLinkClick(parentDiv);
                        return false;
                        });
        
        cancelLink.html("cancel");
        cancelLink.attr("href","#");
        cancelLink.addClass("cancellink");
        cancelLink.click(function(){
                cancelLinkClick(title,desc,parentDiv);
                return false;
        });
        
        descDiv.append(saveLink);
        descDiv.append(cancelLink);
        // set the two sections editable
        
        
        // set up the save button
        return false;

}


function cancelLinkClick(title,description,parentDiv){
        var titleDiv = parentDiv.find(".f2 .q");
        var descDiv = parentDiv.find(".f3 .q");
        
        titleDiv.html(title);
        descDiv.html(description);
        parentDiv.find(".f4").css("display","block");
        parentDiv.find(".f2 .sub").css("display","block");
        // show the edit/delete buttons
        
        
    
    

}

function saveLinkClick(parentDiv){

       
        var pItemId = parentDiv.find(".placeitemid input").val();
        var tpkId = $("#HiddenFieldTravelPackId").val();
        var titleDiv = parentDiv.find(".f2 .q");
        var descDiv = parentDiv.find(".f3 .q");
        
        var title = escape(titleDiv.find("input").val());
        var desc = escape(descDiv.find("textarea").val());
        var args = new Object();
        args.mainDiv = parentDiv;
        args.title = title;
        args.desc = desc;
        planeteye.map.services.updateTPKPlaceItem(tpkId, pItemId, title, desc, saveSuccessHandler, function(){}, args);
}

function saveSuccessHandler(xhr,args){
  
    var mainDiv = args.mainDiv;
    mainDiv.find(".f2 .q").html(unescape(args.title));
    mainDiv.find(".f3 .q").html(unescape(args.desc));
    
    mainDiv.find(".f4").css("display","block");
    mainDiv.find(".f2 .sub").css("display","block");
    refreshMap();
}
/**
 * Success handler for when the remove button is clicked on an item
 */
function removePlaceSuccessHandler(xhr, args){
    
    args.removeDiv.remove();
    refreshMap(); 

}

function refreshMap(){
    
    GEvent.trigger(GoogleMapControl1_map.map,"planeteye.map.refresh");
    GEvent.trigger(GoogleMapControl1_map.map,"moveend");
    
}

function closeSearchBox(){
    $("#locationname").val("");
    $("#locationdescription").val("");
    $("#locationaddress").val("");
    $("#locationphone").val("");
    $("#locationwebsite").val("");
    $("#SearchText").val("");
    // reset the help text in the search box
    $(".instructions").css("display","block");
    $(".searchresultscontainer").css("display","none");
    $(".ssbus .ssbus_crea").toggle();
    $(".additionalinfo").css("display","none");
    $(".ssbus .newlocation").toggle();
    return false;

}

function validateFields(){
    var name = $("#locationname").val();
    var address = $("#locationaddress").val();
    var errors = new Array();
    if(name == "")
        errors.push("Name is blank");
        
    if(address == "")
        errors.push("Address is blank");
        
    if(errors.length > 0){
        // display the errors
        return false;
    }else{
        return true;
    }

}
