
//<![CDATA[

// create HTML for poiNav
var poiNavHTML = '<a href="maps.xml"><img id="map-rss" src="/img/icons/rss.png" width="17" height="17" alt="Get the latest updates via RSS"/></a><img src="/img/main/show-nearby.gif" width="126" height="29" alt="Show nearby..." /><br />'
+'<a href="#" onclick="return boxclick(\'cafe\')"><img src="/img/main/blank.gif" id="show_cafe" class="mapButton" width="87" height="25" alt="Show cafes" /></a><a href="#" onclick="return boxclick(\'pub\')"><img src="/img/main/blank.gif" id="show_pub" class="mapButton" width="80" height="25" alt="Show pubs" /></a><a href="#" onclick="return boxclick(\'restaurant\')"><img src="/img/main/blank.gif" id="show_restaurant" class="mapButton" width="121" height="25" alt="Show restaurants" /></a><br />'
+'<img src="/img/main/or-drag-icon.gif" width="288" height="58" alt="Or drag and icon to add a location" /><br />'
+'<div id="cafe_drag"><img src="/img/icons/cafe_drag.png" alt="" id="cafeadd" class="draggable" /></div><div id="pub_drag"><img src="/img/icons/pub_drag.png" alt="" id="pubadd" class="draggable" /></div ><div  id="restaurant_drag"><img src="/img/icons/restaurant_drag.png" alt="" id="restaurantadd" class="draggable" /></div >';

//then add to poiNav container
$('poiNav').innerHTML = poiNavHTML;
// Create our custom icons
var chromaIcon = new GIcon();
chromaIcon.image = "http://chromaagency.com/img/icons/home.png";
chromaIcon.iconSize = new GSize(84, 38);
chromaIcon.iconAnchor = new GPoint(9, 3);
chromaIcon.infoWindowAnchor = new GPoint(9, 3);
// Set up GMarkerOptions object literal
var homeMarkerOptions = { 
    icon:chromaIcon
};
var cafeIcon = new GIcon();
cafeIcon.image = "http://chromaagency.com/img/icons/cafe.png";
cafeIcon.iconSize = new GSize(20, 20);
cafeIcon.iconAnchor = new GPoint(10, 10);
cafeIcon.infoWindowAnchor = new GPoint(10, 10);
// Set up GMarkerOptions object literal
var cafeMarkerOptions = { 
    icon:cafeIcon
};

var cafeDragIcon = new GIcon();
cafeDragIcon.image = "http://chromaagency.com/img/icons/cafe_drag.png";
cafeDragIcon.iconSize = new GSize(20, 20);
cafeDragIcon.iconAnchor = new GPoint(10, 10);
cafeDragIcon.infoWindowAnchor = new GPoint(10, 10);
cafeDragIcon.draggable = true;
// Set up GMarkerOptions object literal
var cafeDragMarkerOptions = {
    icon:cafeDragIcon,
    draggable: true
};

var pubIcon = new GIcon();
pubIcon.image = "http://chromaagency.com/img/icons/pub.png";
pubIcon.iconSize = new GSize(20, 20);
pubIcon.iconAnchor = new GPoint(10, 10);
pubIcon.infoWindowAnchor = new GPoint(10, 10);
// Set up GMarkerOptions object literal
var pubMarkerOptions = { 
    icon:pubIcon
};

var pubDragIcon = new GIcon();
pubDragIcon.image = "http://chromaagency.com/img/icons/pub_drag.png";
pubDragIcon.iconSize = new GSize(20, 20);
pubDragIcon.iconAnchor = new GPoint(10, 10);
pubDragIcon.infoWindowAnchor = new GPoint(10, 10);
pubDragIcon.draggable = true;
// Set up GMarkerOptions object literal
var pubDragMarkerOptions = {
    icon:pubDragIcon,
    draggable: true
};

var restaurantIcon = new GIcon();
restaurantIcon.image = "http://chromaagency.com/img/icons/restaurant.png";
restaurantIcon.iconSize = new GSize(20, 20);
restaurantIcon.iconAnchor = new GPoint(10, 10);
restaurantIcon.infoWindowAnchor = new GPoint(10, 10);
// Set up GMarkerOptions object literal
var restaurantMarkerOptions = { 
    icon:restaurantIcon
};

var restaurantDragIcon = new GIcon();
restaurantDragIcon.image = "http://chromaagency.com/img/icons/restaurant_drag.png";
restaurantDragIcon.iconSize = new GSize(20, 20);
restaurantDragIcon.iconAnchor = new GPoint(10, 10);
restaurantDragIcon.infoWindowAnchor = new GPoint(10, 10);
restaurantDragIcon.draggable = true;
// Set up GMarkerOptions object literal
var restaurantDragMarkerOptions = {
    icon:restaurantDragIcon,
    draggable: true
};

// create array of markers and icons
var gmarkers = [];
var gicons = [];
// array of buttons states for 'show nearby' buttons'
var buttonsToggle = [];

// add marker options to associative gicons array
gicons["home"] = homeMarkerOptions;
gicons["cafe"] = cafeMarkerOptions;
gicons["cafedrag"] = cafeDragMarkerOptions;
gicons["pub"] = pubMarkerOptions;
gicons["pubdrag"] = pubDragMarkerOptions;
gicons["restaurant"] = restaurantMarkerOptions;
gicons["restaurantdrag"] = restaurantDragMarkerOptions;

buttonsToggle["cafe"] = false;
buttonsToggle["pub"] = false;
buttonsToggle["restaurant"] = false;

var home= new GLatLng(51.49985,-0.08475);
var geocoder;
var bounds;
var address = "Address not found";
var map = new GMap2($("map"));
if (GBrowserIsCompatible()) {
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.setCenter(home, 15, G_NORMAL_MAP);
    geocoder = new GClientGeocoder();
    bounds = new GLatLngBounds();

    GEvent.addListener(map, "addmarker", function(category, e){
        //if (!overlay) {
        //createMarker(point, "tester", "home");
        //script for detecting the mouse coordinate
        var posx = 0;
        var posy = 0;


        if (!e) var e = window.event;
        if (e.pageX || e.pageY) 	{
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY) 	{
            posx = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
        }
        // get offset of map container (prototype method)
        var mapElement = $('map');
        var mapOffset = mapElement.cumulativeOffset();

        // get lat lng from pixel coords where pixel is cursor position minus map div offset
        var newPoint = new GPoint(posx - mapOffset[0], posy - mapOffset[1]);
      
        var latlng = map.fromContainerPixelToLatLng(newPoint);
     
        openInputBox(latlng, category);
    });
}
// create scriptaculous draggable icons
new Draggable('cafeadd', {
    ghosting: true,
    zindex:0,
    revert:true
});
new Draggable('pubadd', {
    ghosting: true,
    zindex:0,
    revert:true
});
new Draggable('restaurantadd', {
    ghosting: true,
    zindex:0,
    revert:true
});

Droppables.add('map', {
    accept: 'draggable',
    onDrop: function(drag, drop, e) {
        // get the css id of the dropped element take the 'add' off the end which gives us the category of the marker
        var cat = drag.id.replace("add","");
        GEvent.trigger(map, "addmarker", cat, e);
    }
});

var homeMarker = createMarker(home, ["<b>Chroma Agency</b><br />1.1.2 The Leathermarket<br />Weston Street<br />London<br />SE1 3ER"], 'home');
// get exisitng locations and add to map
populateMap();
function createMarker (point, htmls, category)
{
    var marker = new GMarker(point, gicons[category]);

    // === Store the category and name info as a marker properties ===
    marker.mycategory = category;
    //marker.myname = name;

    GEvent.addListener(marker, "click", function(){
        var tabs = [];
        var labels = ['Info', 'Description'];
        // add tabs and content and add width div to all tabs
        for (var i=0; i<htmls.length; i++) {
            tabs.push(new GInfoWindowTab(labels[i],'<div class="mapInfo" style="width:280px;height: 100px;">' + htmls[i] + '</div>'));
        }
        marker.openInfoWindowTabsHtml(tabs);
    }
    );

    gmarkers.push(marker);
    map.addOverlay(marker);
    return marker;
}
function openInputBox(point, category){
    //var win = new Window({id: "voteWindow", url: "ChroMaS/addtomap.php?lat="+latlng.lat()+"&lng="+latlng.lng()+"&address="+address+"&cat="+category, width:440, top: 107, minHeight: 352, destroyOnClose: true});
    //win.showCenter({modal:true});
    //return false;
    var marker = new GMarker(point, gicons[category+"drag"]);
    GEvent.addListener(marker, "dragend", function(){
        point = marker.getLatLng();
        if (point){
            writeHTML(marker, point);
        }
    });

    gmarkers.push(marker);
    map.addOverlay(marker);
    // === Store the category and name info as a marker properties ===
    marker.mycategory = category;
    writeHTML(marker, point);
    function writeHTML(marker, point){
        //Effect.Fade('poiNav', { duration: 0.3 });
        $('poiNav').style.display = 'none';
        var poiFormHTML = '<img src ="/img/main/add-'+ marker.mycategory+'.gif" width="271" height="22" alt="add details" /><a href="#" onclick="closeInputBox(false); return false;"><img src="/img/main/blank.gif" id="closeIcon" width="18" height="19" alt="Close" /></a><br />'
        +'<img src="/img/main/add-details-hr.gif" width="288" height="12" alt="" />'
        +'<span id="poiResult"></span>'
        +'<span id="errDiv"></span>'
        +'<form method="post" id="poiForm" onsubmit="return poiFormValidate(this);">'
        +'<input type="text" name="poi_name" id="poi_name" value="Name" onblur="if(this.value==\'\'){this.value=\'Name\'};" onfocus="if(this.value==\'Name\'){this.value=\'\'};" /><br />'
        +'<input type="text" name="poi_address" id="poi_address" value="Address" onblur="if(this.value==\'\'){this.value=\'Address\'};" onfocus="if(this.value==\'Address\'){this.value=\'\'};" /><br />'
        +'<input type="text" name="poi_website" id="poi_website" value="Website" onblur="if(this.value==\'\'){this.value=\'Website\'};" onfocus="if(this.value==\'Website\'){this.value=\'\'};" /><br />'
        +'<textarea name="poi_desc" id="poi_desc" onblur="if(this.value==\'\'){this.value=\'Description\'};" onfocus="if(this.value==\'Description\'){this.value=\'\'};" >Description</textarea><br />'
        +'<input type="hidden" name="lat" value="'+ point.lat()+'" /><input type="hidden" name="lng" value="'+ point.lng()+'" /><input type="hidden" name="cat" value="'+ marker.mycategory+'" />'
        +'<input type="image" src="/img/main/blank.gif" width="87" height="24" name="poi_submit" id="poi_submit" value="Submit" />'
        +'</form>';

        $('poiNav').innerHTML = poiFormHTML;
        Effect.Appear('poiNav', { 
            duration: 0.7
        });

    }
}

function closeInputBox(hideMarkers)
{
    //nasty hack that refreshes page only if IE due to bug where draggables not working after DOM edit
    var browser=navigator.appName;
    if(browser.indexOf("Microsoft") != -1) {
        //poiNavHTML += "<p style=\"clear: left;\">As an IE user you may need to refresh the page to be able to drag icons. We are working on a fix</p>";
        window.location = 'index.php';

    }
    else {
        // replace poiNav with original form HTML
        $('poiNav').style.display = 'none';
        $('poiNav').innerHTML = poiNavHTML;
        Effect.Appear('poiNav', {
            duration: 0.5
        });
        // pop most recent added marker
        gmarkers.pop().hide();
        // check if hideMarkers is true then hide any exisitng markers
        if(hideMarkers == true) {
            hideAll();
        }
        // then repopulate map in event of new marker added
        populateMap();
        // create scriptaculous draggable icons
        new Draggable('cafeadd', {
            ghosting: true,
            zindex:0,
            revert:true
        });
        new Draggable('pubadd', {
            ghosting: true,
            zindex:0,
            revert:true
        });
        new Draggable('restaurantadd', {
            ghosting: true,
            zindex:0,
            revert:true
        });

        for(description in buttonsToggle) {

            if (buttonsToggle[description]) {
                show(description);
            }
            else{
                hide(description);
            }
        }
    }
}

// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
    for (var i=0; i<gmarkers.length; i++) {
        if (gmarkers[i].mycategory == category) {
            gmarkers[i].show();
        }
    }
    $("show_" + category).style.backgroundImage = "url(/img/buttons/"+ category + "_button_over.png)"
    buttonsToggle[category] = true;
// == check the checkbox ==
//$(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
    for (var i=0; i<gmarkers.length; i++) {
        if (gmarkers[i].mycategory == category) {
            gmarkers[i].hide();
        }
    }
    // == clear the checkbox ==
    //$(category+"box").checked = false;
    // == close the info window, in case its open on a marker that we just hid
    $("show_" + category).style.backgroundImage = "url(/img/buttons/"+ category + "_button.png)"
    buttonsToggle[category] = false;
    map.closeInfoWindow();
}
function hideAll() {
    for (var i=0; i<gmarkers.length; i++) {
        if (gmarkers[i].mycategory != 'home' && gmarkers[i].isHidden() == false) {
            gmarkers[i].hide();
        //$(category+"box").checked = false;
        }
    }
}
// == a checkbox has been clicked ==
function boxclick(category) {
    if (buttonsToggle[category]) {
        hide(category);
    } else {
        show(category);
    }
  
    return false;
}

function populateMap() {
    var searchUrl = 'http://chromaagency.com/inc/ChroMaS/searchmap.php';
    GDownloadUrl(searchUrl, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName('marker');

        if(markers.length > 0)
        {
            for (var i = 0; i < markers.length; i++) {
                var name = markers[i].getAttribute('name');
                var bubble_content = markers[i].getAttribute('bubble_content');
                var distance = parseFloat(markers[i].getAttribute('distance'));
                var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                    parseFloat(markers[i].getAttribute('lng')));
                var category = markers[i].getAttribute('category');
                var description = markers[i].getAttribute('description');
                // create the markers but hide them
                var tempMark = createMarker(point, [bubble_content, description], category);
                tempMark.hide();
            }
        }
    });
}

// poi form valid flag
var poiFormValid;
// highlighting send to friend form validation
function poiFormHighlight (inputField, textAlert)
{
    $('poi_name').style.borderColor = '#fff';
    $('poi_name').style.backgroundColor = '#fff';
    $('poi_address').style.borderColor = '#fff';
    $('poi_address').style.backgroundColor = '#fff';

    poiFormValid = false;
    var errmsg = document.createElement('p');
    errmsg.id = 'err';
    var msg = document.createTextNode(textAlert);
    errmsg.appendChild(msg);
    // check if element with id 'err' exisits, if not then create it
    if ($('err')) {
        $('errDiv').removeChild($('err'));
    }
    $('errDiv').appendChild(errmsg);

    var inputbox = $(inputField);
    inputbox.style.borderColor = '#9f0369';
    inputbox.style.backgroundColor = '#efd4e5';
    inputbox.focus();
}
// check for valid send to friend form
function poiFormValidate(pageForm) {

    poiFormValid = true;
    if (pageForm.poi_address.value == "" || pageForm.poi_address.value == "Address")
    {
        poiFormHighlight('poi_address', 'Please an address');
    }
    else if (pageForm.poi_name.value == "" || pageForm.poi_name.value == "Name")
    {
        poiFormHighlight('poi_name', 'Please the location name');
    }
  
    if (poiFormValid) {
        // AJAX form submission
        var serialForm = Form.serialize('poiForm');
        var url = '/inc/ChroMaS/addtomap.php';
        var params = serialForm;

        $('poiNav').style.display = 'none';

        var ajax = new Ajax.Updater(
        {
            success: 'poiNav'
        },
        url,
        {
            method: 'post',
            parameters: params,
            onFailure: reportError
        });
        Effect.Appear('poiNav', {
            duration: 0.7
        });

        setTimeout("closeInputBox(true)", 2000);
    }
    return false;
  
}
// alert box if AJAX error
function reportError(request) {
    alert("There was an error with your submission. Please try again" + request);
}
//]]>
