// GENERAL CORE FUNCTIONS
$A = function(arr)
{
    var returnArr = [];
    for (var i=0,len=arr.length; i<len ; i++)
        returnArr.push(arr[i]);
    return returnArr;
}

Function.prototype.bind = function()
{
    var args = $A(arguments);
    var _scope = args.shift();
    var _obj = this;
    return function()
    {
        return _obj.apply(_scope, args.concat($A(arguments)));
    }
}

Function.prototype.bindAsEventListener = function()
{
	var _this = this;
	var args = $A(arguments);
	var _scope = args.shift();
	return function(event) {
		_this.apply(_scope, [( event || window.event)].concat(args).concat($A(arguments)));
	}
}

function $(id)
{
	return document.getElementById(id);
}

function observe(obj, eventName, callbackFunction, useCapture)
{
	if (obj.attachEvent)
	{
		obj.attachEvent("on" + eventName, callbackFunction);
	}
	else
	{
		obj.addEventListener(eventName, callbackFunction, useCapture);
	}
}

function getRunTimeValue(element, attributeName, doc) 
{ 
   doc = (typeof(doc) == "undefined") ? document:doc;
   if(doc.defaultView && doc.defaultView.getComputedStyle && doc.defaultView.getComputedStyle(element,null)) 
   {
		return doc.defaultView.getComputedStyle(element,null)[attributeName]; 
   }
   else if(typeof(doc.all)!="undefined" && element.currentStyle) 
   { 
		return element.currentStyle[attributeName]; 
   } 
   else if (element.style)
		return element.style[attributeName];
   else
		return 0; 
}


Element = {};
Element.removeClassName = function(element, classname)
{
	element.className = element.className.replace(new RegExp("\\s*(" + classname + ")","gi"),"");
}
Element.addClassName = function(element, classname)
{
	Element.removeClassName(element, classname);
	element.className += " " + classname;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////
///		SLIDER CLASS
///
///		containerId - type of String = the container that contains all the various slides
///
///		interval - type of Integer = time between slide movement (in millisecond 1000 = 1 sec)
///
///		autostart - type of Boolean = automatically start slide show - if not passed is false
///
///		addStartButton - type of Boolean - tells the slider to add start/stop button.
///										 is set to true automatically if user chose not to autostart
///
//////////////////////////////////////////////////////////////////////////////////////////////////////////
var Slider = function(options)
{
	var S = {
		containerId: options.containerId,
		delay: options.delay,
		loop: options.loop || false,
		pauseOnMouseOver: options.pauseOnMouseOver || false,
		containerHeight: 0,
		containerWidth: 0,
		numberOfSliders: 0,
		pageNumber: 1,
		isPlaying: options.autoPlay || false,
		addNavigation: options.addNavigation || false,
		addStartButton: options.addStartButton || false,
		startText: options.startText || "Start",
		endText: options.endText || "Stop",
		
		start: function()
		{
			var container = this.getSliderContainer();
			if (container)
			{
				this.containerWidth = parseInt(getRunTimeValue(container, "width"));
				var children = container.getElementsByTagName("li");
				if (children && children.length)
				{
					var moveContainer = container.getElementsByTagName("ul")[0];
					if (moveContainer)
					{
						this.numberOfSliders = children.length;
						if (this.numberOfSliders)
						{
						    if (this.pauseOnMouseOver)
						    {
						        observe(container, "mouseover", this.mouseOver.bind(this), false);
						        observe(container, "mouseout", this.mouseOut.bind(this), false);
						    }
							moveContainer.style.width = (this.numberOfSliders * this.containerWidth) + "px";
							// Reset position FF fix on refresh
							container.scrollLeft = 0;
							this.prepareMove();
						}
					}
				}
			}
			
			this.buildNavigation();
		},
		
		getSliderContainer: function()
		{
			return $(this.containerId);
		},
		
		getStopStartButtonId: function()
		{
			return this.containerId + "_stop-start-btn";
		},
		
		getStopStartButton: function()
		{
			return $(this.getStopStartButtonId());
		},
		
		gotoPage: function(pageNumber)
		{
		    clearTimeout(this.moveTimeout);
		    this.isPlaying = false;
		    this.pageNumber = pageNumber;
		    this.moveSlider();
		    this.showCurrentPageIndicator();
			if (options.onNavigationClick)
				options.onNavigationClick(this.pageNumber);
		},
		
		buildNavigation: function()
		{
			if (this.numberOfSliders > 1)
			{
				var container = this.getSliderContainer();
				if (container)
				{
				    var navigationDiv = document.createElement("div");
				    navigationDiv.id = this.containerId + "_nav";
					navigationDiv.className = "slide-navigation";
					
					var pageNavigationDiv = document.createElement("div");
					pageNavigationDiv.className = "pages";
					for (var i=1, len=this.numberOfSliders ; i<=len ; i++)
					{
					    var pageHref = document.createElement("a");
					    pageHref.href = "javascript:;";
					    pageHref.id = this.containerId + "_p" + i;
					    pageHref.innerHTML = i;
					    if (this.pageNumber == i)
					        pageHref.className = "current";
					    pageHref.onclick = this.gotoPage.bind(this, String(i));
					    pageNavigationDiv.appendChild(pageHref);
					}
					navigationDiv.appendChild(pageNavigationDiv);
					
					// If user has decided not to auto start the slider we need to add stop/play button
        			// even if the user didn't want it to be added
			        if (!this.isPlaying || this.addStartButton)
			        {
					    var playStopContainer = document.createElement("div");
					    playStopContainer.className = "btns";
					    var stopStartBtn = document.createElement("a");
					    stopStartBtn.href = "javascript:;";
					    stopStartBtn.id = this.getStopStartButtonId();
					    stopStartBtn.onclick = this.toggleStopStart.bind(this);
					    
					    playStopContainer.appendChild(stopStartBtn);
					    navigationDiv.appendChild(playStopContainer);
					}
					
					var insertPosition = container.nextSibling;
				    if (insertPosition)
					    container.parentNode.insertBefore(navigationDiv, insertPosition);
					else
					    container.parentNode.appendChild(navigationDiv);
					
					this.updateStopStartButtonStyle();
				}
			}
		},
		
		showCurrentPageIndicator: function()
		{
		    var ahref;
		    for (var i=1, len=this.numberOfSliders ; i<=len ; i++)
		    {
		        ahref = $(this.containerId + "_p" + i);
		        if (ahref)
		        {
		            if (this.pageNumber == i)
		                ahref.className = "current";
		            else
		                ahref.className = "";
		        }
		    }
		},
		
		toggleStopStart: function()
		{
			this.isPlaying = !this.isPlaying;
			if (this.isPlaying && !this.loop && this.pageNumber >= this.numberOfSliders)
			    this.pageNumber = 0;
			this.updateStopStartButtonStyle();
			this.prepareMove();
		},
		
		updateStopStartButtonStyle: function()
		{
			var stopStartBtn = this.getStopStartButton();
			this.isPlaying = this.isPlaying && ((this.pageNumber < this.numberOfSliders) || this.loop);
			if (stopStartBtn)
			{
				if (this.isPlaying)
				{
					stopStartBtn.className = "";
					stopStartBtn.innerHTML = this.endText;
				}
				else
				{
					stopStartBtn.className = "current";
					stopStartBtn.innerHTML = this.startText;
				}
			}
		},
		
		mouseOver: function()
		{
		    this.isPaused = true;
		    clearTimeout(this.moveTimeout);
		},
		
		mouseOut: function()
		{
		    this.isPaused = false;
		    this.prepareMove();
		},
		
		prepareMove: function()
		{
		    clearTimeout(this.moveTimeout);
			if (this.isPlaying && !this.isPaused)
			    this.moveTimeout = setTimeout(this.nextSlide.bind(this), this.delay);
		},
		
		nextSlide: function()
		{
		    this.pageNumber++;
		    if (this.pageNumber > this.numberOfSliders)
		    {
		        if (this.loop)
		            this.pageNumber = 1;
		        else
		            return;
		    }
		    
		    this.moveSlider();
		},
		
		moveSlider: function()
		{
		    clearInterval(this.transitionInterval);
		    
		    this.newLeft = (this.pageNumber-1) * this.containerWidth;
		    this.transitionInterval = setInterval(this.moveTo.bind(this), 50);
		},
		
		moveTo: function()
		{
		    var moveContainer = this.getSliderContainer();
		    if (moveContainer)
		    {
		        var currentLeft = moveContainer.scrollLeft;
		        var difference = (this.newLeft - currentLeft);
		        var rate = parseInt(difference/6.4);
		        // Fix because of DOM inability to apply float values to styles
		        if (rate==0)
		        {
		            if (difference < 0)
		                rate--;
		            else
		                rate++;
		        }
		        moveContainer.scrollLeft = currentLeft + rate;
		        if (difference==0)
		        {
		            moveContainer.scrollLeft = this.newLeft;
		            clearInterval(this.transitionInterval);
		            this.prepareMove();
		            this.showCurrentPageIndicator();
		            this.updateStopStartButtonStyle();
		            if (options.onPageChange)
		                options.onPageChange(this.pageNumber);
		        }
		    }
		}
		
	};
	
	return S;
}


function startSlider()
{
	var slider = new Slider(
	    {   containerId: "slider",
	        delay: 5000,
	        autoPlay: true,
	        buildNavigation: true,
	        loop: false,
	        pauseOnMouseOver: true,
	        addStartButton: true,
	        startText: "Start",
            stopText: "Stop",
	        onPageChange: window.onPageChange,
			onNavigationClick: window.initQuotes
	    }
	);
	slider.start();
}

observe(window, "load", startSlider, false);




//////////////////////////////////////////////////////////////////////////////////////////////////////////
///
///		START Quotes
///
//////////////////////////////////////////////////////////////////////////////////////////////////////////

var g_slides;
var g_index = -1;
var intervalBetweenSlides = 5000;
var speed = 8; // milliseconds
var timeToFirstSlide = 3000;
var useRandom = false;

    function fade(outId, inId, opacityValue)
    {
        opacityValue = opacityValue || 0;
        var inSlide = $(inId);
        var outSlide = $(outId);

        if (inSlide)
        {
            inSlide.style.opacity = parseInt((opacityValue / 10)*100)/100;
            inSlide.style.filter = 'alpha(opacity=' + parseInt(opacityValue * 10) + ')';
        }

        if (outSlide)
        {
            outSlide.style.opacity = 1 - parseInt((opacityValue / 10)*100)/100;
            outSlide.style.filter = 'alpha(opacity=' + parseInt(100 - (opacityValue * 10)) + ')';
        }

        if (opacityValue >= 10)
        {
            if (outSlide)
							Element.removeClassName(outSlide, "show");
            window.setTimeout('rotateSlides()', intervalBetweenSlides);
        }
        else
            window.setTimeout('fade("' + outId + '","' + inId + '",' + (opacityValue + 0.1) + ')', speed);
    }
    
	function beforeFade(outId, inId)
	{
		var inSlide = $(inId);
		if (inSlide)
			Element.addClassName(inSlide, "show");

	  fade(outId, inId);
	}
	
	function afterFade(inSlide, outSlide)
	{
			if (outSlide)
				Element.removeClassName(outSlide, "show");
	}
		
    function randomSlides(storage, slides)
    {
        if (storage.length > 1)
        {
            var current = Math.floor ( Math.random ( ) * ( storage.length ) );
            slides.push(storage[current]);
            storage.splice(current,1);
            return randomSlides(storage, slides);
        }
        else
            slides.push(storage[0]);
						
            
        return slides;
    }
    
    function rotateSlides(slides)
    {
        if(slides)
		{
            g_slides = slides;
			g_index = 0;
        }
        var thisSlide = g_slides[g_index];
        var nextSlide = g_slides[g_index+1];
        if (!nextSlide)
        {
            nextSlide = g_slides[0];
            g_index = -1;
        }
				
        beforeFade(thisSlide, nextSlide);

        g_index++;
    }

var wasQuotesInited = false;
function initQuotes()
{
	if (!wasQuotesInited)
	{
		wasQuotesInited = true;
		var slidesContainer = $('quotes');
		
		if (slidesContainer)
		{
			var children = slidesContainer.getElementsByTagName('li');
			var slides = [];
			
			for (var i = 0, len = children.length; i < len; i++)
			{
				children[i].id = children[i].id || "slide_" + i;
					slides[i] = children[i].id;
			}
			
			window.setTimeout(function(){ rotateSlides(slides)}, timeToFirstSlide);
		}
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////
///
///		TABSET
///
//////////////////////////////////////////////////////////////////////////////////////////////////////////
var TabSet = function()
{
	var _super = {
		
		init: function(id)
		{
			this.id = id;
			this.attachEvents();
			this.showTab(null, 0);
		},
		
		getDirectChildren: function(container, tagName)
		{
			tagName = tagName.toUpperCase();
			var items = [];
			var child = container.firstChild;
			do
			{
				if (child.tagName == tagName)
					items.push(child);
				child = child.nextSibling;
			}
			while (child)

			return items;
		},
		
		attachEvents: function()
		{
			var container = $(this.id);
			var btnsAndContent =  this.getDirectChildren(container, "div");
			var tab_buttons_container = btnsAndContent[0];
			var tab_content_container = btnsAndContent[1];
			if (tab_buttons_container && tab_content_container)
			{
				tab_buttons_container.id = this.id + "_buttons";
				tab_content_container.id = this.id + "_content";
				var tab_buttons = tab_buttons_container.getElementsByTagName("a");
				var tab_content = this.getDirectChildren(tab_content_container, "div");
				if (tab_buttons.length == tab_content.length && tab_content.length > 0)
				{
					var btn;
					for (var i=0,len=tab_buttons.length ; i<len ; i++)
					{
						btn = tab_buttons[i];
						tab_content[i].id = this.id + "_tab_" + i;
						btn.id = this.id + "_btn_" + i;
						btn.onclick = this.showTab.bindAsEventListener(this, String(i));
						
					}
				}
			}
		},
		
		showTab: function(evt, tab_i)
		{
			evt = evt || window.event;
			var tab_content_container = $(this.id + "_content");
			var tab_buttons_container = $(this.id + "_buttons");
			var tab_content = this.getDirectChildren(tab_content_container, "div");
			var tab_buttons = tab_buttons_container.getElementsByTagName("a");
			for (var i=0,len=tab_content.length ; i<len ; i++)
			{
				tab_content[i].style.zIndex = 0;
				tab_buttons[i].className = "";
			}
			var tabToShow = $(this.id + "_tab_" + tab_i);
			if (tabToShow)
				tabToShow.style.zIndex = 1;
			var btn = $(this.id + "_btn_" + tab_i);
			if (btn)
			    btn.className = "selected";
			
			if (evt)
			{
			    if (evt.preventDefault) 
			    {
                    evt.preventDefault();
                    evt.stopPropagation();
                } 
                else 
                {
                  evt.returnValue = false;
                  evt.cancelBubble = true;
                }
			}
			return false;
		}		
	};
	
	_super.init.apply(_super, arguments);
	
	return _super;
}

observe(window, "load", initQuotes, false);