var disabledLinks = new Array();
var bCancelLinkOpen = false;

function removeTags(subject){
    return subject.replace(/<\/?[^>]+(>|$)/g, "");
}
var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
function getAJAX() {
    var oXHR;
    // create the Ajax object (IE6/IE7/FF)
    try {
        oXHR = new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch (e)
    {
        try {
            oXHR = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (e2)
        {
            try {
                oXHR = new XMLHttpRequest();
            }
            catch (e3) {
                oXHR = false;
            }
        }
    }
    return oXHR;
}
function setAsHome(myLink)
{
	if(navigator.appName.indexOf('Microsoft')!=-1) {
		   // IE
		   myLink.style.behavior='url(#default#homepage)';
		   myLink.setHomePage(location.href);
	} else if(navigator.appName.indexOf('Netscape')!=-1) {
		   // Netscape / firefox browsers
		   var msg = "Just drag this link onto your ";
		   msg += "'home' button.";
		   alert(msg);
	} else if(navigator.appName.indexOf('Opera')!=-1) {
		   // Opera
		   var msg = "Please go to Tools - Preferences ";
		   msg += "- General and click 'Use current' ";
		   msg += "to set this as your homepage! ";
		   alert(msg);
	} else {
		   // Other browsers
		   var msg = "Sorry, your browser doesn't allow ";
		   msg += "scripts to set the default homepage. ";
		   msg += "Please use your browser's 'options' dialog ";
		   msg += "to do it! Thank you for your patience. ";
		   alert(msg);
	}
    return false;
}
function appendHTML(elt, html) {
    var e = document.createElement("div");
    e.innerHTML = html;
    var c = e.firstChild;
    while(c) {
        elt.appendChild( c.cloneNode(true) );
        c = c.nextSibling;
    }
}
function deleteChildNode(parentNode,childNodeID) {
    if(oNode = document.getElementById(childNodeID)) {
        parentNode.removeChild(document.getElementById(childNodeID));
        return true;
    } else {
        return false;
    }
}

function silly_swap(host) {
	
	var oImg 			= host.firstChild;
	var sImgStripped 	= host.href.substr(0,(host.href.length-4));
	var sPrevImg	 	= $('a_med').href.substr(0,($('a_med').href.length-4));
	
	$('img_med').src	= sImgStripped + '_med.jpg';
	$('a_med').href		= sImgStripped + '.jpg';
	
	oImg.src 			= sPrevImg + '_tn.jpg';
	host.href			= sPrevImg + '.jpg';
	
	return false;
	
}
function popupWindow(url,width,height) {
 	
 	var left   	= (screen.width  - width)/2;
	var top    	= (screen.height - height)/2;
    var day 	= new Date();
    var id		= day.getTime();
    
    eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=0,width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + "');");

    return false;
}
function showPopupDiv(url,popupId,hostLinkId) {

    // If user agent is IE6, we'll use a normal popup window instead
    // of trying to manage dozens of nasty hacks

    var agt=navigator.userAgent.toLowerCase();

    if(agt.indexOf("msie 6.")!=-1){
    	
    	popupWindow(url,500,500);
       
    } else {

        // This is NOT IE6

        // Create the HTML required for popup container
        var popupHTML = '<div id="' + popupId + '" class="popupDiv"><div id="popupDivTitlebar"><h1>yourlocalweb.co.uk</h1><div id="closeButton"><a id="closePopupLink" href="' + window.location + '" onclick="return closePopupDiv(\'' + popupId + '\',\'' + hostLinkId + '\');" title="Close this window">Close</a></div></div><iframe id="popupIFrame" frameborder="0" title="Content Submission Service" src="' + url + '" name="content_submission" scrolling="auto">Sorry, your browser does not support the IFrame standard. Please upgrade your browser to a modern version - we recommend Mozilla Firefox!</iframe></div>';
        //popupHTML += '<script type="text/javascript">new Draggable(\'' + popupId + '\',{handle:\'popupDivTitlebar\',starteffect:\'None\'});<\/script>';

        // Disable the anchor link that opened the popup window
        hostLink = document.getElementById(hostLinkId);
        disabledLinks[hostLinkId] = hostLink.onclick;
        hostLink.onclick = new Function('return false;');

        // Append the HTML to the document, effectively showing the popup
        appendHTML(document.getElementById('content'),popupHTML);

    }

    // Prevent the browser from navigating to the href specified
    // in anchor
    return false;

}
function closePopupDiv(popupId,hostLinkId) {

    // delete the div container
    deleteChildNode(document.getElementById('content'),popupId);

    // enable host anchor link that opened the
    // popup window
    document.getElementById(hostLinkId).onclick = disabledLinks[hostLinkId];

    return false;
}
function openLink(url) {
    if(!bCancelLinkOpen) {
        window.open(url);
        bCancelLinkOpen = false;
    }
    return false;
}
function cancelClick() {
    bCancelLinkOpen = true;
}
function cancelEvent(e) {

    // cancels the specified event
    // (stops other elements firing it)
    var e = e || window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    alert('cancelEvent');
}
var jump_menu_append_uri = '';
function MM_jumpMenu(targ,selObj,restore) { //v3.0
    
    eval(targ+".location='"+gsBaseURL+selObj.options[selObj.selectedIndex].value+jump_menu_append_uri+"'");
    if (restore) selObj.selectedIndex=0;
}
function openDirectory(service,location) {
    // (requires prototype.js)
    window.open('http://www.yell.com/ucs/UcsSearchAction.do?keywords=' + Url.encode(service.unescapeHTML()) + '&location=' + Url.encode(location.unescapeHTML()));
    return false;
}
function openPropertyToBuy(location) {
    // required prototype.js)
    window.open('http://www.findaproperty.com/searchresults.aspx?bedrooms=0&res=0&salerent=0&loc=' + Url.encode(location.unescapeHTML()));
    return false;
}
function showMore(containerID) {

    var oContainer = document.getElementById(containerID);
    var oParent = document.getElementById(oContainer.parentNode.id);
    var htmlLink = '<div id="collapseControls_'+containerID+'"><a href="#" onclick="return showLess(\''+containerID+'\');">Show less...</a></div>';

    deleteChildNode(oParent,'collapseControls_'+containerID);
    oContainer.className = 'more';
    appendHTML(oParent,htmlLink);

    return false;
}
function showLess(containerID) {

    var oContainer = document.getElementById(containerID);
    var oParent = document.getElementById(oContainer.parentNode.id);
    var htmlLink = '<div id="collapseControls_'+containerID+'"><a href="#" onclick="return showMore(\''+containerID+'\');">Show more...</a></div>';

    deleteChildNode(oParent,'collapseControls_'+containerID);
    oContainer.className = 'less';
    appendHTML(oParent,htmlLink);

    return false;
}
function prepCollapser(containerID) {
    var oContainer;
    if(oContainer = document.getElementById(containerID)) {
        showLess(containerID);
    }
}
function clickOnEnter(e,link) {
    var key=e.keyCode || e.which;
    if(key==13) {
        link.click();
    }
}
function getResource(uri, alt_uri, wait_callback, data_callback, error_callback, timeout) {
    var doneWait = false;
    var tryAgain = function () {
      getResource(uri, wait_callback, data_callback, error_callback, timeout);
    }
    var r = getAJAX();
    var timer = setTimeout(
        function() {
            r.abort();
            r.onreadystatechange = null;
            setTimeout(tryAgain, timeout);
        },
        timeout);
    r.open("GET", uri, true);
    r.onreadystatechange = function() {
        if (r.readyState != 4) {
            // Ignore non-loaded readyStates
            // ...will timeout if do not get to "Loaded"
            if(!doneWait) {
                wait_callback();
                doneWait = true;
            }
            return;
        }
        clearTimeout(timer);  // readyState==4, no more timer
        if (r.status==200) {  // "OK status"
              data_callback(r.responseText, r.responseXML);
        }
        else if (r.status==304) {
            // "Not Modified": No change to display
        }
        else if (r.status >= 400 && r.status < 500) {
            // Client error, probably bad URI
            error_callback(r,uri,alt_uri)
        }
        else if (r.status >= 500 && r.status < 600) {
            // Server error, try again after delay
            setTimeout(tryAgain, timeout);
        }
        else {
            error_callback(r,uri,alt_uri);
        }
    }
    r.send(null);
    return r;
}
function gLP(oLink,bFilter) {
    if(getResource(oLink.href.toString() + 'ajax.html',oLink.href.toString(),wLP,uLP,eLP, 5000)) {
        // update selected item
        if(!bFilter) {
            var old = document.getElementById('lmc');
            old.className = ''
            old.id = '';
            oLink.className = 'selected'
            oLink.id = 'lmc';
        }
        return false;
    }
}
function gLPF(oLink) {
    return gLP(oLink,true);
}
function wLP() {
    // show wait timer for local places (A-Z)
    document.getElementById('localList').innerHTML = '<p class="wait">Please wait...</p>';
}
function uLP(data) {
    // update local place index (A-Z)
    document.getElementById('localList').innerHTML = data;
}
function eLP(r,uri,alt_uri) {
    // Ajax failed, so navigate to the alternate content
    // as a last ditch resort
   goTo(alt_uri);
}

var map;
var markerConf = [];
var gmDefaults = { longDec: 0, latDec: 0, zoomLevel: 0 };
var map_types;
var cur_level;

function showMapLoading() {
	// show loading text
    var oMap = $("googleMap");
    removeChildNodes(oMap);
    var newdiv = document.createElement('div');
	newdiv.innerHTML = '<div id="map_load"><p>Loading map...</p></div>';
	oMap.appendChild(newdiv);
}

function loadGMap(locLevel,longDec,latDec,zoomLevel,defaultType) {

	if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById("googleMap"));
        var point = new GLatLng(latDec, longDec);

        // set normal as default map
        if(defaultType){
        	//map.addMapType(defaultType);
        	//var mapControl = new GHierarchicalMapTypeControl();
        	map.setMapType(defaultType);
        	//mapControl.clearRelationships();
        }else{ 
	        // add terrain/physical map type selector control
	        map.addMapType(G_PHYSICAL_MAP);
	        var mapControl = new GHierarchicalMapTypeControl();
	        // set up map type menu relationships
	        mapControl.clearRelationships();
	        mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
        	map.setMapType(G_NORMAL_MAP);
        	map.addControl(mapControl); 
        }
        
        // centre map
        map.setCenter(point, zoomLevel);
        
        // add control after you've specified the relationships
        map.addControl(new GSmallMapControl());        

        // add marker if this is a county
        cur_level = locLevel;
        if((locLevel == 'county') || (locLevel == 'zone')) {
            // standard icon (large)
            markerOptions = false;
        } else {
            var tinyIcon = new GIcon();
            tinyIcon.image = gsBaseURL + 'images/tiny-map-marker.png';
            tinyIcon.iconSize = new GSize(10, 10);
            tinyIcon.iconAnchor = new GPoint(5, 5);
            tinyIcon.infoWindowAnchor = new GPoint(5, 1);
            markerOptions = { icon:tinyIcon, clickable:false };
        }
        map.addOverlay(new GMarker(point,markerOptions));

        // create marker managers for all groups
        for (var i=0; i<markerConf.length; i++) {
            markerConf[i]["mm"] = new MarkerManager(map);
        }

        // save default values
        gmDefaults.longDec = longDec;
        gmDefaults.latDec = latDec;
        gmDefaults.zoomLevel = zoomLevel;

        // refire checkboxes that have stayed checked
        if(map_type == 'produce'){
        	toggleProduceMarkers();
        }else{
        	if(defaultType){
        	
			}else{
			   fireCheckboxes(['plot_cities','plot_towns','plot_villages']); 
			}        	
        }

        // remove loading indicator
        /*var oMapLoad = $('map_load');
        if(oMapLoad) {
        	oMapLoad.parentNode.removeChild(oMapLoad);
		}*/

    } else {
    	// show browser not compatible message
    	var oMap = $("googleMap");
    	removeChildNodes(oMap);
    	var newdiv = document.createElement('div');
		newdiv.innerHTML = '<div class="jswarn"><p>Sorry, your browser is not compatible with the Google Maps API. We recommend the latest version of <a href="http://www.getfirefox.com/">Mozilla Firefox</a> for web browsing.</p></div>';
		oMap.appendChild(newdiv);
    }
}

function removeChildNodes(ctrl) {
  while (ctrl.childNodes[0]) {
    ctrl.removeChild(ctrl.childNodes[0]);
  }
  return true;
}
function addMarkerGroup(type,aoMarkers,urls) {
    markerConf.push({ "type": type, "visible": 0, "mm": "1", "markers": aoMarkers, "urls": urls });
}

function toggleMarkers(type,toggleCheckBox) {
    if(toggleCheckBox.checked == true) {
        // add markers
        addMarkers(type);
    } else {
        // remove markers
        removeMarkers(type);
    }
    // auto zoom to show all markers in view
    autoZoom();
}

function autoZoom() {

  var bounds = new GLatLngBounds;
  for (var i=0; i<markerConf.length; i++) {
      if(markerConf[i]["visible"] == 1) {
          //alert(markerConf[i]["markers"].length);
          for (var i2=0; i2<markerConf[i]["markers"].length; i2++) {
            bounds.extend(markerConf[i]["markers"][i2].getLatLng());
          }
      }
  }

  var curLatLng = new GLatLng(gmDefaults.latDec,gmDefaults.longDec);

  // check if any bounds were added
  if(bounds.isEmpty()) {
    // return to default map center and zoom level
    map.setCenter(curLatLng, gmDefaults.zoomLevel);
  } else {
    // also add in the current location
    bounds.extend(curLatLng);

    // set zoom level
    if((map_type == 'produce') && (cur_level == 'county' || cur_level == 'zone')){
      	map.setZoom((map.getBoundsZoomLevel(bounds)));
    }else{
      	map.setZoom((map.getBoundsZoomLevel(bounds) - 1));
    }


    // Set map center to the center of the GLatLngBounds
    map.setCenter(bounds.getCenter());
  }

}

function addMarkers(type,id,auto_zoom,change_list) {
  // add all the markers to the marker manager
  for (var i=0; i<markerConf[type]["markers"].length; i++) {
        marker = markerConf[type]["markers"][i];

        if(markerConf[type]["urls"]){
         	marker['url'] = markerConf[type]["urls"][i];
		    if( marker['url']){
		        GEvent.addListener(marker, 'click', function() {
		           document.location = gsBaseURL + this['url'];
		      });
		    }

        }

	    markerConf[type]["mm"].addMarker(marker, 0);
  }

  markerConf[type]["mm"].refresh();
  markerConf[type]["visible"] = 1;

  if(map_type == 'produce' && change_list){
  	$('produceListSelector').value = type;
  }

  if(auto_zoom){
  	autoZoom();
  }

  if((id || id == 0)){
  		setTimeout(function(){ GEvent.trigger(markerConf[type]["markers"][id], "click"); }, 1);
  }
}

function showInfoWindow(obj,html){
	obj.openInfoWindowHtml(html);
}

function removeMarkers(type) {
  for (var i=0; i<markerConf[type]["markers"].length; i++) {
    markerConf[type]["mm"].removeMarker(markerConf[type]["markers"][i]);
  }
  markerConf[type]["mm"].refresh();
  markerConf[type]["visible"] = 0;
}

function getMiniIcon(locType) {
    // Create our "tiny" marker icon
    var tinyIcon = new GIcon();
    var sMarkerColour = 'red';
    switch(locType) {
        case 'city':  	sMarkerColour = 'red';  	break;
        case 'town':  	sMarkerColour = 'blue'; 	break;
        case 'village': sMarkerColour = 'green';	break;
    }
    tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_" + sMarkerColour + ".png";
    tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    tinyIcon.iconSize = new GSize(12, 20);
    tinyIcon.shadowSize = new GSize(22, 20);
    tinyIcon.iconAnchor = new GPoint(6, 20);
    tinyIcon.infoWindowAnchor = new GPoint(5, 1);
    return tinyIcon;
}

function getProduceMiniIcon(type){

    switch(type){
		case 'Bakery': 						sImageSrc = 'bakery.png';		break;
		case 'Beverage':   					sImageSrc = 'beverage.png';		break;
		case 'Box Scheme':  				sImageSrc = 'box_scheme.png'; 	break;
		case 'Country Markets':  			sImageSrc = 'country_market.png';break;
		case 'Crafts':              		sImageSrc = 'crafts.png';        break;
		case 'Dairy':               		sImageSrc = 'dairy.png';         break;
		case 'Deli':               			sImageSrc = 'deli.png';          break;
		case 'Farm Shop':           		sImageSrc = 'farm_shop.png';     break;
		case 'Fish':                		sImageSrc = 'fish.png';          break;
		case 'Meat/Game':           		sImageSrc = 'meat_game.png';     break;
		case 'Miscellaneous':       		sImageSrc = 'misc.png';          break;
		case 'Nursery':             		sImageSrc = 'nursery.png';       break;
		case 'Pick Your Own':       		sImageSrc = 'pick_your_own.png'; break;
		case 'Preserves':           		sImageSrc = 'preserves.png';     break;
		case 'Restaurants':         		sImageSrc = 'resturant.png';     break;
		case 'Logpile Member (wood fuel)': 	sImageSrc = 'log.png';			 break;
		default:                            sImageSrc = 'blank.png';         break;
    }

	var oIcon = new GIcon(G_DEFAULT_ICON);
    oIcon.image = gsBaseURL + 'images/produce_icons/' + sImageSrc;
    oIcon.transparent = gsBaseURL + 'images/produce_icons/clickmap.png';
    oIcon.shadow  =  '';
    oIcon.shadowSize  =  new GSize(0,0);
    oIcon.iconSize = new GSize(32,32);
    oIcon.imageMap = [0,2,0,22,3,24,24,24,26,23,26,3,23,0,2,0,0,2];
    oIcon.infoWindowAnchor = new GPoint(13,0);
	return oIcon;
}

function toggleProduceMarkers(type,id) {

	removeProduceMarkers();

    if((type == '' || type == undefined) && type !== 0){
    	addMarkers(0,id,true,true);
    }else if(type == 'ALL'){
        var markerCount = markerConf.length;
		for (var i=0; i<markerCount; i++) {
		 	addMarkers(i,null,false);
		}
		// auto zoom to show all markers in view
    	autoZoom();
    }else{
        addMarkers(type,id,true,true);
    }
    
    //To stop the dropdown being grey on IE
    window.focus();
    
    return true;
}

function removeProduceMarkers() {
	var markerCount = markerConf.length;
	for (var i=0; i<markerCount; i++) {
		var groupCount = markerConf[i]["markers"].length;
		for (var j=0; j<groupCount; j++) {
			markerConf[i]["mm"].removeMarker(markerConf[i]["markers"][j]);
		}
		markerConf[i]["mm"].refresh();
		markerConf[i]["visible"] = 0;
	}
}

function goTo(uri) {
     window.location.href = uri;
     return false;
}

// fire the click event for each checkbox with corresponding ID in idlist array
// if it is checked
function fireCheckboxes(idlist) {
    var oCB = null;
    for (var i=0; i<idlist.length; i++) {
        oCB = document.getElementById(idlist[i]);
        if(oCB.checked) {
            oCB.click(); // untick
            oCB.click(); // tick again to fire correct event
        }
    }
}

// Search hints helper functions
function doReq(query) {
    // if query doesn't not include searchURI, add it
    if (query.indexOf(ac_searchURI) < 0)  query = ac_searchURI + query;
    ac_widget.doQuery(query);
}
var ac_getURI = function (value) {
    var gE = widget.DOM.gE;
    return ac_searchURI + '?q=' + encodeURI(value) + '&l=' + gE('fSearch_l').value + '&i=' + gE('fSearch_i').value + '&m=' + ac_alignMode;
};

// Community Link builder functions
var ac_lbGetURI = function (value) {
    var gE = widget.DOM.gE;
    return ac_searchURI + '?q=' + encodeURI(value) + '&l=' + gE('fSearch_l').value + '&i=' + gE('fSearch_i').value + '&m=' + ac_alignMode + '&hc=1';
};
var ac_lbUpdate = function(li) {
    var gE = widget.DOM.gE;
    var sLocURI = (li.getElementsByTagName('a')[0].href);
    var sLocName = removeTags(li.getElementsByTagName('a')[0].innerHTML);

    oInpBox = gE('fBuilder_loc');
    oInpBox.value = sLocName;

    oSelLocAnc = gE('lb_selAnchor');
    oSelLocAnc.href = sLocURI;
    oSelLocAnc.innerHTML = sLocName;

    oPrevLocAnc = gE('lb_preAnchor');
    oPrevLocAnc.href = sLocURI;
    oPrevLocAnc.title = 'Visit ' + sLocName + ' on yourlocalweb.co.uk';
	
	oPrevLocAnc2 = gE('lb_preAnchor2');
    oPrevLocAnc2.href = sLocURI;
    oPrevLocAnc2.innerHTML = sLocName;
    oPrevLocAnc2.title = oPrevLocAnc.title;
    
    oPrevLocAnc3 = gE('lb_preAnchor3');
    oPrevLocAnc3.href = sLocURI;
    oPrevLocAnc3.title = oPrevLocAnc.title;
    oPrevLocAnc3.innerHTML = 'Visit ' + sLocName + '<br />on yourlocalweb.co.uk';
    
    oPrevLocAnc3 = gE('lb_preAnchor4');
    oPrevLocAnc3.href = sLocURI;
    oPrevLocAnc3.title = oPrevLocAnc.title;
    
    gE('lb_codeURI').innerHTML = sLocURI;
    gE('lb_codeAncTip').innerHTML = oPrevLocAnc.title;
    
    gE('lb_codeURI2').innerHTML = sLocURI;
    gE('lb_codeAncTip2').innerHTML = oPrevLocAnc.title;
    
    gE('lb_codeURI3').innerHTML = sLocURI;
    gE('lb_codeAncTip3').innerHTML = oPrevLocAnc.title;
    
    gE('lb_codeURI4').innerHTML = sLocURI;
    gE('lb_codeAncTip4').innerHTML = oPrevLocAnc.title;
    
    gE('lb_codeAncTip5').innerHTML = oPrevLocAnc.title;
    
    gE('lb_codeAncText').innerHTML = sLocName;

    return false;
};

function lb_toggleCodeBlock (block_id) {
	
	switch(block_id) {
		case 'code_classic':
			$('code_classic').style.display = 'block';
			$('code_text').style.display = 'none';
			$('code_logo').style.display = 'none';
			break;
		case 'code_logo':
			$('code_classic').style.display = 'none';
			$('code_text').style.display = 'none';
			$('code_logo').style.display = 'block';
			break;
		case 'code_text':
			$('code_classic').style.display = 'none';
			$('code_text').style.display = 'block';
			$('code_logo').style.display = 'none';
			break;
	}
	
	return false;
	
};

function getPlaceSelector(path, div){
	obj = document.getElementById(div);

	page_request = getAJAX();

	page_request.open('GET', path, true);

	page_request.onreadystatechange=function(){
		if(page_request.readyState==4){
		   if(path){
				obj.innerHTML = page_request.responseText;
			}
		}
	}
	page_request.send(null);
}

// turns commas into xhtml <br /> elements (line breaks) for the specified css class
function replace_with_brs(xhtml,target_css_class,replace,debug){
	var oRE_find = new RegExp("class=\"?" + target_css_class + "\"?[^<]*>(.*)<","g");
	var oRE_replace = new RegExp(replace,'g');
	return xhtml.replace(oRE_find, function(match){ return match.replace(oRE_replace,'<br />'); });
}

function markerAddInfo(array,images,index){
	for (var i=0; i<array.length; i++){
	    // create the html for the info window - (address field pre-processed to turn commas into line breaks)
        html = '<div id="producer_infowindow">' + replace_with_brs($('producers'+ index +'_' + i).innerHTML,'producer_address',',') + '</div>';
	    array[i].bindInfoWindowHtml(html);
    }
    addMarkerGroup("producers" + index, array);
}
function ch(id){
	cn = $(id).className;

	if(cn != "selected"){
		$(id).className = "selected";
	}
}

function chb(id){
	cn = $(id).className;

	if(cn == "selected"){
		$(id).className = "";
	}
}

function rate(id,rating,type,link){

	var thankyou = $('rating-' + id);

	ajax_wait = function(){ thankyou.innerHTML = '<span class="rl_voting"> - <img src="' + gsBaseURL + 'images/wait-sm.gif" /> Voting... </span>' }

	ajax_data = function(text,XML){
		//document.write(text);
		var result_ = XML.getElementsByTagName("result")[0].childNodes[0].nodeValue;
		if(result_ == '400: Bad Request (Failed)'){
			thankyou.innerHTML = ' - Sorry your vote was not successful. Please try again. ';
		}else if(result_ == '400: Bad Request (Duplicate)'){
			thankyou.innerHTML = ' - You have voted for this link already! ';
		}else if(result_ == '400: Bad Request (Vote Limit)'){
			thankyou.innerHTML = ' - This link has reached todays vote limit! ';
		}else{
			thankyou.innerHTML = '<span class="rl_success"> - Thank you for your vote! </span>';
		}

	}

	ajax_error = function(){ }

	var lRndNum = Math.random();
	var sReqUrl = gsBaseURL  + 'ylwproxy/ajax/connector.php?req=' + lRndNum + '&name=rating-vote&type=' + type + '&rating=' + rating + '&id=' + id;
    getResource(sReqUrl, gsInteractiveURL, ajax_wait, ajax_data, ajax_error, 5000);
	return false;
}
function get_position(e) {

	var e = $(e);

	var obj = e;

	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}else if (obj.x)
		curleft += obj.x;

	var obj = e;

	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop};
};

// displays balloon under object
function show_balloon(balloon_id,object_id, offsetX, offsetY, replace, align) {

	// figure out offsets
	if((offsetX == false) ||
	   (offsetX == '') ||
	   (offsetX == undefined)){
		offsetX = 8;
	}
	if((offsetY == false) ||
	   (offsetY == '') ||
	   (offsetY == undefined)){
		offsetY = 0;
	}

	// get nodes
	var balloon = $(balloon_id);
	var object = $(object_id);

    // get co-ords of objects
	var pos			= get_position(object_id);
	var balloon_w	= balloon.offsetWidth;
	var object_w	= object.offsetWidth;

	// determine alignment mode
	switch (align){
		case "l": // left align
			var l = pos.x + offsetX;
			break;

		case "r": // right align
			//l = pos.x - dlw + fldw + 10;
			var l = Math.round((pos.x - (object_w + balloon_w)) + offsetX);

		default: // centered
			var l = Math.round(pos.x + (object_w/2) - (balloon_w/2) + (offsetX));
			break;

	}

	// set position
	balloon.style['left'] = l + "px";
    balloon.style['top'] = (pos.y + object.offsetHeight + (offsetY)) + "px";

	// replace content?
	if(replace){
		balloon.innerHTML = "<p>" + object.innerHTML + "</p>";
		object.title = '';
	}

}
function hide_balloon(balloon_id) {
	var balloon = $(balloon_id);
	balloon.style['top'] = "-1000px";
}

function toggle_selects(hide) {
	
	// only do this for IE6
	var agt=navigator.userAgent.toLowerCase();
			
    if(agt.indexOf("msie 6.")!=-1){
    	//var f = document.getElementById(id);
		var s = document.getElementsByTagName('select');

		for (var i = 0; i < s.length; ++i) {
			s[i].style.display = (hide ? 'none' : '');
		}
	}
}
