// define JSON setup
var mainJSON = { menuNavigation: [
	{ name:"Meet the Litter", url: "index.htm", baseUrl:"/content/litter/", activeState:"litter",
		menuConfig: { width:"100",
			menus: [
				{ name:"Shannon", target:"1" },
				{ name:"Lee", target:"2" },
				{ name:"Ari", target:"3" },
				{ name:"Meagan", target:"4" },
				{ name:"Miriam", target:"5" },
				{ name:"Melanie", target:"6" }
			]
		}
	},	
	{ name:"Services & Pricing", url: "index.htm", baseUrl:"/content/services/", activeState:"services",
		menuConfig: { width:"146",
			menus: [
				{ name:"Services", target:"0" },
				{ name:"Pricing", target:"1" },
				{ name:"Service Area Map", target:"2" }
			]
		}
	},	
	{ name:"Client Testimonials", url:"/content/testimonials/index.htm", activeState:"testimonials" },	
	{ name:"Give us a Whistle", url:"/content/whistle/index.htm", activeState:"whistle"	},
	{ name:"The Contract", url:"/content/contract/index.htm",  activeState:"contract" }
]};

// parse the search string
function parseQuery(str) {
	var vars = str.split(/[&;]/);
	var rs = {};
	if (vars.length) vars.each(function(val) {
		var keys = val.split('=');
		if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = decodeURIComponent(keys[1]);
	});
	return rs;
}

function getQueryStringValues(url) {
		var qs = $pick(url, $pick(window.location.search, '')).split('?')[1]; //get the query string
		if(qs) return parseQuery(qs);
		return {}; //if there isn't one, return null
}

var qs = getQueryStringValues();

var urlLoc, urlLocArray;
function initFrameWork() {
	var sURL = location.href;
	sURL = sURL.toLowerCase();

	fullURLString = sURL;

	var paramIndex = sURL.indexOf('?');
	if (paramIndex != -1) {
		// remove any parameters only work with real folder locations
		sURL = sURL.slice(0,paramIndex);
	}
	
	paramIndex = sURL.indexOf('#');
	if (paramIndex != -1) {
		// remove any parameters only work with real folder locations
		sURL = sURL.slice(0,paramIndex);
	}

	fullURLStringNoParam = sURL;

	paramIndex = sURL.indexOf('://') + 3;
	sURL = sURL.slice(paramIndex); // remove all http:// | https:// text

	urlLocArray = sURL.split("/");
	urlLoc = sURL;
}

initFrameWork();

var vUpdateTimer, scrollObj;
var printerVersion = (qs.p == 'true') ? true : false;

var SlideMenu = new Class({
	initialize: function(relDivContainer, buttonSlider, leftPos, jsonData, allSliderRefs, sliderActive) {
		this.dropContainer = new Element('div', {'styles': {'position': 'absolute', 'width':jsonData.width + 'px', 'left':leftPos }});
		this.slideTimer = null;
		this.buttonSlider = buttonSlider;
		this.allSliderRefs = allSliderRefs;
				
		this.slidingDivContainer = new Element('div', {'class':'dropMenu'});

		jsonData.menus.each(function(el) {
			var dSelection = new Element('a', {'href': 'javascript:void(0);'}).set('text', el.name);

			if (!sliderActive) {
				dSelection.href = buttonSlider.href + '?t=' + el.target;
			} else {
				dSelection.addEvent('click', BuildMainNav.scrollToElement.bindWithEvent(BuildMainNav, el.target));
			}
			
			if (sliderActive) {
				// check for active page
				//dSelection.set('id', 'dropActive');
			
			}
			dSelection.inject(this);
		}.bind(this.slidingDivContainer));
		
		this.slidingDivContainer.inject(this.dropContainer);
		this.dropContainer.inject(relDivContainer);
		
		if (sliderActive) {
			this.slider = null;
		} else {
			this.slider = new Fx.Slide(this.slidingDivContainer, {duration: 200, link:'cancel'}).hide();
			
			(function(){ this.setStyle('margin-top', '-' + this.getSize().y + 'px'); }).delay(5, this.slidingDivContainer);
		
			this.buttonSlider.addEvent('mouseover', this.slideShow.bindWithEvent(this));
			this.buttonSlider.addEvent('mouseout', this.slideHide.bindWithEvent(this, false));
		
			this.slidingDivContainer.addEvent('mouseenter', function() { $clear(this.slideTimer); }.bind(this));
			this.slidingDivContainer.addEvent('mouseleave', this.slideHide.bindWithEvent(this, false));
		}
	},
	
	slideShow: function() {
		$clear(this.slideTimer);
		this.slider.slideIn();
		
		// hide all other sliders	
		if (!this.sliderActive) {
			this.buttonSlider.addClass('tempHover');
		}
		
		if (this.allSliderRefs.length > 1) {
			this.allSliderRefs.each(function(el) {
				if (el.slider.element != this.slider.element) {
					if (el.slidingDivContainer.getStyle('margin-top').toInt() == 0) {
						el.slideHide(true);
					}
				}
			}.bind(this));
		}	
	}, 
	
	slideHide: function(hideNow) {
		$clear(this.slideTimer);
		
		if (hideNow === true) {
			this.slider.slideOut();
			if (!this.sliderActive) {
				this.buttonSlider.removeClass('tempHover');
			}
			
		} else {
			this.slideTimer = (function() { this.slider.slideOut(); if (!this.sliderActive) { this.buttonSlider.removeClass('tempHover'); } }).delay(500, this);
		}
	}
});



var BuildMainNav = {
	initialize: function(divElement) {
		this.divElementName = divElement;
		
		if ($('contentScroll')) {
			this.scrollFx = new Fx.Scroll($('contentScroll'), {onComplete: function() { $clear(vUpdateTimer); scrollObj.vUpdateThumbFromContentScroll(); }});
		}
		
		this.navDiv = $(divElement);
		this.navDiv.setHTML('');
		this.dropDownContainer = new Element('div', {'id':'dropDownContainer'});
		this.sliderRef = [];
		
		mainJSON.menuNavigation.each( function(el, i) {
			var activeButton = false;
			var baseLink = (el.baseUrl) ? el.baseUrl : '';

			var hrefLink = baseLink + el.url;
			
			var buttonElem = new Element('a').set('html', el.name);

			if (urlLoc.match(el.activeState)) {
				activeButton = true;
				buttonElem.set('id', 'navActive');
			}
					
			var dropDownParam = el.menuConfig;
			
			if (dropDownParam) {
				if (!el.url) { hrefLink = 'javascript:void(0);'; }
			}
			
			if (!activeButton) {
				buttonElem.set('href', hrefLink);
			} else {
				buttonElem.set('href', 'javascript:void(0);');
				this.activeSectionButton = buttonElem;
			}
			
			buttonElem.inject(this.navDiv);
			
			if (dropDownParam) {
				var slRef = new SlideMenu(this.dropDownContainer, buttonElem, buttonElem.getCoordinates($(this.divElementName)).left, dropDownParam, this.sliderRef, activeButton)
				if (!activeButton) {
					this.sliderRef.push(slRef);
				}
			} else {
				buttonElem.addEvent('mouseover', this.hideAllActiveMenus.bindWithEvent(this));				
			}
		}.bind(this));
		
		
		this.dropDownContainer.inject(this.navDiv);
		
		if (typeof domIsReady == "function") {
			domIsReady();
		}
	},
	
	hideAllActiveMenus: function() {
		this.sliderRef.each(function(el) {
			if (el.slidingDivContainer.getStyle('margin-top').toInt() == 0) {
				el.slideHide(true);
			}
		}.bind(this));	
	},
	
	scrollToElement: function(event, elementTarget) {
		$clear(vUpdateTimer);

		if ($(elementTarget) || elementTarget == '0') {
			vUpdateTimer = scrollObj.vUpdateThumbFromContentScroll.periodical(40, scrollObj);
			if (elementTarget == '0') {
				BuildMainNav.scrollFx.toTop();
			} else {
				BuildMainNav.scrollFx.toElement(elementTarget);
			}
		}	
	}
};


var ScrollBar = new Class({
	Implements: [Events, Options],

	options: {
		maxThumbSize: 15,
		wheel: 8,
		arrows: true,
		hScroll: true // horizontal scrollbars
	},

	initialize: function(main, content, options) {
		this.setOptions(options);
		
		if (qs.t) {
			if ($(qs.t) && qs.t != "0") {
				//$(content).scrollTop = $(content).getPosition(qs.t).y * -1;
			} else {
				$(content).scrollTop = 0;
			}
		} else {
			$(content).scrollTop = 0;
		}
		
		this.main = $(main);
		this.content = $(content);
	
		if (this.options.arrows == true) {
			this.arrowOffset = 30;
		} else {
			this.arrowOffset = 0;
		}

		if (this.options.hScroll == true) {
			this.hScrollOffset = 15;
		} else {
			this.hScrollOffset = 0;
		}

		this.vScrollbar = new Element('div', {'class': 'vScrollbar'}).inject(this.content, 'after');

		if (this.options.arrows == true) {
			this.arrowUp = new Element('div', {'class': 'arrowUp'}).inject(this.vScrollbar, 'inside');
			this.arrowUp.addEvent('mouseover', function() { this.addClass('arrowUp_over') }.bind(this.arrowUp));
		}

		this.vTrack = new Element('div', {'class': 'vTrack'}).inject(this.vScrollbar, 'inside');

		this.vThumb = new Element('div', {'class': 'vThumb'}).inject(this.vTrack, 'inside');
		this.vThumb.addEvent('mouseover', function() { this.addClass('vThumb_over') }.bind(this.vThumb));
		this.vThumb.addEvent('mouseout', function() { if (!this.vMouse.start) { this.vThumb.removeClass('vThumb_over'); }}.bind(this));
		
		if (this.options.arrows == true) {
			this.arrowDown = new Element('div', {'class': 'arrowDown'}).inject(this.vScrollbar, 'inside');
			this.arrowDown.addEvent('mouseover', function() { this.addClass('arrowDown_over') }.bind(this.arrowDown));
		}
		
		if (this.options.hScroll) {
			this.hScrollbar = new Element('div', {'class': 'hScrollbar'}).inject(this.vScrollbar, 'after');

			if (this.options.arrows == true) {
				this.arrowLeft = new Element('div', {'class': 'arrowLeft'}).inject(this.hScrollbar, 'inside');
			}

			this.hTrack = new Element('div', {'class': 'hTrack'}).inject(this.hScrollbar, 'inside');

			this.hThumb = new Element('div', {'class': 'hThumb'}).inject(this.hTrack, 'inside');

			if (this.options.arrows == true) {
				this.arrowRight = new Element('div', {'class': 'arrowRight'}).inject(this.hScrollbar, 'inside');
			}

			this.corner = new Element('div', {'class': 'corner'}).inject(this.hScrollbar, 'after');
		}
		
		this.bound = {
			'vStart': this.vStart.bind(this),
			'hStart': this.hStart.bind(this),				
			'end': this.end.bind(this),
			'vDrag': this.vDrag.bind(this),
			'hDrag': this.hDrag.bind(this),				
			'wheel': this.wheel.bind(this),
			'vPage': this.vPage.bind(this),
			'hPage': this.hPage.bind(this)
		};

		this.vPosition = {};
		this.hPosition = {};
		this.vMouse = {};
		this.hMouse = {};
		this.update();
		this.attach();
	},

	update: function() {
		//var offsetW = '776'; //this.content.offsetWidth;

		//this.main.setStyle('height', this.content.offsetHeight + this.hScrollOffset);
		this.vTrack.setStyle('height', this.content.offsetHeight - this.arrowOffset - 2);

		this.main.setStyle('width', '766px'); //this.content.offsetWidth + 15);
		if (this.options.hScroll) { this.hTrack.setStyle('width', this.content.offsetWidth - this.arrowOffset);	}
		
		// Remove and replace vertical scrollbar			
		if (this.content.scrollHeight <= this.main.offsetHeight) {
			this.vScrollbar.setStyle('visibility', 'hidden');
			$('contentRight').setStyle('border-right-color', '#D9F3FD');

			//this.vScrollbar.setStyle('display', 'none');
			//if (this.options.hScroll == true){				
			//	this.hTrack.setStyle('width', this.hTrack.offsetWidth + 15);
			//}
			//this.content.setStyle('width', (this.content.offsetWidth) + 'px');	
		} else {
			this.vScrollbar.setStyle('display', 'block');
			
			BuildMainNav.activeSectionButton.addEvent('click', BuildMainNav.scrollToElement.bindWithEvent(BuildMainNav, '0'));
		}

		if (this.options.hScroll == true) {
			// Remove and replace horizontal scrollbar
			if (this.content.scrollWidth <= this.main.offsetWidth) {
				this.hScrollbar.setStyle('display', 'none');
				this.vTrack.setStyle('height', this.vTrack.offsetHeight + this.hScrollOffset);
				this.content.setStyle('height', this.content.offsetHeight + this.hScrollOffset);
			} else {
				this.hScrollbar.setStyle('display', 'block');
			}

			// Remove and replace bottom right corner spacer
			if (this.content.scrollHeight <= this.main.offsetHeight || this.content.scrollWidth <= this.main.offsetWidth) {
				this.corner.setStyle('display', 'none');
			} else {
				this.corner.setStyle('display', 'block');
			}

			// Horizontal
			this.hContentSize = this.content.offsetWidth;
			this.hContentScrollSize = this.content.scrollWidth;
			this.hTrackSize = this.hTrack.offsetWidth;

			this.hContentRatio = this.hContentSize / this.hContentScrollSize;

			this.hThumbSize = (this.hTrackSize * this.hContentRatio).limit(this.options.maxThumbSize, this.hTrackSize);

			this.hScrollRatio = this.hContentScrollSize / this.hTrackSize;

			this.hThumb.setStyle('width', this.hThumbSize);

			this.hUpdateThumbFromContentScroll();
			this.hUpdateContentFromThumbPosition();
		} else if (this.options.hScroll) {
			this.hScrollbar.setStyle('display', 'none');
			this.corner.setStyle('display', 'none');										
		}

		// Vertical
		this.vContentSize = this.content.offsetHeight;
		this.vContentScrollSize = this.content.scrollHeight;
		this.vTrackSize = this.vTrack.offsetHeight;

		this.vContentRatio = this.vContentSize / this.vContentScrollSize;

		this.vThumbSize = (this.vTrackSize * this.vContentRatio).limit(this.options.maxThumbSize, this.vTrackSize);

		this.vScrollRatio = this.vContentScrollSize / this.vTrackSize;

		this.vThumb.setStyle('height', this.vThumbSize);

		this.vUpdateThumbFromContentScroll();
		this.vUpdateContentFromThumbPosition();
	},

	vUpdateContentFromThumbPosition: function() {
		this.content.scrollTop = this.vPosition.now * this.vScrollRatio;
	},

	hUpdateContentFromThumbPosition: function() {
		this.content.scrollLeft = this.hPosition.now * this.hScrollRatio;
	},

	vUpdateThumbFromContentScroll: function() {
		this.vPosition.now = (this.content.scrollTop / this.vScrollRatio).limit(0, (this.vTrackSize - this.vThumbSize));
		this.vThumb.setStyle('top', this.vPosition.now);
	},

	hUpdateThumbFromContentScroll: function() {
		this.hPosition.now = (this.content.scrollLeft / this.hScrollRatio).limit(0, (this.hTrackSize - this.hThumbSize));
		this.hThumb.setStyle('left', this.hPosition.now);
	},

	attach: function() {
		this.vThumb.addEvent('mousedown', this.bound.vStart);
		
		if (this.options.wheel) { 
			this.content.addEvent('mousewheel', this.bound.wheel);
			this.vTrack.addEvent('mouseup', this.bound.vPage);
			
			if (this.options.hScroll) {
				this.hThumb.addEvent('mousedown', this.bound.hStart);
				this.hTrack.addEvent('mouseup', this.bound.hPage);
			}
			
			if (this.options.arrows == true) {
				this.arrowUp.addEvent('mousedown', function(event) {
					this.interval = (function(event) {
						this.content.scrollTop -= this.options.wheel;
						this.vUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));

				this.arrowUp.addEvent('mouseup', function(event) {
					$clear(this.interval);
				}.bind(this));

				this.arrowUp.addEvent('mouseout', function(event) {
					this.arrowUp.removeClass('arrowUp_over');
					$clear(this.interval);
				}.bind(this));

				this.arrowDown.addEvent('mousedown', function(event) {
					this.interval = (function(event) {
						this.content.scrollTop += this.options.wheel;
						this.vUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));

				this.arrowDown.addEvent('mouseup', function(event) {
					$clear(this.interval);
				}.bind(this));

				this.arrowDown.addEvent('mouseout', function(event) {
					this.arrowDown.removeClass('arrowDown_over');
					$clear(this.interval);
				}.bind(this));
				
				if (this.options.hScroll) {
					this.arrowLeft.addEvent('mousedown', function(event) {
						this.interval = (function(event){
							this.content.scrollLeft -= this.options.wheel;
							this.hUpdateThumbFromContentScroll();
						}.bind(this).periodical(40))
					}.bind(this));

					this.arrowLeft.addEvent('mouseup', function(event){
						$clear(this.interval);
					}.bind(this));

					this.arrowLeft.addEvent('mouseout', function(event){
						$clear(this.interval);
					}.bind(this));

					this.arrowRight.addEvent('mousedown', function(event){
						this.interval = (function(event){
							this.content.scrollLeft += this.options.wheel;
							this.hUpdateThumbFromContentScroll();
						}.bind(this).periodical(40))
					}.bind(this));

					this.arrowRight.addEvent('mouseup', function(event){
						$clear(this.interval);
					}.bind(this));

					this.arrowRight.addEvent('mouseout', function(event){
						$clear(this.interval);
					}.bind(this));
				}
			}
		}
	},
		
	wheel: function(event){
		this.content.scrollTop -= event.wheel * this.options.wheel;
		this.vUpdateThumbFromContentScroll();
		event.stop();
	},

	vPage: function(event){
		if (event.page.y > this.vThumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
		else this.content.scrollTop -= this.content.offsetHeight;
		this.vUpdateThumbFromContentScroll();
		event.stop();
	},
		
	hPage: function(event){
		if (event.page.x > this.hThumb.getPosition().x) this.content.scrollLeft += this.content.offsetWidth;
		else this.content.scrollLeft -= this.content.offsetWidth;
		this.hUpdateThumbFromContentScroll();
		event.stop();
	},		

	vStart: function(event) {
		this.vMouse.start = event.page.y;
		this.vPosition.start = this.vThumb.getStyle('top').toInt();
		document.addEvent('mousemove', this.bound.vDrag);
		document.addEvent('mouseup', this.bound.end);
		this.vThumb.addEvent('mouseup', this.bound.end);
		event.stop();
	},
		
	hStart: function(event){
		this.hMouse.start = event.page.x;		
		this.hPosition.start = this.hThumb.getStyle('left').toInt();
		document.addEvent('mousemove', this.bound.hDrag);
		document.addEvent('mouseup', this.bound.end);
		this.hThumb.addEvent('mouseup', this.bound.end);
		event.stop();
	},		

	end: function(event) {
		this.vThumb.removeClass('vThumb_over');
		this.vMouse.start = null;
		document.removeEvent('mousemove', this.bound.vDrag);
		document.removeEvent('mousemove', this.bound.hDrag);			
		document.removeEvent('mouseup', this.bound.end);
		this.vThumb.removeEvent('mouseup', this.bound.end);
		if (this.options.hScroll) {
			this.hThumb.removeEvent('mouseup', this.bound.end);	
		}
		event.stop();
	},

	vDrag: function(event){
		this.vMouse.now = event.page.y;
		this.vPosition.now = (this.vPosition.start + (this.vMouse.now - this.vMouse.start)).limit(0, (this.vTrackSize - this.vThumbSize));
		this.vUpdateContentFromThumbPosition();
		this.vUpdateThumbFromContentScroll();
		event.stop();
	},
		
	hDrag: function(event){
		this.hMouse.now = event.page.x;
		this.hPosition.now = (this.hPosition.start + (this.hMouse.now - this.hMouse.start)).limit(0, (this.hTrackSize - this.hThumbSize));
		this.hUpdateContentFromThumbPosition();
		this.hUpdateThumbFromContentScroll();
		event.stop();
	}
});



function writeFooter() {
	var theDate = new Date();
	var theYear = theDate.getFullYear();
	var displayYear = ('&copy; ' + theYear + ' ');
	
	document.write('<div id="footer">' + displayYear + 'Companion Care Inc. All Rights Reserved.<br/><a href="mailto:admin@companioncareaustin.com">admin@companioncareaustin.com</a></div>');
}

function openWindow(theURL,winName,features) {
	if (!features) {
		features = 'toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=900,height=700';
	}
	if (!winName) {
		winName = 'newwindow';
	}
	
	var newW = window.open(theURL,winName,features);
	if (newW) {
		newW.focus();
	}
}

window.addEvent('domready', function() {
	if (printerVersion) {
		//document.body.setStyle('text-align', 'left');

		$('bodyContainer').setStyles({'position':'static', 'margin':'0px 0px', 'padding':'4px', 'width':'650px', 'height':'auto', 'text-align':'left', 'border':'none'});
		$('footer').setStyles({'width':'650px', 'padding-top':'20px'});

		if ($('contentRight')) {	
			$('logo').setStyle('display', 'none');
			var compInfo = new Element('div', {'id':'companyPrintHeader'}).set('html', '<span id="compHead">Companion Care, Inc.</span><br />#222 PO Box 2013<br />Austin, TX 78768<br />512.459.CARE<img src="/includes/images/logo.gif" alt="Home" title="Home" width="66" height="53" />');		
			compInfo.inject($('contentRight'), 'top');
		
			var newDivContainer = new Element('div', {'id':'printContainer'});
			newDivContainer.adopt($('contentRight'));
		
			newDivContainer.inject(document.body, 'top');
		
			$('bodyContainer').destroy();
/*		
			$('content').setStyles({'position': 'static', 'width':'100%', 'height':'100%', 'background':'none'});	
			$('contentFrame').setStyles({'position': 'static', 'top':'0', 'left':'0', 'width':'auto', 'height':'auto', 'background':'none', 'border':'none', 'overflow':'visible'});	
			$('contentScroll').setStyles({'float':'none', 'width':'auto', 'height':'auto', 'overflow':'auto'});
			$('pictureLeft').setStyle('display', 'none');
			$('contentRight').setStyles({'float':'none', 'width':'auto', 'height':'auto', 'background':'none', 'border':'none', 'padding':'0px'});	*/
		}
	
		if (typeof domIsReady == "function") {
			domIsReady();
		}
		
		if (typeof loadReady == "function") {
			loadReady();
		}
		
		window.addEvent('load', function() {
				(function() { window.print(); }).delay(300);
		});
			
	} else {
		if ($('contentRight')) {
			var printerRedirect = window.location;
			printerRedirect = 'http://' + printerRedirect.host + printerRedirect.pathname + '?p=true';
	
			var printElement = new Element('a', {'href': 'javascript:openWindow("' + printerRedirect + '", "_blank", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=680, height=600")', 'id':'printfriendly'}).set('text', 'Print');
			printElement.inject($('navigation'), 'after');
		}
		
		BuildMainNav.initialize('navigation');
		
		if ($('contentScroll')) {
			scrollObj = new ScrollBar('contentFrame', 'contentScroll', { 'hScroll': false, 'wheel':20 });
		}
	}
});

window.addEvent('load', function() {
	if (!printerVersion) {
		if (qs.t) {
			// scroll down the page
			(function() { BuildMainNav.scrollToElement(false, qs.t); }).delay(200);
		}
		
		if (typeof loadReady == "function") {
			loadReady.delay(500);
		}
	}
});
