addDOMLoadEvent(roundCorners);
addDOMLoadEvent(setupMap);
addDOMLoadEvent(setupLinkDeleteButtons);
addDOMLoadEvent(setupTabs);
addDOMLoadEvent(setupTagAjax);
addDOMLoadEvent(setupMakeChangesAjax);
addDOMLoadEvent(setupNicEdit);
addDOMLoadEvent(setupShowHide);
addDOMLoadEvent(formAddressFeatures);
addDOMLoadEvent(setupSearchAjax); //1.1.002

//1.1.002
function setupSearchAjax()
{
    if ($('siteSearch'))
    {
        Event.observe($('siteSearch').down('.watch'), 'keyup', function(e)
	{
            var myAjax = new Ajax.Updater("searchResults", "data/siteSearch.php", {method: 'get', parameters: $('siteSearch').serialize()});
	});
    }
}

function formAddressFeatures() {
    if ($('locationItemId') && $('addressMap'))
    {
        if ($('locationItemId').getValue()!="NONE") {
                $('locationItemId').up('fieldset').select('.fhAddress').each(function(s) {
                    s.hide();
                });
        } else {
                $('locationItemId').up('fieldset').select('.fhAddress').each(function(s) {
                    s.show();
                });
        }

        Event.observe($('locationItemId'), 'change', function(e)
	{
            if ($('locationItemId').getValue()!="NONE") {
                $('locationItemId').up('fieldset').select('.fhAddress').each(function(s) {
                    s.hide();
                });
            } else {
                $('locationItemId').up('fieldset').select('.fhAddress').each(function(s) {
                    s.show();
                });
            }
	});
    }
}

function showChromeFrameMessage () {
    if ($('googleChromeFrameDetection'))
    {
        $('googleChromeFrameDetection').insert({top: '<div class="error"><p>Using Internet Explorer but want to make this, and other compatible websites, run faster? Install Google Chrome Frame for free - this software makes Internet Explorer display compatible websites using the rendering code from Google Chrome, which is faster and supports more advanced web technologies. <a href="http://code.google.com/chrome/chromeframe/">Find out more about Google Chrome Frame!</a></p></div>'});
    }
}

function setupShowHide()
{
    var x = $$('.showhide');
    for(var i=0; i < x.length; i++)
    {   
        //if (i==0) {
        //    $(x[i]).previous("h2").insert({before:'<p class="lead">To view more information, click on the <img src="images/plus-grey.png" alt="plus symbol"> symbol'});
	//}
	$(x[i]).insert({top:'<img src="images/minus-grey.png" alt="Show more information">'});
	hideRegion($(x[i]));
    }
    
    if (location.hash!="")
    {
        selectedOption = location.hash.replace("#","");
        var y = $('content').select('a');
        for(var i=0; i < y.length; i++)
        {
            if ($(y[i]).readAttribute('name')==selectedOption)
            {
                showRegion($(y[i]).next(".showhide"));
                $(y[i]).scrollTo();
            }
        }
    }
}

function hideRegion(p)
{
	p.down('img').src = "images/plus-grey.png";
	p.down('img').alt = "Show more information";

	p.next(".showhideme").style.display = "none";
	
	Event.stopObserving(p.down("img"), 'click');
	Event.observe(p.down("img"), 'click', function(e)
	{
		showRegion(this.up('.showhide'));
	});
}

function showRegion(p)
{       
        p.next('.showhideme').style.display = "block";
	p.down('img').src = "images/minus-grey.png";
	p.down('img').alt = "Hide extra information";
	Event.stopObserving(p.down("img"), 'click');
	Event.observe(p.down("img"), 'click', function(e)
	{
		hideRegion(this.up('.showhide'));
	});
}

function setupNicEdit()
{
    if (getIEVersionNumber()!=7&&getIEVersionNumber() !=6)
    {
        var x = $$('.nicEdit textarea');
        for (var i=0; i<x.length;i++)
        {
                CKEDITOR.replace( $(x[i]).readAttribute('name'),
                {
                    toolbar :
                    [
                        ['Cut','Copy','PasteText','RemoveFormat'],
                        ['Bold','Italic','Strike'],
                        ['NumberedList','BulletedList','Outdent','Indent'],
                        ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                        ['Maximize'],
                        '/',
                        ['Image','Link','Unlink','-','Table','HorizontalRule','SpecialChar','Blockquote','TextColor'],
                        ['Format'],
                        ['-', 'Undo','Redo','Scayt']
                        
                    ]
                });
        }
    } else {
        if ($('description')) {
            nicEditors.allTextAreas({buttonList : ['removeformat', 'bold','italic','ol', 'ul', 'indent', 'outdent', 'hr', 'image', 'link', 'unlink', 'image']});
        }
    }
}

function setupTagAjax()
{
    if ($('addTagForm'))
    {
        Event.observe('addTagForm', 'submit', function(e)     {
                Event.stop(e);
                new Ajax.Updater(this.previous('.itemTags'), './data/addTag.php', {evalScripts: true,method: 'post', parameters: this.serialize(true)});
                this.down("input").value = "";
            }, false);
        setupTagFlagging();
    }
}

function setupMakeChangesAjax()
{
    if ($('submitChangesForm'))
    {
        Event.observe('submitChangesForm', 'submit', function(e)     {
                Event.stop(e);
                new Ajax.Updater($('submitChanges'), './data/submitChanges.php', {evalScripts: true,method: 'post', parameters: this.serialize(true)});
            }, false);
    }
}

function setupTagFlagging()
{
        var x = $$('#flagTagForm input.imageButton');
        for (var i=0; i<x.length;i++)
        {
            Event.observe($(x[i]), 'click', function(e)     {
                    Event.stop(e);
                    if(confirm("Are you sure you want to flag '" + this.getValue() + "' as inappropriate?"))
                        new Ajax.Updater(this.up('.itemTags'), './data/flagTag.php', {evalScripts: true, method: 'post', parameters: {itemId: $('itemId').getValue(), flagTag: $('flagTag').getValue(), tagField: this.getValue()}});
                }, false);
        }

        var y = $$('#flagTagForm input.approveTag');
        for (var n=0; n<y.length;n++)
        {
            Event.observe($(y[n]), 'click', function(e)     {
                    Event.stop(e);
                    if(confirm("Are you sure you want to approve '" + this.getValue() + "?"))
                        new Ajax.Updater(this.up('.itemTags'), './data/moderateTag.php', {evalScripts: true, method: 'post', parameters: {itemId: $('itemId').getValue(), status: "approve", tagField: this.getValue()}});
                }, false);
        }

        y = $$('#flagTagForm input.deleteTag');
        for (n=0; n<y.length;n++)
        {
            Event.observe($(y[n]), 'click', function(e)     {
                    Event.stop(e);
                    if(confirm("Are you sure you want to delete '" + this.getValue() + "?"))
                        new Ajax.Updater(this.up('.itemTags'), './data/moderateTag.php', {evalScripts: true, method: 'post', parameters: {itemId: $('itemId').getValue(), status: "delete", tagField: this.getValue()}});
                }, false);
        }
}

function setupTabs()
{
    if ($('itemDetails'))
    {
        $('itemDetails').insert({before: '<ul id="tabNav"></ul>'});
        $('itemDetails').setStyle({marginTop: "0px"} );
        var x = $$('.tab');
        for (var i=0; i<x.length;i++)
        {
            tabTitle = $(x[i]).down("h2").innerHTML;
            tabId = $(x[i]).identify();
            $('tabNav').insert({bottom: '<li><a href="#" rel="' + tabId + '">' + tabTitle + '</a></li>'});
            $(x[i]).hide();
        }

        $(x[0]).show();
        $('tabNav').down("li").addClassName("active");

        var y = $$('#tabNav li');
        for (var p=0; p<y.length;p++)
        {
            Event.observe($(y[p]).down("a"), 'click', function(e)     {
                Event.stop(e);
                this.up("ul").select("li.active").each(function(s){
			s.removeClassName("active");
		});
                $('itemDetails').select("div.tab").each(function(s){
			s.hide();
		});
                tabId = this.readAttribute('rel');
                this.up("li").addClassName("active");
                $(tabId).show();
                
            }, false);
        }

    }
}

function setupMap()
{
    if ($('largeMap'))
    {
        $('largeMap').insert({before: '<p><label for="locations">Locations:</label> <input checked class="mapWatch" type="checkbox" id="locations" value="SET">&nbsp;<label for="groups">Groups:</label> <input checked class="mapWatch" type="checkbox" id="groups" value="SET">&nbsp;<label for="businesses">Businesses:</label> <input class="mapWatch" type="checkbox" id="businesses" value="SET"></p>'});
        $('largeMap').setStyle({marginTop: '1em', width: '100%', height: '400px'});
        var map = new GMap2($('largeMap'));
        $('largeMap').insert({after: '<p>Click on the map icons to view more information about each location.</p><p>You can click and drag on the map to move around, and can zoom in using the zoom controls.</p>'});
        map.setCenter(new GLatLng(52.146280, -0.852900), 13);
        map.setUIToDefault();
        map.setMapType(G_HYBRID_MAP);
        addIcons(map);
        var x = $$('.mapWatch');
        for (var i=0; i<x.length;i++)
        {
            Event.observe($(x[i]), 'click', function()     {
               addIcons(map);
            }, false);
        }
    }
}

function addIcons(map)
{
    map.clearOverlays();
    if ($('businesses').getValue()=="SET") buildMarkersFromXML(map, "data/mapDataBusinesses.php", true);
    if ($('locations').getValue()=="SET") buildMarkersFromXML(map, "data/mapDataLocations.php", true);
    if ($('groups').getValue()=="SET") buildMarkersFromXML(map, "data/mapDataGroups.php", true);
}

function buildMarkersFromXML(map, fileName, infoWindow)
{
    var location = new GIcon();
    location.image = 'images/locationIcon/image.png';
    location.printImage = 'images/locationIcon/printImage.gif';
    location.mozPrintImage = 'images/locationIcon/mozPrintImage.gif';
    location.iconSize = new GSize(30,45);
    location.shadow = 'images/locationIcon/shadow.png';
    location.transparent = 'images/locationIcon/transparent.png';
    location.shadowSize = new GSize(53,45);
    location.printShadow = 'images/locationIcon/printShadow.gif';
    location.iconAnchor = new GPoint(15,45);
    location.infoWindowAnchor = new GPoint(15,0);
    location.imageMap = [19,0,21,1,23,2,24,3,25,4,26,5,27,6,27,7,28,8,28,9,29,10,29,11,29,12,29,13,29,14,29,15,29,16,29,17,29,18,29,19,28,20,28,21,27,22,26,23,26,24,25,25,24,26,22,27,21,28,20,29,19,30,19,31,19,32,18,33,18,34,18,35,17,36,17,37,17,38,16,39,16,40,16,41,15,42,15,43,15,44,14,44,14,43,14,42,13,41,13,40,13,39,12,38,12,37,12,36,11,35,11,34,11,33,10,32,10,31,10,30,9,29,8,28,7,27,5,26,4,25,3,24,2,23,2,22,1,21,1,20,1,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,1,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1,10,0];

    var business = new GIcon();
    business.image = 'images/businessIcon/image.png';
    business.printImage = 'images/businessIcon/printImage.gif';
    business.mozPrintImage = 'images/businessIcon/mozPrintImage.gif';
    business.iconSize = new GSize(30,43);
    business.shadow = 'images/businessIcon/shadow.png';
    business.transparent = 'images/businessIcon/transparent.png';
    business.shadowSize = new GSize(52,43);
    business.printShadow = 'images/businessIcon/printShadow.gif';
    business.iconAnchor = new GPoint(15,43);
    business.infoWindowAnchor = new GPoint(15,0);
    business.imageMap = [20,0,22,1,23,2,24,3,25,4,26,5,27,6,27,7,28,8,28,9,29,10,29,11,29,12,29,13,29,14,29,15,29,16,29,17,29,18,28,19,28,20,27,21,26,22,26,23,25,24,24,25,23,26,21,27,20,28,19,29,19,30,19,31,18,32,18,33,18,34,17,35,17,36,17,37,16,38,16,39,16,40,15,41,15,42,14,42,14,41,13,40,13,39,13,38,12,37,12,36,12,35,11,34,11,33,11,32,10,31,10,30,10,29,9,28,8,27,6,26,5,25,4,24,3,23,2,22,2,21,1,20,1,19,1,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,7,1,9,0];

    var group = new GIcon();
    group.image = 'images/groupIcon/image.png';
    group.printImage = 'images/groupIcon/printImage.gif';
    group.mozPrintImage = 'images/groupIcon/mozPrintImage.gif';
    group.iconSize = new GSize(30,43);
    group.shadow = 'images/groupIcon/shadow.png';
    group.transparent = 'images/groupIcon/transparent.png';
    group.shadowSize = new GSize(52,43);
    group.printShadow = 'images/groupIcon/printShadow.gif';
    group.iconAnchor = new GPoint(15,43);
    group.infoWindowAnchor = new GPoint(15,0);
    group.imageMap = [19,0,21,1,23,2,24,3,25,4,26,5,27,6,27,7,28,8,28,9,28,10,28,11,28,12,28,13,28,14,28,15,28,16,28,17,28,18,28,19,27,20,27,21,26,22,25,23,25,24,23,25,22,26,20,27,19,28,19,29,19,30,19,31,18,32,18,33,18,34,17,35,17,36,17,37,16,38,16,39,16,40,15,41,15,42,14,42,14,41,14,40,13,39,13,38,13,37,12,36,12,35,12,34,11,33,11,32,11,31,10,30,10,29,10,28,9,27,7,26,6,25,5,24,4,23,3,22,2,21,2,20,1,19,1,18,1,17,1,16,1,15,1,14,1,13,1,12,1,11,1,10,1,9,2,8,2,7,3,6,3,5,4,4,5,3,6,2,8,1,10,0];

    GDownloadUrl(fileName, function(data) {
      var xml = GXml.parse(data);
      var markers = xml.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
        var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                parseFloat(markers[i].getAttribute("lng")));
        var infowindow = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
        var icon = markers[i].getAttribute("icon");
        if (icon=="location") useIcon = location;
        else if (icon=="business") useIcon = business;
        else if (icon=="group") useIcon = group;
        if (infoWindow) {
            var marker = new GMarker(point, useIcon);
            map.addOverlay(marker);
            marker.bindInfoWindow(infowindow);
        }
      }
    });
}

function roundCorners()
{
    var x = $$('.sidebar');
    for (var i=0; i<x.length;i++)
    {
        $(x[i]).insert({top: '<div class="sbtl">&nbsp;</div><div class="sbtr">&nbsp;</div><div class="sbbl">&nbsp;</div><div class="sbbr">&nbsp;</div>'});
    }

    if ($('itemDetails')) $('itemDetails').insert({top: '<div class="sbtl">&nbsp;</div><div class="sbtr">&nbsp;</div><div class="sbbl">&nbsp;</div><div class="sbbr">&nbsp;</div>'});
}