// page init
$(function(){
	initScrollBars();
	initHomeGallery();
	initInnerGallery();
	initTabs();
});

// cutsom scroll init
function initScrollBars() {
	$('div.scroll-holder').each(function(){
		var _holder = $(this);
		var _scroller = _holder.find('div.scrollable');
		_scroller.css({
			width: _scroller.width()
		})
	});
	HSA_initScrollbars();
}

// slideshow init
function initHomeGallery() {
	var _activeClass = 'active';
	var _switchTime = 5000;
	var _slideSpeed = 650;
	var _autoSlide = true;

	$('div.promo-holder').each(function(){
		var _holder = $(this);
		var _slider = _holder.find('div.slideset > div.slider').eq(0);
		var _slides = _slider.find('>div');
		var _pagerLinks = _holder.find('div.switcher li');
		var _slideCount = _slides.length;
		var _currentIndex = 0;
		var _stepWidth = 0;
		var _diff = 0;
		var _minWidth = 1000;
		var _timer;

		// flexible gallery
		$(window).resize(function(){
			reCalcDimensions();
			if(_stepWidth>_minWidth) _slides.css({width:_holder.width()});
			else _slides.css({width:_minWidth});
			_slider.css({marginLeft:-_stepWidth*_currentIndex-(_currentIndex*2+1)*(_diff)});
			autoSlide();
		});

		// gallery control
		_pagerLinks.each(function(_ind){
			$(this).click(function(){
				if(_currentIndex != _ind) {
					_currentIndex = _ind;
					switchSlide();
				}
				return false;
			});
		});

		// gallery animation
		function reCalcDimensions() {
			_stepWidth = _holder.width();
			if(_stepWidth<_minWidth) _diff = _minWidth-_stepWidth;
			else _diff=0;
			_diff = Math.round(_diff/2);
			_pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
		}
		function switchSlide() {
			autoSlide();
			reCalcDimensions();
			_slider.animate({marginLeft:-_stepWidth*_currentIndex-(_currentIndex*2+1)*(_diff)},{duration:_slideSpeed,queue:false});
		}
		function autoSlide() {
			if(_autoSlide) {
				if(_timer) clearTimeout(_timer)
				_timer = setTimeout(function(){
					if(_currentIndex < _slideCount-1) _currentIndex++;
					else _currentIndex=0;
					switchSlide();
				},_switchTime)
			}
		}
		$(window).trigger('resize');
		autoSlide();
	});

}

// inner gallery
function initInnerGallery() {
	$('div.gallery-holder').scrollGallery({
		sliderHolder: 'div.slider-holder',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'.pager li',
		autoRotation:false,
		switchTime:5000,
		duration:650,
		step:1
	});
}

function initTabs() {
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					//reset all tabs on start
					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							//reset all tabs before change
							for (var i = 0; i < this.tabs.length; i++)
							{
								document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1)).style.display = "none";
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		pauseOnHover:true,
		autoRotation:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		vertical:false,
		step:false
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;

		// gallery init
		if(!_slides.length) return;
		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;
		var _animateProperty = (_vertical ? 'marginTop' : 'marginLeft');

		_slides.each(function(){
			_sumWidth+=$(this).outerWidth(true);
			_sumHeight+=$(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true);
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
		}
		function switchSlide() {
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		refreshStatus();
		autoSlide();
	});
}

// custom scrollbar script
var HSA_scrollAreas = new Array();
var HSA_default_imagesPath = "images";
var HSA_default_btnLeftImage = "button-left.gif";
var HSA_default_btnRightImage = "button-right.gif";
var HSA_default_scrollStep = 5;
var HSA_default_wheelSensitivity = 10;
var HSA_default_scrollbarPosition = 'bottom'; //'top';//'bottom';'inline';
var HSA_default_scrollButtonWidth = 33;
var HSA_default_scrollbarHeight = 23;
var HSA_resizeTimer = 200;

function HSA_initScrollbars() {
	var scrollElements = HSA_getElements("scrollable", "DIV", document, "class");
	for (var i=0; i<scrollElements.length; i++)
	{
		HSA_scrollAreas[i] = new ScrollArea(i, scrollElements[i]);
	}
}

function ScrollArea(index, elem) //constructor
{
	this.index = index;
	this.element = elem;

	var attr = this.element.getAttribute("imagesPath");
	this.imagesPath = attr ? attr : HSA_default_imagesPath;

	attr = this.element.getAttribute("btnLeftImage");
	this.btnLeftImage = attr ? attr : HSA_default_btnLeftImage;

	attr = this.element.getAttribute("btnRightImage");
	this.btnRightImage = attr ? attr : HSA_default_btnRightImage;

	attr = Number(this.element.getAttribute("scrollStep"));
	this.scrollStep = attr ? attr : HSA_default_scrollStep;

	attr = Number(this.element.getAttribute("wheelSensitivity"));
	this.wheelSensitivity = attr ? attr : HSA_default_wheelSensitivity;

	attr = this.element.getAttribute("scrollbarPosition");
	this.scrollbarPosition = attr ? attr : HSA_default_scrollbarPosition;

	attr = this.element.getAttribute("scrollButtonWidth");
	this.scrollButtonWidth = attr ? attr : HSA_default_scrollButtonWidth;

	attr = this.element.getAttribute("scrollbarHeight");
	this.scrollbarHeight = attr ? attr : HSA_default_scrollbarHeight;

	this.scrolling = false;

	this.iOffsetX = 0;
	this.scrollWidth = 0;
	this.scrollContent = null;
	this.scrollbar = null;
	this.scrollleft = null;
	this.scrollright = null;
	this.scrollslider = null;
	this.scroll = null;
	this.enableScrollbar = false;
	this.scrollFactor = 1;
	this.scrollingLimit = 0;
	this.leftPosition = 0;

	//functions declaration
	this.init = HSA_init;
	this.scrollLeft = HSA_scrollLeft;
	this.scrollRight = HSA_scrollRight;
	this.createScrollBar = HSA_createScrollBar;
	this.scrollIt = HSA_scrollIt;

	this.init();

}


function HSA_init()
{


	this.scrollContent = document.createElement("DIV");
	this.scrollContent.style.position = "absolute";
	this.scrollContent.style.width = this.element.offsetWidth + "px";
	this.scrollContent.style.height = this.element.offsetHeight + "px";
	this.scrollContent.innerHTML = this.element.innerHTML;
	this.scrollContent.style.overflow = "hidden";

	this.element.innerHTML = "";

	this.element.style.overflow = "hidden";
	this.element.style.display = "block";
	this.element.style.visibility = "visible";
	this.element.style.position = "relative";
	this.element.appendChild(this.scrollContent);

	this.scrollContent.className = 'scroll-content';

	this.element.index = this.index;
	this.element.over = false;

	var _this = this;
	this.element.onmouseover = function(){
        _this.element.over = true;
    };
    this.element.onmouseout = function(){
        _this.element.over = false;
    }

	if (document.all)
	{
		this.element.onscroll = HSA_handleOnScroll;
		this.element.onresize = HSA_handleResize;
	}
	else
	{
		window.onresize = HSA_handleResize;
	}

	this.createScrollBar();
	if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        this.element.addEventListener('DOMMouseScroll', HSA_handleMouseWheel, false);
	/** IE/Opera. */
	this.element.onmousewheel = document.onmousewheel = HSA_handleMouseWheel;

}

function HSA_createScrollBar()
{

	if (this.scrollbar != null)
	{
		this.element.removeChild(this.scrollbar);
		this.scrollbar = null;
	}


	if (this.scrollContent.scrollWidth <= this.scrollContent.offsetWidth)
		this.enableScrollbar = false;
	else if (this.element.offsetWidth > 2*this.scrollButtonWidth)
		this.enableScrollbar = true;
	else
		this.enableScrollbar = false;

	if (this.scrollContent.scrollWidth - Math.abs(this.scrollContent.scrollLeft) < this.element.offsetWidth)
		this.scrollContent.style.left = 0;

	if (this.enableScrollbar)
	{

		this.scrollbar = document.createElement("DIV");
		this.element.appendChild(this.scrollbar);
		this.scrollbar.style.position = "absolute";
		this.scrollbar.style.left = "0px";
		this.scrollbar.style.width = this.element.offsetWidth+"px";
		this.scrollbar.style.height = this.scrollbarHeight + "px";

		this.scrollbar.className = 'hscroll-bar';

		if(this.scrollbarHeight != this.scrollbar.offsetHeight)
		{
			this.scrollbarHeight = this.scrollbar.offsetWidth;
		}

		this.scrollbarHeight = this.scrollbar.offsetHeight;

		if(this.scrollbarPosition == 'top')
		{
			this.scrollContent.style.top = this.scrollbarHeight + 5 + "px";
			this.scrollContent.style.height = this.element.offsetHeight - this.scrollbarHeight - 5 + "px";
		}
		else if (this.scrollbarPosition == 'bottom')
		{
			this.scrollbar.style.top = this.element.offsetHeight - this.scrollbarHeight  + "px";
			this.scrollContent.style.height = this.element.offsetHeight - this.scrollbarHeight - 5 + "px";
		}


		//create scroll up button
		this.scrollleft = document.createElement("DIV");
		this.scrollleft.index = this.index;
		this.scrollleft.onmousedown = HSA_handleBtnLeftMouseRight;
		this.scrollleft.onmouseup = HSA_handleBtnLeftMouseLeft;
		this.scrollleft.onmouseout = HSA_handleBtnLeftMouseOut;
		this.scrollleft.style.position = "absolute";
		this.scrollleft.style.left = "0px";
		this.scrollleft.style.width = this.scrollButtonWidth + "px";
		this.scrollleft.style.height = this.scrollbarHeight + "px";

		this.scrollleft.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnLeftImage + '" border="0"/>';
		this.scrollbar.appendChild(this.scrollleft);

		this.scrollleft.className = 'hscroll-left';

		if(this.scrollButtonWidth != this.scrollleft.offsetWidth)
		{
			this.scrollButtonWidth = this.scrollleft.offsetWidth;
		}

		//create scroll down button
		this.scrollright = document.createElement("DIV");
		this.scrollright.index = this.index;
		this.scrollright.onmousedown = HSA_handleBtnRightMouseRight;
		this.scrollright.onmouseup = HSA_handleBtnRightMouseLeft;
		this.scrollright.onmouseout = HSA_handleBtnRightMouseOut;
		this.scrollright.style.position = "absolute";
		this.scrollright.style.left =  this.scrollbar.offsetWidth - this.scrollButtonWidth + "px";
		this.scrollright.style.height = this.scrollbarHeight + "px";
		this.scrollright.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnRightImage + '" border="0"/>';
		this.scrollbar.appendChild(this.scrollright);

		this.scrollright.className = 'hscroll-right';


		//create scroll
		this.scroll = document.createElement("DIV");
		this.scroll.index = this.index;
		this.scroll.style.position = "absolute";
		this.scroll.style.zIndex = 0;
		this.scroll.style.textAlign = "center";
		this.scroll.style.left = this.scrollButtonWidth + "px";
		this.scroll.style.height = this.scrollbarHeight + "px";

		var h = this.scrollbar.offsetWidth - 2*this.scrollButtonWidth;
		this.scroll.style.width = ((h > 0) ? h : 0) + "px";

		this.scroll.innerHTML = '';
		this.scroll.onclick = HSA_handleScrollbarClick;
		this.scrollbar.appendChild(this.scroll);
		this.scroll.style.overflow = "hidden";

		this.scroll.className = "hscroll-line";

		//create slider
		this.scrollslider = document.createElement("DIV");
		this.scrollslider.index = this.index;
		this.scrollslider.style.position = "absolute";
		this.scrollslider.style.zIndex = 1000;
		this.scrollslider.style.textAlign = "center";
		this.scrollslider.innerHTML = '<div id="scrollslider' + this.index + '" style="padding:0;margin:0;"><div class="scroll-bar-left"></div><div class="scroll-bar-right"></div></div>';
		this.scrollbar.appendChild(this.scrollslider);

		this.subscrollslider = document.getElementById("scrollslider"+this.index);
		this.subscrollslider.style.width = Math.round((this.scrollContent.offsetWidth/this.scrollContent.scrollWidth)*(this.scrollbar.offsetWidth - 2*this.scrollButtonWidth)) + "px";

		this.scrollslider.className = "hscroll-slider";

		this.scrollWidth = this.scrollbar.offsetWidth - 2*this.scrollButtonWidth - this.scrollslider.offsetWidth;
		this.scrollFactor = (this.scrollContent.scrollWidth - this.scrollContent.offsetWidth)/this.scrollWidth;
		this.leftPosition = getRealLeft(this.scrollbar) + this.scrollButtonWidth;
		/* this.scrollbarWidth = this.scrollbar.offsetWidth - 2*this.scrollButtonWidth - this.scrollslider.offsetWidth; */

		this.scrollslider.style.left = /* 1 / this.scrollFactor * Math.abs(this.scrollContent.offsetTop) +*/ this.scrollButtonWidth + "px";
		this.scrollslider.style.height = "100%";
		this.scrollslider.onmousedown = HSA_handleSliderMouseDown;
		if (document.all)
			this.scrollslider.onmouseup = HSA_handleSliderMouseLeft;
	}
	else
		this.scrollContent.style.height = this.element.offsetHeight + "px";
}

function HSA_handleBtnLeftMouseRight()
{
	var sa = HSA_scrollAreas[this.index];
	sa.scrolling = true;
	sa.scrollLeft();
}

function HSA_handleBtnLeftMouseLeft()
{
	HSA_scrollAreas[this.index].scrolling = false;
}

function HSA_handleBtnLeftMouseOut()
{
	HSA_scrollAreas[this.index].scrolling = false;
}

function HSA_handleBtnRightMouseRight()
{
	var sa = HSA_scrollAreas[this.index];
	sa.scrolling = true;
	sa.scrollRight();
}

function HSA_handleBtnRightMouseLeft()
{
	HSA_scrollAreas[this.index].scrolling = false;
}

function HSA_handleBtnRightMouseOut()
{
	HSA_scrollAreas[this.index].scrolling = false;
}

function HSA_scrollIt()
{
	this.scrollContent.scrollLeft = this.scrollFactor * ((this.scrollslider.offsetLeft + this.scrollslider.offsetWidth/2) - this.scrollButtonWidth - this.scrollslider.offsetWidth/2);
}

function HSA_scrollLeft()
{
	if (this.scrollingLimit > 0)
	{
		this.scrollingLimit--;
		if (this.scrollingLimit == 0) this.scrolling = false;
	}
	if (!this.scrolling) return;
	if ( this.scrollContent.scrollLeft - this.scrollStep > 0)
	{
		this.scrollContent.scrollLeft -= this.scrollStep;
		this.scrollslider.style.left = 1 / this.scrollFactor * Math.abs(this.scrollContent.scrollLeft) + this.scrollButtonWidth + "px";
	}
	else
	{
		this.scrollContent.scrollLeft = "0";
		this.scrollslider.style.left = this.scrollButtonWidth + "px";
		return;
	}
	setTimeout("HSA_Ext_scrollLeft(" + this.index + ")", 30);
}

function HSA_Ext_scrollLeft(index)
{
	HSA_scrollAreas[index].scrollLeft();
}

function HSA_scrollRight()
{
	if (this.scrollingLimit > 0)
	{
		this.scrollingLimit--;
		if (this.scrollingLimit == 0) this.scrolling = false;
	}
	if (!this.scrolling) return;


	this.scrollContent.scrollLeft += this.scrollStep;
	this.scrollslider.style.left =  1 / this.scrollFactor * Math.abs(this.scrollContent.scrollLeft) + this.scrollButtonWidth + "px";

	if (this.scrollContent.scrollLeft >= (this.scrollContent.scrollWidth - this.scrollContent.offsetWidth))
	{
		this.scrollContent.scrollLeft = (this.scrollContent.scrollWidth - this.scrollContent.offsetWidth);
		this.scrollslider.style.left = this.scrollbar.offsetWidth - this.scrollButtonWidth - this.scrollslider.offsetWidth + "px";
		return;
	}

	setTimeout("HSA_Ext_scrollRight(" + this.index + ")", 30);
}

function HSA_Ext_scrollRight(index)
{
	HSA_scrollAreas[index].scrollRight();
}

function HSA_handleMouseMove(evt)
{
	var sa = HSA_scrollAreas[((document.all && !window.opera) ? this.index : document.documentElement.scrollAreaIndex)];
	var posy = 0;
	if (!evt) var evt = window.event;

	if (evt.pageX)
		posy = evt.pageX;
	else if (evt.clientX)
		posy = evt.clientX;

		if (document.all && !window.opera)
		{
			posy += document.documentElement.scrollLeft;
		}

	var iNewY = posy - sa.iOffsetX - sa.leftPosition;
		iNewY += sa.scrollButtonWidth;

	if (iNewY < sa.scrollButtonWidth)
		iNewY = sa.scrollButtonWidth;
	if (iNewY > (sa.scrollbar.offsetWidth - sa.scrollButtonWidth) - sa.scrollslider.offsetWidth)
		iNewY = (sa.scrollbar.offsetWidth - sa.scrollButtonWidth) - sa.scrollslider.offsetWidth;

	sa.scrollslider.style.left = iNewY + "px";

	sa.scrollIt();
}

function HSA_handleSliderMouseDown(evt)
{
	if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest))
	{
		document.onselectstart = function() { return false; }
		document.onmousedown = function() { return false; }
	}
	var sa = HSA_scrollAreas[this.index];
	if (document.all && !window.opera)
	{
		sa.scrollslider.setCapture()
		sa.iOffsetX = event.offsetX;
		sa.scrollslider.onmousemove = HSA_handleMouseMove;
	}
	else
	{
		if(window.opera)
		{
			sa.iOffsetX = event.offsetX;
		}
		else
		{
			sa.iOffsetX = evt.layerX;
		}
		document.documentElement.scrollAreaIndex = sa.index;
		document.documentElement.addEventListener("mousemove", HSA_handleMouseMove, true);
		document.documentElement.addEventListener("mouseup", HSA_handleSliderMouseLeft, true);
	}
}

function HSA_handleSliderMouseLeft()
{
	if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest))
	{
		document.onmousedown = null;
		document.onselectstart = null;
	}
	if (document.all && !window.opera)
	{
		var sa = HSA_scrollAreas[this.index];
		sa.scrollslider.onmousemove = null;
		sa.scrollslider.releaseCapture();
		sa.scrollIt();
	}
	else
	{
		var sa = HSA_scrollAreas[document.documentElement.scrollAreaIndex];
		document.documentElement.removeEventListener("mousemove", HSA_handleMouseMove, true);
		document.documentElement.removeEventListener("mouseup", HSA_handleSliderMouseLeft, true);
		sa.scrollIt();
	}
}

function HSA_handleResize()
{
	if (HSA_resizeTimer)
	{
		clearTimeout(HSA_resizeTimer);
		HSA_resizeTimer = 0;
	}
	HSA_resizeTimer = setTimeout("HSA_performResizeEvent()", 100);
}

function HSA_performResizeEvent()
{
	for (var i=0; i<HSA_scrollAreas.length; i++)
		HSA_scrollAreas[i].createScrollBar();
}

function HSA_handleMouseWheel(event)
{
	if (this.index != null) {
		var sa = HSA_scrollAreas[this.index];
		if (sa.scrollbar == null) return;
		sa.scrolling = true;
		sa.scrollingLimit = sa.wheelSensitivity;

		var delta = 0;
		if (!event) /* For IE. */
				event = window.event;
		if (event.wheelDelta) { /* IE/Opera. */
				delta = event.wheelDelta/120;

				/*if (window.opera)
						delta = -delta;*/
		} else if (event.detail) { /** Mozilla case. */
				delta = -event.detail/3;
		}
		if (delta && sa.element.over) {
				if (delta > 0)
					sa.scrollLeft();
				else
					sa.scrollRight();

				if (event.preventDefault)
						event.preventDefault();
				event.returnValue = false;
		}
	}
}

function HSA_handleSelectStart()
{
	event.returnValue = false;
}

function HSA_handleScrollbarClick(evt)
{
	var sa = HSA_scrollAreas[this.index];
	var offsetX = (document.all ? event.offsetX : evt.layerX);

	if (offsetX < (sa.scrollButtonWidth + sa.scrollslider.offsetWidth/2))
		sa.scrollslider.style.left = sa.scrollButtonWidth + "px";
	else if (offsetX > (sa.scrollbar.offsetWidth - sa.scrollButtonWidth - sa.scrollslider.offsetWidth))
		sa.scrollslider.style.left = sa.scrollbar.offsetWidth - sa.scrollButtonWidth - sa.scrollslider.offsetWidth + "px";
	else
	{
		sa.scrollslider.style.left = offsetX + sa.scrollButtonWidth - sa.scrollslider.offsetWidth/2 + "px";
	}
	sa.scrollIt();
}

function HSA_handleOnScroll()
{
	event.srcElement.doScroll("pageLeft");
}

//--- common functions ----

function HSA_getElements(attrValue, tagName, ownerNode, attrName) //get Elements By Attribute Name
{
	if (!tagName) tagName = "*";
	if (!ownerNode) ownerNode = document;
	if (!attrName) attrName = "name";
	var result = [];
	var nl = ownerNode.getElementsByTagName(tagName);
	for (var i=0; i<nl.length; i++)
	{
	//	if (nl.item(i).getAttribute(attrName) == attrValue)
//		result.push(nl.item(i));
		if (nl.item(i).className.indexOf(attrValue) != -1)
		result.push(nl.item(i));
	}
	return result;
}

function getRealLeft(elem)
{
	var nLeft = 0;
	if(elem)
	{
		do
		{
			nLeft += elem.offsetLeft - elem.scrollLeft;
			elem = elem.offsetParent;
		}
		while(elem)
	}
	return nLeft;
}

// slider init
function initSlider() {
	var _activeClass = 'active';
	var _duration = 550;

	$$("div#carusel").each(function(_el, i){
		var _item = _el;
		var _btnPrev = _item.getElement("a.link-prev");
		var _btnNext = _item.getElement("a.link-next");
		var _holder = _item.getElement("div.holder");
		var _slider = _holder.getElement("ul.gallery-list");
		var _slides = _slider.getElements("li.slide");
		var _pager = _item.getElements("div.swicher ul a");
		var _slideCount = _slides.length;
		var _elWidth = _slides[0].getSize().x;
		var _sumWidth = _elWidth * _slideCount;
		var _currentStep = 0;
		var _maxStep = Math.abs(_holder.getSize().x - _sumWidth)/_elWidth;

		// gallery control
		_btnPrev.addEvent('click', function(){
			prevSlide();
			return false;
		});
		_btnNext.addEvent('click', function(){
			nextSlide();
			return false;
		});
		_pager.each(function(_el, i){
			_el.addEvent('click', function(){
				_currentStep = i;
				switchSlide();
				return false;
			});
		});

		// gallery animation
		function prevSlide() {
			if(_currentStep > 0) _currentStep--;
			else _currentStep = _slideCount-1;
			switchSlide();
		}
		function nextSlide() {
			if(_currentStep < _slideCount-1) _currentStep++;
			else _currentStep=0;
			switchSlide();
		}
		function switchSlide() {
			var offset;
			var myFxSlide = new Fx.Morph(_slider, {duration: _duration});

			_pager.removeClass(_activeClass)[_currentStep].addClass(_activeClass);
			offset = -_currentStep*_elWidth;
			myFxSlide.start({'marginLeft':offset});
		}
		switchSlide();
	});
}

function validateEmail(email) {
	var at = email.lastIndexOf("@");

	// Make sure the at (@) sybmol exists and  
	// it is not the first or last character
	if (at < 1 || (at + 1) === email.length)
		return false;

	// Make sure there aren't multiple periods together
	if (/(\.{2,})/.test(email))
		return false;

	// Break up the local and domain portions
	var local = email.substring(0, at);
	var domain = email.substring(at + 1);

	// Check lengths
	if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
		return false;

	// Make sure local and domain don't start with or end with a period
	if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
		return false;

	// Check for quoted-string addresses
	// Since almost anything is allowed in a quoted-string address,
	// we're just going to let them go through
	if (!/^"(.+)"$/.test(local)) {
		// It's a dot-string address...check for valid characters
		if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
			return false;
	}

	// Make sure domain contains only valid characters and at least one period
	if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
		return false;	

	return true;
}

function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 46 || charCode > 57))
	  return false;
  
   return true;
}

/*
function switchNewsPage(newsID){
	$.ajax({
	  type: "POST",
	  url: 'opened-news.html',
	  cache: false,
	  success: function(html){
		if(html){
			$('body').html(html);
			showNews(newsID);
		}
	  },
	  error: function(){
		  alert('Please retry');
	  }
	});
				  
}
*/

function showNews(newsID){
	param = 'news_id=' + newsID;
			
	//show loading 
	$('.full-post').html('<br/><br/>');
	$('.full-post').addClass('loading');
	
	$.ajax({
	  type: "POST",
	  url: 'requests/news.php',
	  cache: false,
	  data: param,
	  success: function(html){
		if(html){
			$('.full-post').removeClass('loading');
			$('.full-post').html(html);
		}
	  },
	  error: function(){
		  alert('Please retry');
	  }
	});
				  
}
$(document).ready(function(){
						   
	//selected works current
	if($('#selected-work').length > 0){
    	var url = document.location.toString();
		var tab = url.split('#');
		if(tab[1]){
			$('ul.tabset li a').removeClass('active');
			$('#main div.tab-content').hide();
			$('a[href="#'+tab[1]+'"]').addClass('active');
			$('#'+tab[1]).show();
		}
	}
	
	//contact page form
	if($('#contact-form').length > 0){
	  $('#contact-form').submit(function(){
			  var error = false;
			  $('#contact-form input[type="text"]').removeClass("error");
			  $('#contact-form textarea').removeClass("error");
			  
			  //form validation
			  if(!$("#name").val()){
				  error = true;
				  $("#name").addClass("error");
			  }
			  if(!validateEmail($("#email").val())){
				  error = true;
				  $("#email").addClass("error");
			  }
			  if(!$("#phone").val()){
				  error = true;
				  $("#phone").addClass("error");
			  }
			  if(!$("#message").val()){
				  error = true;
				  $("#message").addClass("error");
			  }			
			  if(!error){
				  param = 'name='      + $("#name").val() +
						  '&email='    + $("#email").val() +
						  '&phone='    + $("#phone").val() +
						  '&message='  + $("#message").val();
						  
				  //show loading 
				  $('.btn .loading-dark').show();
				  
				  $.ajax({
					type: "POST",
					url: 'requests/contact.php',
					cache: false,
					data: param,
					success: function(html){
					  if(parseInt(html) == 1){
						  $('.btn').html('<div id="thank-you">Thank you!</div>');
						  $('#contact-form input').val('');
						  $('#contact-form textarea').val('');
						  
		 				  //hide loading 
						  $('.btn .loading-dark').hide();
					  }
					},
					error: function(){
						alert('Please retry');
					}
				  });
				  
			  }
			  //
	  return false;
	  });
	}
	
	//newsletter sign in
	if($('#newsletter-sign').length > 0){
	  $('#email').focus(function(){
						 $(this).val('');
						});
	  
	  $('#newsletter-sign').submit(function(){
			  var error = false;
			  $('#newsletter-sign input[type="text"]').removeClass("error");
			  $('#newsletter-sign .error-container').removeClass('ok');
			  
			  //form validation
			  if(!validateEmail($("#email").val())){
				  error = true;
				  $("#email").addClass("error");
				  $('#newsletter-sign .error-container').html('Your email address is invalid!');
				  $('#newsletter-sign .error-container').show();
			  }
			  if(!error){
				  param = 'email='+ $("#email").val();
						  
				  //show loading 
				  $('.sign .loading-light').show();
				  
				  $.ajax({
					type: "POST",
					url: 'requests/newsletter.php',
					cache: false,
					data: param,
					success: function(html){
					  if(parseInt(html) == 1){
						  $('#newsletter-sign .error-container').html('Thank you for subscribing!');
						  $('#newsletter-sign .error-container').addClass('ok');
						  $('#newsletter-sign .error-container').show();
						  $("#email").val('');
						  
		 				  //hide loading 
						  $('.sign .loading-light').hide();
					  }
					},
					error: function(){
						alert('Please retry');
					}
				  });
				  
			  }
			  //
	  return false;
	  });
	}
});