// JavaScript Document
/**
 * @author 		Matthew Foster
 * @date		June 6th 2007
 * @purpose		To have a base class to extend subclasses from to inherit event dispatching functionality.
 * @procedure	Use a hash of event "types" that will contain an array of functions to execute.  The logic is if any function explicitally returns false the chain will halt execution.
 */
 var EventDispatcher = Class.create({});
	
	
	Object.extend(EventDispatcher.prototype,
					{
						
						buildListenerChain : function(){
							
							if(!this.listenerChain)
								this.listenerChain = {};							
						
						},
						addEventListener : function(type, listener){
							
							this.buildListenerChain();
							
							if(!this.listenerChain[type])					
								this.listenerChain[type] = [listener];
							else
								this.listenerChain[type].push(listener);
							
						},
						hasEventListener : function(type){
							
							return (typeof this.listenerChain[type] != "undefined");
						
						},
						removeEventListener : function(type, listener){
							if(!this.hasEventListener(type))
								return false;
								
							for(var i = 0; i < this.listenerChain[type].length; i++)
								if(this.listenerChain[type][i] == listener)
									this.listenerChain[type].splice(i, 1);
						
						},
						dispatchEvent : function(type, args){
							this.buildListenerChain();
							
							if(!this.hasEventListener(type))
								return false;
								
							this.listenerChain[type].any(function(f){ return (f(args) == false ? true : false); });						
						},
						on : function(type, listener){
							this.addEventListener(type, listener);
						},
						fire : function(type, args){
							this.dispatchEvent(type, args);
						}
					}
					
				);


/**

Copyright (c) 2007 Matthew E. Foster

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/

var FishEyeToolBar = Class.create();

Object.extend(Object.extend(FishEyeToolBar.prototype, EventDispatcher.prototype),
				{
					
					initialize : function(ele, options){
						
						this.elementArr = [];
												
						this.options =  {selector : "img",
										 createSub : this.createSub.bind(this),
										 subOptions : {}};
						
						Object.extend(this.options, options);
						
						this.createListener();
						this.buildInterface(ele);
						this.attachListener();
						this.resetTimer = false;				
					
					},
					createSub : function(ele){
						
						return new FishEyeItem(ele, this.options.subOptions);
					
					},
					buildInterface : function(ele){
						this.container = $(ele);
						 
						this.container.getElementsBySelector(this.options.selector).collect(this.buildItem.bind(this));
					
					},
					buildItem : function(ele){
						
						var obj = this.options.createSub(ele, this.options.subOptions);
						
						obj.addEventListener("click", this.itemClickHandle);
						
						this.elementArr.push(obj);
						
						this.dispatchEvent("itemBuild", obj);												
					
					},
					createListener : function(e){
						
						this.mouseMoveHandle = this.handleMouseMove.bindAsEventListener(this);
						this.itemClickHandle = this.handleItemClick.bind(this);
						this.mouseOutHandle = this.handleMouseOut.bindAsEventListener(this);
						this.cancelTimerHandle = this.cancelTimer.bindAsEventListener(this);
					},
					attachListener : function(){
						
						Event.observe(this.container, "mousemove", this.mouseMoveHandle);
						Event.observe(this.container, "mouseout", this.mouseOutHandle);
						Event.observe(this.container, "mouseover", this.cancelTimerHandle);
											
					},
					cancelTimer : function(){
						
						clearTimeout(this.resetTimer);
						
					},
					handleMouseMove : function(e){
						
						this.cancelTimer();
						
						this.elementArr.invoke("handleFishEye", { x : Event.pointerX(e), y : Event.pointerY(e) });
					
					},
					handleMouseOut : function(e){
					
						this.resetTimer = setTimeout(this.resetElements.bind(this), 1);						
						
					},
					
					resetElements : function(){
					
						this.elementArr.invoke('resetElement');
					
					},
					handleItemClick : function(e){
						
						this.dispatchEvent("itemClick", e);
					
					},
					elements : function(){
						
						return this.elementArr;
						
					}	
				}
			);
	
	
var FishEyeItem = Class.create();


Object.extend(Object.extend(FishEyeItem.prototype, EventDispatcher.prototype),
				{	
					initialize : function(ele, options){
						
						this.options = {
											scaleFactor : 0.5,
											scaleThrottle : 120
										}
										
						Object.extend(this.options, options || {});
						
						
						this.buildInterface(ele);
						this.createListener();
						this.attachListener();
						
						this.setOriginalProperties();
						
						
						this.lastScale = 1;
						
					},
					setOriginalProperties : function(){
						
						this.originalHeight =parseInt(this.ele.getStyle("height").replace(/[^0-9]/gi, ""));
					
						this.originalWidth =parseInt(this.ele.getStyle("width").replace(/[^0-9]/gi, "")); 
						
						this.originalMarginTop= parseInt(this.ele.getStyle("margin-top").replace(/[^0-9]/gi, ""));
						
					},
					buildInterface : function(ele){
						
						this.ele = $(ele);
																									
					},
					createListener : function(e){
					
						this.fishEyeHandle = this.handleFishEye.bind(this);
						this.clickHandle = this.handleClick.bindAsEventListener(this);
						this.cancelMouseOutHandle = this.handleMouseOut.bindAsEventListener(this);
					
					},
					attachListener : function(){
						
						Event.observe(this.ele, "click", this.clickHandle);
						Event.observe(this.ele, "click", this.cancelMouseOutHandle);	
						
					},
					handleMouseOut : function(e){
						
						Event.stop(e);
						return false;
						
					},
					handleClick : function(e){
						
						this.dispatchEvent("click", e);
					
					},						
					handleFishEye : function(p){
						
						var offset = this.getCenterAxis();
						var distance = Math.abs(p.x - offset);
						
						if(distance > this.options.scaleThrottle){
							this.resetElement();
							return true;
						}
						
						var scale = Math.abs(this.options.scaleThrottle - distance) / this.options.scaleThrottle + 1;
						this.lastScale = scale;
						
						this.scaleElement(scale);
												
					},
					scaleElement : function(scale){
						
						this.ele.setStyle({ zIndex : 2, marginTop : this.originalMarginTop - ((scale * this.originalHeight) - this.originalHeight) + "px",   height : (scale * this.originalHeight) + "px", width : (scale * this.originalWidth) + "px"});													
												
					},
					resetElement : function(){
					
						this.ele.setStyle({ zIndex : 1, marginTop :  this.originalMarginTop + "px",  height : this.originalHeight  + "px", width : this.originalWidth + "px" });
					
					},
					getCenterAxis : function(){
						
						return Math.floor(Position.cumulativeOffset(this.ele).first() + (((this.originalWidth/2)) * this.lastScale));
					
					}		
				}
			);

var FishEyeItemDown = Class.create();

Object.extend(Object.extend(FishEyeItemDown.prototype, FishEyeItem.prototype),
				{
					
					setOriginalProperties : function(){
						
						this.originalHeight =parseInt(this.ele.getStyle("height").replace(/[^0-9]/gi, ""));
					
						this.originalWidth =parseInt(this.ele.getStyle("width").replace(/[^0-9]/gi, "")); 
						
						this.originalMarginBottom = parseInt(this.ele.getStyle("margin-bottom").replace(/[^0-9]/gi, ""));
												
												
					},
					scaleElement : function(scale){
						
						this.ele.setStyle({ zIndex : scale * 100, marginBottom : this.originalMarginBottom - ((scale * this.originalHeight) - this.originalHeight) + "px",   height : (scale * this.originalHeight) + "px", width : (scale * this.originalWidth) + "px"});													
												
					},
					resetElement : function(){
					
						this.ele.setStyle({ zIndex : 1, marginBottom :  this.originalMarginBottom + "px",  height : this.originalHeight  + "px", width : this.originalWidth + "px" });
					
					}
					
					
					
				}
			);


/*=============================== END OF EYE FISH ====================================*/


var seasonSpeed = 4;

function showSeasonChooser() {
	
	var seasonChooser = document.getElementById('seasonChooser');
	if(seasonChooser.style.marginTop == '') {
			seasonChooser.style.marginTop = "-140px";
	}
	if(seasonChooser.style.marginTop == '-140px') {
		seasonChooserIn();	
	}
	else {
		seasonChooserOut();
	}
}
function seasonChooserIn() {
		var seasonChooser = document.getElementById('seasonChooser');
		var Margin = new Array();
		Margin = seasonChooser.style.marginTop.split('px');
		var curMargin = Number(Margin[0]);
		
		if(curMargin<0) {
			seasonChooser.style.marginTop = curMargin+seasonSpeed+"px";
			setTimeout('seasonChooserIn()',1);
		} else {
			seasonChooser.style.marginTop = 0 + "px";
		}
}
function seasonChooserOut() {
		var seasonChooser = document.getElementById('seasonChooser');
		var Margin = new Array();
		Margin = seasonChooser.style.marginTop.split('px');
		var curMargin = Number(Margin[0]);
		
		if(curMargin>=-140) {
			seasonChooser.style.marginTop = curMargin-seasonSpeed+"px";
			setTimeout('seasonChooserOut()',1);
		} else {
			seasonChooser.style.marginTop = -140 + "px";
		}
}



var testimonial = 0;
//================================settings ================================
		var testimonialWidth = 240;
		var testimonialSpeed = 10;
		var testimonialSpeedReset = 30;
//================================functions ================================
function showNext() {
		

		var divs = $('allTestimonials').getElementsByClassName('aTestimonial');
		var testimonialsCount = divs.length;
		var holder = $('testimonialsHolder');
		
		testimonial++;
		
		if(testimonial>=testimonialsCount) { //ako izvikash funciqta pove4e puti ot broq testimoniali - rezetvai
					/*for(var x=0;x<testimonialsCount;x++) {
						divs[x].style.left = "0px";
					}	*/
					testimonial = 0;
					resetTestimonials();
					
		}
		else {	//ina4e - varshi si rabotata
					
						if(holder.style.left == '') {
							holder.style.left = "0px";
						}
						
						var theLeft = holder.style.left.split("px");
						var curLeft = Number(theLeft[0]); //curLeft darji momentnata stoinost na Left kato 4islo
						
						if(curLeft > -1*(testimonial*testimonialWidth)) {
							curLeft = curLeft - testimonialSpeed;
							holder.style.left = curLeft + "px";
							testimonial--;
							setTimeout('showNext()',1);
						}
						else {
							holder.style.left = -1*(testimonial*testimonialWidth) + "px";
						}
							
					
		}

}
function resetTestimonials() {
		
		var holder = $('testimonialsHolder');
					
						var theLeft = holder.style.left.split("px");
						var curLeft = Number(theLeft[0]); //curLeft darji momentnata stoinost na Left kato 4islo
						
						if(curLeft < 0) {
							//curLeft = curLeft + testimonialSpeedReset;
							holder.style.left = curLeft + testimonialSpeedReset + "px";
							setTimeout('resetTestimonials()',1);
						}
						else {
							holder.style.left = "0px";
						}
					
}
/*=============== CHANGE SEASON ON CLICK ==================*/

function changeSeason(season) {

	var domain = "http://"+document.domain;
	if (season == "summer") season = "Summer";
	if (season == "autumn") season = "Autumn";
	if (season == "spring") season = "Spring";
	if (season == "winter") season = "Winter";
	
			if(document.createStyleSheet) {
				document.createStyleSheet(domain+'/css/style'+season+'.css');
				Set_Cookie("season", season);
			}
			
			else {
			
			var styles = "@import url('"+domain+"/css/style"+season+".css');";
			
			var newSS=document.createElement('link');
			
			newSS.rel='stylesheet';
			
			newSS.href='data:text/css,'+escape(styles);
			
			document.getElementsByTagName("head")[0].appendChild(newSS);
			Set_Cookie("season", season);
			}
}

/*=============== CHANGE SEASON ON LOAD (IF COOKIE) ==================*/
window.onload = function () {
	if(Get_Cookie("season")) {
			var season = Get_Cookie("season");
			changeSeason(season);
	}
	else {
		//alert("you dont have a cookie?");
	}
}



/*=============== COOKIES ==================*/
/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.1
Last Update: 4 October 2007

Changes:
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks

1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
