Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;


/* Common functions */

function IsEmail(_email) {
    email_re1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\.$)/;
    email_re2 = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (_email == "" || email_re1.exec(_email) || !email_re2.exec(_email))
        return false;
    return true;
}

/*******
********
********
********/

//Fix PNG

var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
function fixPNG(myImage) {
	if (myImage.Fixed)
		return;
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
		if (!myImage.src.endsWith('.png'))
			return;
		myImage.Fixed = true;
		var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
		var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
		var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' ";
		var imgStyle = "display:inline-block;" + myImage.style.cssText;
		var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + myImage.width + "px; height:" + myImage.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
		myImage.outerHTML = strNewHTML;
	}
}
function fixPNGLoader() {
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
		//document.getElementById('GoogleMap');
		var imgs = document.getElementsByTagName('img');
		for (var i = 0; i < imgs.length; i++) {
			if (imgs[i].src.endsWith('.png'))
				fixPNG(imgs[i]);
		}
	}
}
//Event.observe(window, 'load', fixPNGLoader);

/***********************************************************************************************************/

//SearchInput
function searchSmartInputs() {
	var SmartInputs = document.getElementsByClassName('SmartInput');
	for (var i = 0; i < SmartInputs.length; i++)
		activateSmartInput(SmartInputs[i]);
}
function activateSmartInput(SmartInput) {
	//var SearchInput = $('SearchInput');
	
	SmartInput.hasFocus = false;

	var mouseover = function() {
		if (this.value == this.defaultValue) {
			this.style.color = '#000000';
			this.value = '';
		}
	}
	Event.observe(SmartInput, 'mouseover', mouseover);

	var focus = function() {
		this.hasFocus = true;
		if (this.value == this.defaultValue) {
			this.style.color = '#000000';
			this.value = '';
		}
	}
	Event.observe(SmartInput, 'focus', focus);
	
	var mouseout = function() {
		if (this.value == '' && !this.hasFocus) {
			this.style.color = '';
			this.value = this.defaultValue;
		}
	};
	Event.observe(SmartInput, 'mouseout', mouseout);
	
	var blur = function() {
		this.hasFocus = false;
		if (this.value == '') {
			this.style.color = '';
			this.value = this.defaultValue;
		}
	};
	Event.observe(SmartInput, 'blur', blur);
}
Event.observe(window, 'load', searchSmartInputs);

/***********************************************************************************************************/

//TABS
/*
var TabsInfo = {
		TabsId: new Array('HomeT1', 'HomeT2', 'HomeT3', 'HomeT4'),
		DefaultTabId: 'HomeT1',
		BoxesId: new Array('HomeTEl1', 'HomeTEl2', 'HomeTEl3', 'HomeTEl4'),
		TabActiveClass: 'HomeTActive',
		TabOverClass: 'HomeTActive',
		TabClass: 'HomeTActive'
	}
*/
function activateTabs(TabsInfo) {
	if (TabsInfo.TabsId.length != TabsInfo.BoxesId.length) {
		alert('TabsInfo.TabsId.length != TabsInfo.BoxesId.length');
		return;
	}
		
	var OnTabClick = function () {
			this.TabsInfo.ActiveTabId = this.Id;
			for (i=0; i<this.TabsInfo.TabsId.length; i++) {
				var tab = $(this.TabsInfo.TabsId[i]);
				if (tab.Active) {
					tab.Active = false;
					tab.addClassName(this.TabsInfo.TabClass);
					tab.removeClassName(this.TabsInfo.TabActiveClass);
					tab.removeClassName(this.TabsInfo.TabOverClass);
					
					$(TabsInfo.BoxesId[i]).hide();
				}
			}
			this.Active = true;
			this.removeClassName(this.TabsInfo.TabClass);
			this.removeClassName(this.TabsInfo.TabOverClass);
			this.addClassName(this.TabsInfo.TabActiveClass);
			
			$(TabsInfo.BoxesId[ this.TabsInfo.TabsId.indexOf(this.Id) ]).show();
		}
	var OnTabMouseOver = function () {
			if (!this.Active) {
				this.addClassName(this.TabsInfo.TabOverClass);
				this.removeClassName(this.TabsInfo.TabClass);
			}
		}
	var OnTabMouseOut = function () {
			if (!this.Active) {
				this.addClassName(this.TabsInfo.TabClass);
				this.removeClassName(this.TabsInfo.TabOverClass);
			}
		}
	for (i=0; i<TabsInfo.TabsId.length; i++) {
		var tab = $(TabsInfo.TabsId[i]);
		tab.Id = TabsInfo.TabsId[i];
		tab.TabsInfo = TabsInfo;
		tab.Active = false;
		Event.observe( tab , 'click', OnTabClick);
		Event.observe( tab , 'mouseover', OnTabMouseOver);
		Event.observe( tab , 'mouseout', OnTabMouseOut);
		$(TabsInfo.BoxesId[i]).hide();
	}

	var fxx = OnTabClick.bind($(TabsInfo.DefaultTabId));
	fxx();
}

/***********************************************************************************************************/

/* Expander */
function Expander(_obj, hide) {
	if (_obj == null ) {
		_t = document.getElementsByClassName("Expander");
		if (_t.length == 0)
			return;
		_obj = _t[0];
	}
	var parent;
	var child;
	var children = _obj.childElements();
	for (var i=0; i < children.length ; i++) {
		Expander(children[i], hide);
		if (children[i].hasClassName("parent"))
			parent = children[i];
		if (children[i].hasClassName("child"))
			child = children[i];
	}
	if (!parent || !child)
		return;
	
	child._hide = hide;
	if (hide)
		child.hide();
	else
		child.show();

	Event.observe(parent, 'click', function() {
												child.toggle();
												if (child._hide)
													parent.className = parent.className.replace("Plus", 'Minus');
												else
													parent.className = parent.className.replace("Minus", 'Plus');
												child._hide = !child._hide;
											} );
}
//Event.observe(window, 'load', function(){ Expander(null, true); } );

/***********************************************************************************************************/

/* ShoppingCart */
function CartInitialize() {
	
	var CartContainer = $('CartContainer');
	if (!CartContainer)
		return;
	var Moving = 0.15;
	var Speed = 10;
	var OriginWidth = CartContainer.firstDescendant().getWidth();
	
	var Move = function() {
		var width = CartContainer.width;
		var Moving = CartContainer.Moving;

		if ((width <= 0 && Moving < 0) || (width >= OriginWidth && Moving >0) || Moving == 0)
			return;
		
		
		var temp;
		if (Moving > 0)
			temp = Math.round((OriginWidth - width) * Moving);
		else
			temp = Math.round(width * Moving);
		
		if (Math.abs(temp) < 2)
			temp = (Moving < 0)? -1 : 1;

		width += temp;
		
		
		if (width > OriginWidth)
			width = OriginWidth;
		else if (width < 0)
			width = 0;

		CartContainer.width = width;
		CartContainer.setStyle({
			'width': width + 'px'
		});
		
		if (Speed >= 2)
			setTimeout(Move, Speed);
		else
			Move();
	}
	var OpenCart = (document.getElementsByClassName("OpenCart"))[0];
	Event.observe(OpenCart, 'click', function() {
										CartContainer.Moving = Moving;
										CartContainer.width = parseInt(CartContainer.getStyle('width'));
										Move();
									} );
	Event.observe(CartContainer, 'click', function() {
										CartContainer.Moving = -1 * Moving;
										CartContainer.width = parseInt(CartContainer.getStyle('width'));
										Move();
									} );
}
//Event.observe(window, 'load', CartInitialize );

/***********************************************************************************************************/

/* CorrectHeight */
function CorrectHeight() {
	
	var staticHeight = 462;
	
	
	/*
	var divHeight;
	var obj = document.getElementById('LContent');
	if(obj.offsetHeight)          {divHeight=obj.offsetHeight;}
	else if(obj.style.pixelHeight){divHeight=obj.style.pixelHeight;}
	alert(divHeight);
	*/
	
	
	var LContent = $('LContent');
	
	
	//LHeader.addClassName('read');
	//alert(LContent.id);
	//alert(LContent.getHeight());
	//alert((LContent.getHeight() % staticHeight));

	var oldHeight = LContent.getHeight();

	if (oldHeight == 587 || oldHeight == 584)
		return;

	/*
	if(Prototype.Browser.IE)
		oldHeight = oldHeight - 90;
	*/
	var newHeight;
	var HaveToFix = true;
	var diff = oldHeight % staticHeight;

	//alert(LContent.getHeight() + '-' + diff);

	// 18 px diff
	if (HaveToFix && diff <= 18) {
		HaveToFix = false;

		$('LFooter').setStyle({
			'background': 'url(/imgs/bc_footer_18.jpg)'
		});
		
		if (18 - diff !=0 ) {
			newHeight = oldHeight + 18 - diff;
			LContent.setStyle({
				'height': newHeight + 'px'
			});
		}
	}



	// 154 px diff
	if (HaveToFix && diff <= 154) {
		HaveToFix = false;

		$('LFooter').setStyle({
			'background': 'url(/imgs/bc_footer_154.jpg)'
		});
		
		if (154 - diff !=0 ) {
			if (!(Prototype.Browser.IE6 || Prototype.Browser.IE7)) {
				newHeight = oldHeight + 154 - diff;
				LContent.setStyle({
					'height': newHeight + 'px'
				});
			}
		}
	}


	// 308 px diff
	if (HaveToFix && diff <= 308) {
		HaveToFix = false;

		$('LFooter').setStyle({
			'background': 'url(/imgs/bc_footer_308.jpg)'
		});
		
		if (308 - diff !=0 ) {
			newHeight = oldHeight + 308 - diff;
			LContent.setStyle({
				'height': newHeight + 'px'
			});
		}
	}


	// all period diff
	if (HaveToFix && diff <= staticHeight) {
		HaveToFix = false;
		
		if ($('LFooter'))
			$('LFooter').setStyle({
				'background': 'url(/imgs/bc_footer_462.jpg)'
			});
		
		if (staticHeight - diff !=0 ) {
			newHeight = oldHeight + staticHeight - diff;
			LContent.setStyle({
				'height': newHeight + 'px'
			});
		}
	}

	/*
	if (Prototype.Browser.IE) {
		var _objArray = $$('div');
		for (var i = 0; i < _objArray.length; i++) {
			if (_objArray[i].getStyle('position') == "relative") {
				if (_objArray[i].id.indexOf("shadowbox") != -1 )
					continue;
				ReinitialiseDOMelement(_objArray[i]);
			}
		}
	}
	*/
	if($('LHeader')!=null){
	$('LHeader').setStyle({
		'height': '38px'
	});
	}
	
}



if (!(typeof settingCorrectHeight !== "undefined" && settingCorrectHeight == false))
	Event.observe(window, 'load', CorrectHeight);

/***********************************************************************************************************/

function ReinitialiseDOMelement (objid) {
	var obj;
	if (typeof(objid) == "string")
		obj = $(objid);
	else
		obj = objid;
	var newHeight = obj.getHeight() + 1;
	obj.setStyle({'height': newHeight + 'px'});
	obj.setStyle({'height': (newHeight-1) + 'px'});
}

/***********************************************************************************************************/
/* SearchLocation */
var DirectionsResults = {
		pointFrom: '',
		calculated : 0,
		RadiusSearch : [],
		index:0
	};

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// extend Number object with methods for converting degrees/radians

Number.prototype.toRad = function() { // convert degrees to radians
 return this * Math.PI / 180;
}

Number.prototype.toDeg = function() { // convert radians to degrees (signed)
 return this * 180 / Math.PI;
}

Number.prototype.toBrng = function() { // convert radians to degrees (as bearing: 0...360)
 return (this.toDeg()+360) % 360;
}
 

function SearchLocation() {
	var inputSearchLocation = $('SearchLocation');
	if (inputSearchLocation.value != inputSearchLocation.defaultValue && inputSearchLocation.value != '') {
		//proximity search
		//F_getLatLongFromPostal(inputSearchLocation, function() {
		//													var latlng = '&lat=' + inputSearchLocation.Latitude + '&lng=' + inputSearchLocation.Longitude;
		//													document.location = '/Locations?search=' + escape(inputSearchLocation.value) + latlng;
		//											})
		F_getLatLongFromPostal(inputSearchLocation, function() {
			var url = '/ajax/locations';
			
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(transport) {
					eval(transport.responseText);
					//var point = new google.maps.LatLng(inputSearchLocation.Latitude, inputSearchLocation.Longitude);
					//var directionsService = new google.maps.DirectionsService();

					var RadiusSearch = "";
					var over500 = 0;
					var dissss = "";


					var lat1 = inputSearchLocation.Latitude;
					var lon1 = inputSearchLocation.Longitude;

					//DirectionsResults.pointFrom = point;
					for (var j = 0; j < jsonReturn.length; j++) {
						//var despoint = new google.maps.LatLng(jsonReturn[j].Latitude, jsonReturn[j].Longitude);
						//DirectionsResults.RadiusSearch[j] = {Point : despoint};
						
						var lat2 = parseFloat(jsonReturn[j].Latitude);
						var lon2 = parseFloat(jsonReturn[j].Longitude);

						var dis = distHaversine(lat1, lon1, lat2, lon2);
						
						//var dis = point.distanceFrom(  new GLatLng(jsonReturn[j].Latitude, jsonReturn[j].Longitude)  ) / 1000;
						dissss += dis + ", ";
						if (dis > 500)
							over500++;
						if ( dis < 100 )
							RadiusSearch += jsonReturn[j].LID + ',';
					}
					
					if (RadiusSearch == "" && over500 == jsonReturn.length) {
						for (var j = 0; j < jsonReturn.length; j++) {
							var lat2 = parseFloat(jsonReturn[j].Latitude);
							var lon2 = parseFloat(jsonReturn[j].Longitude);
	
							var dis = distHaversine(lat1, lon1, lat2, lon2);
							
							if ( dis < 1300 )
								RadiusSearch += jsonReturn[j].LID + ',';
						}
					}
					
					if (RadiusSearch == "") {
						
						MoveTo(inputSearchLocation.Latitude, inputSearchLocation.Longitude);

						alert('There are no locations close to ' + inputSearchLocation.value);
						return;
						
					}
					
					RadiusSearch = '&RadiusSearch=(' + RadiusSearch.substring(0, RadiusSearch.length - 1) + ')';
					
					var latlng = '&lat=' + inputSearchLocation.Latitude + '&lng=' + inputSearchLocation.Longitude;
					document.location = '/Locations?search=' + escape(inputSearchLocation.value) + latlng + RadiusSearch;
						
						
				}
			});
			//document.location = '/Locations?search=' + escape(inputSearchLocation.value) + latlng;
		});

	}else{
		document.location = '/Locations';
	}
	return false;
}

function distHaversine(lat1, lon1, lat2, lon2) {
	var R = 6371; // km
	var dLat = (lat2-lat1).toRad();
	var dLon = (lon2-lon1).toRad(); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
			Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	return R * c;
}

/***********************************************************************************************************/

/* FixSafariTopNav */
function FixSafariTopNav() {
	if (navigator.userAgent.indexOf('Safari') === -1)
		return;
	var seps = document.getElementsByClassName("N1Sep");
	for (var i=0; i < seps.length ; i++) {
		seps[i].style.marginLeft = '6px';
		seps[i].style.marginRight = '6px';
	}

}
//Event.observe(window, 'load', FixSafariTopNav);



function handleSuccessPH(transport){
	eval(transport.responseText);
	$('LSPhoneNumber').value = jsonReturn[0];
	//alert($('LSPhoneNumber').value);
}

function handleFailurePH(transport){
	alert('Ajax request failed');
}

function getPhoneNums(){
	var action = $F('LID');	
	//alert(action);
	var url = '/ajax/phonenumbers?LID='+action;
	
	var options = {
			method		:	'get',
			onSuccess	:	handleSuccessPH,
			onFailure	: 	handleFailurePH
	};
	
	return new Ajax.Request(url, options);
	
}

function setSubKey(){
	$F('subKey').value = $F('Child Name').value+""+$F('Email Address').value;	
}


