str_town="";


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//e window//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Version 0.0  Initial version 
// Version 0.1  10/10/2006 Added E_STYLE_7 
// Version 0.2  17/05/2007 Added .isHidden() and .supportsHide()


      function EStyle(stemImage, stemSize, boxClass, boxOffset) {
        this.stemImage = stemImage;
        this.stemSize = stemSize;
        this.boxClass = boxClass;
        this.boxOffset = boxOffset;
        //this.border = border;
        
        // Known fudge factors are:
        // Firefox (1.0.6 and 1.5)    5, -1
        // IE 6.0                     0, -1
        // Opera 8.54                 3, -1
        // Opera 9 prev               4, -1
        // Netscape (7.2, 8.0)        5, -1
        // Safari                     5, -1        
        
        var agent = navigator.userAgent.toLowerCase();
        
        var fudge = 5;  // assume Netscape if no match found
       
        if (agent.indexOf("opera") > -1) {
          fudge = 3;
        }   
        if (agent.indexOf("firefox") > -1) {
          fudge = -1;
        }   
        if (agent.indexOf("safari") > -1) {
          fudge = 5;
        }   
        if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){
          fudge = -1;
        }
        this.fudge = fudge;
      }
      
      var E_STYLE_7 = new EStyle("/img/map/stem7.png", new GSize(24,24),  "estyle2", new GPoint(-5,23));


      function EWindow(vmap,estyle) {
        // parameters
        this.vmap=vmap;
        this.estyle=estyle;
        // internal variables
        this.visible = false;
        // browser - specific variables
        this.ie = false;
        var agent = navigator.userAgent.toLowerCase();
        if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}
      } 
      
      EWindow.prototype = new GOverlay();

      EWindow.prototype.initialize = function(vmap) {
        var div1 = document.createElement("div");
        div1.style.position = "absolute";
        vmap.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div1);
        var div2 = document.createElement("div");
        div2.style.position = "absolute";
        div2.style.width = this.estyle.stemSize.width+"px";
        vmap.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div2);
        this.div1 = div1;
        this.div2 = div2;
      }

      EWindow.prototype.openOnMap = function(point, html, offset) {
        this.offset = offset||new GPoint(0,0);
        this.point = point;
        this.div1.innerHTML = '<div class="' + this.estyle.boxClass + '"><nobr>' + html + '</nobr></div>';
        //if (this.ie && this.estyle.stemImage.toLowerCase().indexOf(".png")>-1) {
       //   var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.estyle.stemImage+"', sizingMethod='scale');";
        //  this.div2.innerHTML = '<div style="height:' +this.estyle.stemSize.height+ 'px; width:'+this.estyle.stemSize.width+'px; ' +loader+ '" ></div>';
       // } //else {
          //this.div2.innerHTML = '<img src="' + this.estyle.stemImage + '" width="' + this.estyle.stemSize.width +'" height="' + this.estyle.stemSize.height +'">';
        //}
        var z = GOverlay.getZIndex(this.point.lat());
        this.div1.style.zIndex = z;
        this.div2.style.zIndex = z+1;
        this.visible = true;
        this.show();
        this.redraw(true);
      }
      
      EWindow.prototype.openOnMarker = function(marker,html) {
        var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
        var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
        this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
      }
      

      EWindow.prototype.redraw = function(force) {
        if (!this.visible) {return;}
        var p = this.vmap.fromLatLngToDivPixel(this.point);
        this.div2.style.left   = (p.x + this.offset.x) + "px";
        this.div2.style.bottom = (-p.y + this.offset.y -this.estyle.fudge) + "px";
        this.div1.style.left   = (p.x + this.offset.x + this.estyle.boxOffset.x) + "px";
        this.div1.style.bottom = (-p.y + this.offset.y + this.estyle.boxOffset.y) + "px";
      }

      EWindow.prototype.remove = function() {
        this.div1.parentNode.removeChild(this.div1);
        this.div2.parentNode.removeChild(this.div2);
        this.visible = false;
      }

      EWindow.prototype.copy = function() {
        return new EWindow(this.vmap, this.estyle);
      }

      EWindow.prototype.show = function() {
        this.div1.style.display="";
        this.div2.style.display="";
        this.visible = true;
      }
      
      EWindow.prototype.hide = function() {
        this.div1.style.display="none";
        this.div2.style.display="none";
        this.visible = false;
      }
      
      EWindow.prototype.isHidden = function() {
        return !this.visible;
      }
      
      EWindow.prototype.supportsHide = function() {
        return true;
      }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//map//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //<![CDATA[  
var APmap;
townsearchlat=54.0009;
townsearchlon=-1.5377;
var selectedcategory=0;
var selectedactivity=0;
var townsearched=0;
var activitytitle= 'Paintball';
var overridezoom = 0;
var dist_disp = true;
	
function ewtable(a,b,c,d) {
	//title, distance, links, activity-titles
	var C = APmap.getCenter();
	var X = C.lng();
	var Y = C.lat();

	if((Y==54.0009 && X==-1.5377) || !dist_disp) {
		var distance = '';
	} else {
		var distance = '<em>'+b+' Miles - Approx</em>';
	}
	
	var links = "";
	
	//old image loc = <img src=/new/images/icon.png border='0' >
	
	for(var i=0; i<c.length; i++) {
		links = links + "<a href=\"javascript:tb_show('','"+c[i]+"','')\">"+d[i]+"</a><br />";
	}
	
	return '<table border="0" cellpadding="0" cellspacing="0" align="left" width="150px"><tr align="left"><td class="EWTitle">' + a + '<br>' + distance + '</td></tr>' + '<tr valign="center"><td class="EWbody" valign="center">' + links + '</td></tr></table>';
}

function createMarker(point, html, i, links) {
	var marker = new GMarker(point, icon);

	if(i == 0 && dist_disp == true) {
		if(townsearched>0) {
			ew.openOnMarker(marker,html);
			ewclick.hide();
		}
	}
		
	GEvent.addListener(marker, "mouseover", function() {
		ew.openOnMarker(marker,html);
		ewclick.hide();
	});
	
	GEvent.addListener(marker, "click", function() {
		var zoom = APmap.getZoom();
		if(zoom >= 12) {
			if(links.length == 1) {
				tb_show("",links[0],"");
			} else {
				ew.openOnMarker(marker,html);
				ewclick.hide();
			}
		}
		APmap.setCenter(point, APmap.getZoom()+2);
	});
	return marker;
}

function townsearch(a) {
	//alert('0 lat='+townsearchlat);
	//remove divs
	$('#othertowns').fadeOut('fast');
	$('#nomatches').hide();
	//$('#select-activity').fadeOut('fast');

	var request = GXmlHttp.create();

	var a = a || document.searcher.str_town.value;

	//townsearchvalue = a;

	if(a == '')
		return false;
	//alert('0 lat='+townsearchlat);
	request.open("GET", "/mysql/townsearch.asp?townsearch="+a, true);
	request.onreadystatechange = function() {
	//alert('0a lat='+townsearchlat);
		if (request.readyState == 4) {
			//alert('0b lat='+townsearchlat);
			var xmlDoc = GXml.parse(request.responseText);
			var towninfo= xmlDoc.documentElement.getElementsByTagName("towndata");			
			if (towninfo.length<1) {
				$(function() {
					$('#othertowns').fadeOut('fast');
					$('#nomatches').fadeIn('slow');
					$('#nomatches dt a').click(function(){
						$('#nomatches').fadeOut('slow');
						return false;
					});
				});
			} else {

				var fci = parseInt(towninfo[0].getAttribute('feature_class_id'));

				if(fci == 17 || fci == 18) {
					dist_disp = false;
				} else {
					dist_disp = true;
				}

				//centre map on selected town
				townsearchlat=towninfo[0].getAttribute("lat");
				townsearchlon=towninfo[0].getAttribute("lon");

				var mapz = xmlDoc.documentElement.getElementsByTagName("maps");
				var zoom = parseInt(mapz[0].getAttribute("z"));

				if(zoom >= 1 && zoom <= 12) {
					overridezoom = zoom;
				} else {
					zoom = 12;
					overridezoom = 0;
				}
				//alert('1 lat='+townsearchlat);
				APmap.setCenter(new GLatLng(townsearchlat, townsearchlon), zoom);
				changeactivity("Go Ballistic");
				//changetown(document.searcher.str_town.value)
				str_town = towninfo[0].getAttribute('name');
				changetown(towninfo[0].getAttribute('name'));
				townsearched=1;
				//map.clearOverlays();
			}
			if (towninfo.length>1) {
				//use mysql othertown with link_id to jump to alternatives then use above
				var i = 1 
				var town_list = '<dl><dt><b>Alternative Destinations</b><a href="#" class="close">x</a></dt>';
				for(i=1;i<towninfo.length;i++) { 
					//town_list = town_list + "<dd><a class='alt_town' href='mysql/othertown.asp?id=" + towninfo[i].getAttribute("id") + "'>" + towninfo[i].getAttribute("name") + ", "+towninfo[i].getAttribute("admintwo")+"</a></dd>" 
					town_list = town_list + "<dd><a class='alt_town' town_loc='" + towninfo[i].getAttribute("id") + "' href='#'>" + towninfo[i].getAttribute("name") + ", "+towninfo[i].getAttribute("admintwo")+"</a></dd>" 
				} 
				town_list = town_list + "</dl>" 
				$(function() {
					$('#nomatches').hide('fast');
					$('#othertowns').empty().append(town_list).fadeIn('slow');
					$('#othertowns dt a').click(function(){
						$('#othertowns').fadeOut('slow');
						return false;
					});
				});
			}
			var old_id = getURLVar('id');
			if(old_id > 0) {
				var bob = "";
			} else {
				var venue_markers = activityfilter(0,2,"Karting Nation");
			}
			
		}

		//townsearchlat=towninfo[0].getAttribute("lat");
		//townsearchlon=towninfo[0].getAttribute("lon");
	}

	request.send(null);

	return false;

}
	
function myzoom(a) {
	APmap.setZoom(APmap.getZoom() + a);
}
	
function changetown(a) {
	var a = decodeURI(a);
	$("span#act_town").empty().append(a);
	if(dist_disp) {
		$('div#locationlist p.title strong').empty().append("Nearest Venues to "+a);
	} else {
		$('div#locationlist p.title strong').empty().append("Venues Nationwide");
	}
}

function changeactivity(a) {
	var a = decodeURI(a);
	$("span#act_type").empty();
	$("span#act_type").append(a);
}
	
function movev(a) {
	var C = APmap.getCenter();
	var X = C.lng();
	var Y = C.lat();
	APmap.setCenter(new GLatLng(Y+((3*(12-APmap.getZoom()))+1)*a*.02,X));
}

function moveh(a) {
	var C = APmap.getCenter();
	var X = C.lng();
	var Y = C.lat();
	APmap.setCenter(new GLatLng(Y,X+((3*(12-APmap.getZoom()))+1)*a*.02));
}

var icon = new GIcon();
icon.image = "http://maps.google.com/mapfiles/kml/pal4/icon50.png";
icon.shadow = "";
icon.iconSize = new GSize(20, 20);
icon.shadowSize = new GSize(56, 32);
icon.iconAnchor = new GPoint(16, 32);
icon.infoWindowAnchor = new GPoint(16, 16); 

function activityfilter(cat,act,activity) {
	changeactivity(activity);
	selectedactivity=act
	selectedcategory=cat
	activitytitle=activity
	
	//<p class="title"><strong>Nearby Venues</strong></p>
	
	$('ul#nearestvenues').remove();
	$('div#locationlist iframe').remove();

	actsXML = "";
	
	$.ajax({
		type: 'GET',
		url: "/mysql/site-list-by-activity2.asp",
		dataType: 'xml',
		data: "categoryID="+selectedcategory+"&activityID="+selectedactivity+"&lat="+townsearchlat+"&lon="+townsearchlon,
		complete: function(a, b){
			if( b == 'success' ) {
				var xmlDoc = a.responseXML;
				actsXML = xmlDoc;
				croot = $('console',xmlDoc).attr('root');
				var zoom = parseInt($('maps',xmlDoc).attr('z'));
				//alert('activity set zoom = '+zoom);
				//alert('global zoom = '+overridezoom);
				
				q = 0;
				urls = new Array();
				activities = new Array();

				/************************/

				if(overridezoom >= 1 && overridezoom <= 12) {
					zoom = overridezoom;
				}
				
				APmap.clearOverlays();
	
				ew = new EWindow(APmap, E_STYLE_7);      
				APmap.addOverlay(ew);
				ewclick = new EWindow(APmap, E_STYLE_7);      
				APmap.addOverlay(ewclick); 
	
	
				var homepoint= new GLatLng(townsearchlat, townsearchlon);

				if (townsearched>0) {
					APmap.setCenter(new GLatLng(townsearchlat, townsearchlon), zoom);
				} else {
					//alert('3b lat='+townsearchlat);
					APmap.setCenter(new GLatLng(townsearchlat, townsearchlon), 5);
				}

				listcontent = "<ul id='nearestvenues'>\n";


				/************************/

				$('mark', xmlDoc).each(function() {
					var lat = $(this).attr('lat');
					var lng = $(this).attr('lng');

					point = new GLatLng(parseFloat(lat),parseFloat(lng));

					var box_title = $(this).attr('ttl');
					var distance = $(this).attr('dst');

					urls[q] = new Array();
					activities[q] = new Array();
					r = 0;
					
					$('activ', this).each(function() {

						var actID = $(this).attr('act');
						var locID = $(this).attr('loc');
	
						var act_ttl = $(this).attr('ttl');
						
						activities[q][r] = "Click Here for "+act_ttl;

						var url = croot+"?"+"activityID="+actID+"&locationID="+locID+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596";

						urls[q][r] = url;
						
						if(q < 5 && dist_disp) {
							listcontent = listcontent + "<li><a href=\"javascript:tb_show('','"+url+"','')\">"+act_ttl+" "+box_title+" <span>"+distance+" miles</span></a></li>\n";
						}
						
						r++;
					});

					//<li><a href='#'>paintballing manchester <span>23.5 miles</span></a></li>
					//"<a href=\"javascript:tb_show('','"+c[i]+"','')\">"+d[i]+"</a><br />"
	
					var html = ewtable(box_title, distance, urls[q], activities[q]); 

					APmap.addOverlay(createMarker(point, html, q, urls[q]));
					q++;
				});

				listcontent = listcontent + "</ul>\n";
				if(dist_disp) {
					$('div#locationlist').append(listcontent);
				} else {
					$('div#locationlist').append("<iframe src='/region_map_count.php' width='338px' height='234px' frameborder='0' scrolling='no'></iframe>");
				}

			} else {
				alert('Sorry, we could not complete the request. Please try again.');
				

			}

		}
	});

	/***/
	var centre = APmap.getCenter();
	var zoom = APmap.getZoom();

	map_height = $("#map").height();
	map_width = $("#map").width();

	log_search_loc = $('data markers mark:first activ:first',actsXML).attr('loc');

	log_search_query = "type=search&activityID="+selectedactivity+"&websiteID="+websiteID+"&locationID="+log_search_loc+"&mapLat="+centre.y+"&mapLon="+centre.x+"&mapZoom="+zoom+"&mapWidth="+map_width+"&mapHeight="+map_height+"&str_town="+str_town+"&self="+escape(document.location);

	$.ajax({
		type:'GET',
		url:'/mysql/log-map-activity.php',
		data:log_search_query
	});

	/***/

}
function load() {
	if (GBrowserIsCompatible()) {
		APmap = new GMap2(document.getElementById("map"));
		var mt = APmap.getMapTypes();
		for (var i=0; i<mt.length; i++) {
			mt[i].getMinimumResolution = function() {return 5;}
			mt[i].getMaximumResolution = function() {return 12;}
		}
		APmap.setCenter(new GLatLng(townsearchlat, townsearchlon), 5);
		//map.enableScrollWheelZoom();
		APmap.enableDoubleClickZoom();
		/*
		GDownloadUrl("/mysql/site-list-by-activity.asp?categoryID=1&activityID=0&lat="+townsearchlat+"&lon="+townsearchlon, function(data) {
			GEvent.addListener(map, "move", function() {
				checkBounds();
			});
			var allowedBounds = new GLatLngBounds(new GLatLng(49.5,-10), new GLatLng(59,2.6));    
			function checkBounds() {
				if (allowedBounds.contains(map.getCenter())) {
					return;
				}
				var C = map.getCenter();
				var X = C.lng();
				var Y = C.lat();
				var AmaxX = allowedBounds.getNorthEast().lng();
				var AmaxY = allowedBounds.getNorthEast().lat();
				var AminX = allowedBounds.getSouthWest().lng();
				var AminY = allowedBounds.getSouthWest().lat();
				if (X < AminX) {X = AminX;}
				if (X > AmaxX) {X = AmaxX;}
				if (Y < AminY) {Y = AminY;}
				if (Y > AmaxY) {Y = AmaxY;}
				map.setCenter(new GLatLng(Y,X));
			}	  
		});
		*/
		GEvent.addListener(APmap, "click", function(marker,point) {
			if (point) {
				ew.hide();
			}  
		});	
	}
}

/*******************
CR Map Work
*******************/
//get header GET vars
function getURLVar(urlVarName) {
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
		var urlVars = urlHalves[1].split('&');
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){	
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}
	
/*
var str_town = getURLVar('str_town');

//get the value of str_town from url;
//if it's not an empty string
	//set the value of the form to the value of str_town
	//submit the form
//
$(function() {
	if(str_town != '') {
		$("form[@name='searcher'] input[@name='str_town']").attr("value",str_town);
		$("form[@name='searcher']").submit();
	}
});

/* Alt Town */

$('a.alt_town').livequery('click',function() {
	//var alt_url = ;

	//alt_url = "/mysql/othertown.asp?id=" + alt_url
	
	town_name = $(this).text();

	$.ajax({
		type: 'GET',
		url: '/mysql/othertown.asp',
		dataType: 'xml',
		data: {id: $(this).attr('town_loc')},
		complete: function(a, b){
			if( b != 'success' )
			{
				//alert('Sorry, we could not complete the request. Please try again.');
				return;
			}
			towninfo = a.responseXML.documentElement.getElementsByTagName('towndata');
			
			townsearchlat=towninfo[0].getAttribute("lat");
			townsearchlon=towninfo[0].getAttribute("lon");
			
			activityfilter(0,2,"Karting Nation");
			changetown(town_name);
			
			APmap.setCenter(new GLatLng(townsearchlat, townsearchlon), 12);
			changeactivity("Go Ballistic");
			townsearched=1;
			//APmap.clearOverlays();
			$('#othertowns').fadeOut('fast');
		}
	});

});

$(function(){
	load();
	$('body').unload(function(){
		GUnload();
	});
	//var venue_markers = activityfilter(0,2,"Karting Nation");
	var itm = getURLVar('str_town');
	if( location.search != '' ) {
		if( itm != '' ) {
			//$(function() {
			var display_itm = itm;
			display_itm = decodeURI(display_itm);
			var itm_frags = display_itm.split('#');
			display_itm = itm_frags[0];
			$('input#str_town').attr('value',display_itm);
			//});
			townsearch(itm);
		} else {
			var old_id = getURLVar('id');
			if(old_id > 0) {
				$.ajax({
					type: 'GET',
					url: '/mysql/old_id_search.asp',
					dataType: 'xml',
					data: {id: old_id},
					complete: function(a, b) {
						if( b != 'success' ) {
							//alert(b);
							//return;
						} else {
							townname = a.responseXML.documentElement.getElementsByTagName('town');
							town = townname[0].getAttribute('name');
							////alert(town);
              townsearch(town);
							//alert('4 lat='+townsearchlat);
							var venue_markers = activityfilter(0,2,"Karting Nation");
						}
					}
				});
			} 
		}
	}
	if(itm == '') {
		//alert('5 lat='+townsearchlat);
		var markers = activityfilter(0,2,"Karting Nation");
	}


	var cat = getURLVar('categoryID');
	var actid = getURLVar('activityID');
	var act_id = actid.split('#');
	act = act_id[0];
	var activity = getURLVar('activity');

	if(cat != 0 || act != 0) {
		//var markers = activityfilter(cat,act,activity);
	}
	
	//if(cat != 0) {
	//	var markers = activityfilter(cat,0,activity);
	//} else {
	//	if(act != 0) {
	//		var markers = activityfilter(0,act,activity);
	//	}
	//}
	
	
	setTimeout("$('#othertowns').fadeOut('slow');", 15000);
});

$(function() {
	//eg http://rs2.theactivitypeople.co.uk/console.asp?str_town=liverpool&activityID=1&showmicrosite=true&micrositeurl=http://console.theactivitypeople.co.uk/venue.php?activityID=1&locationID=7630&websiteID=2&KeepThis=true&TB_iframe=true&height=412&width=600
	//eg http://rs2.theactivitypeople.co.uk/console.asp?str_town=liverpool&activityID=1&showmicrosite=true&micrositeurl=http%3A%2F%2Fconsole.theactivitypeople.co.uk%2Fvenue.php%3FactivityID%3D2%26locationID%3D3808%26websiteID%3D2%26KeepThis%3Dtrue%26TB_iframe%3Dtrue%26height%3D412%26width%3D600
	var showmicrosite = getURLVar('showmicrosite');
	if(showmicrosite == 'true') {
		var msi = getURLVar('micrositeurl');
		var micrositeURL = decodeURI(msi);
		micrositeURL = micrositeURL.replace(/%3A/g,":");
		micrositeURL = micrositeURL.replace(/%2F/g,"/");
		micrositeURL = micrositeURL.replace(/%3F/g,"?");
		micrositeURL = micrositeURL.replace(/%3D/g,"=");
		micrositeURL = micrositeURL.replace(/%26/g,"&");
		tb_show("",micrositeURL,"");
		return true;
	};
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//thickbox//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  
var tb_pathToImage = "/new/img/loading.gif";
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'></a></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'></a></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}