/*
	
	Classes:
	
	- DependentDropdown
	- ResetButton
	- LocationMap
	- LocationInfoOverlay
	- CountryMapTooltip ( About Us Country-Map, yellow tooltips )
	- GalleryLightbox (just helpers)
	- PageFooter
	- HomepageSlider (Flash Alternative)
	- Image Slider
*/

var DependentDropdown = Class.create( {

	initialize: function( select ){
		
		this.element = $(select);
		this.master = $$('select[name=' + this.element.readAttribute('title') + ']')[0] || null;
		this.element.writeAttribute('title', null);
		this.optionElements = [];
		this.element.indexDefaultValue = this.element.selectedIndex
		
		if( !this.master ) return;
		
		this.element.select('option[title!=""]').each( function( option ){
			this.optionElements.push( $(option) );
		}.bind( this ) );
		
		this.master.observe( 'change', this.masterHasChanged.bind( this ));
		this.masterHasChanged();
	},

	masterHasChanged: function( e ){
		
		var val = this.master.getValue(); 
		var enable = false;
		
		while( this.element.options.length > 1 )
			this.element.remove( 1 );
		
		for( var i = 0; i < this.optionElements.length; i++ ){
			
			var opt = this.optionElements[i];
			
			if( opt.readAttribute('title') != null ){
				opt.relValue = opt.readAttribute('title')
				//opt.writeAttribute('title', null)
			}
			
			if( opt.relValue == val || opt.relValue.indexOf( val ) != -1 || val == "" ){
				try{
					this.element.add( opt, null );
					enable = true;
				}catch( err ) {
					this.element.add( opt ); // IE only
					enable = true;
				}
			}
		}
		
		if( !enable )
			this.element.setStyle({display:"none"});
		else
			this.element.setStyle({display:"block"});
		
		if( e ){
			this.element.selectedIndex = 0;	// reset, if changed by user
		}
		else{
			this.element.selectedIndex = this.element.indexDefaultValue;
		}
	}
} );


var LocationMap = Class.create({
	
	initialize: function( canvas ){
		
		if( !GBrowserIsCompatible() ) return;
		
		// Create map instance
		
		this.map = new GMap2( canvas );
		
		// Configure map interactions and controls
		
		this.map.enableContinuousZoom();
		this.map.enableScrollWheelZoom();
		this.map.addMapType( G_PHYSICAL_MAP );
		this.map.setMapType( G_SATELLITE_MAP );
		this.map.addControl( new GMapTypeControl());
		this.map.addControl( new GLargeMapControl3D() );
		
		// Custom properties
		
		this.map.dimensions = this.map.getSize();
		this.map.active = null;
		this.map.panToPoint = new GPoint( this.map.dimensions.width/2, this.map.dimensions.height - 20 )
		
		// Create bounds which will hold all marker locations
		
		this.bounds = new GLatLngBounds();
		
		$$('.gm-address').each( function( address ){
			var addr = $(address);
			this.addLocation( GLatLng.fromUrlValue( this.extractInvertedLatLng( addr.readAttribute('title') ) ), addr );
		}.bind( this ) );
	},
	
	addLocation: function( loc, contentElement ){

		this.bounds.extend( loc );
		this.map.setCenter( this.bounds.getCenter());
		this.map.setZoom( this.map.getBoundsZoomLevel( this.bounds ));
		this.setMaxZoomCenter( loc );
		this.map.addOverlay( new LocationInfoOverlay( this.map, loc, contentElement ) );
	},
	
	addLocationByAddress: function( address, contentElement ){
		var gc = new GClientGeocoder();
		gc.getLatLng( address, function( loc ){
			if( loc ) this.addLocation( loc, contentElement );
		}.bind( this ) );
	},
	
	extractInvertedLatLng: function( lngLatString ){
		var split = lngLatString.split(',');
		return split[1] + ',' + split[0];
	},
	
	extractCoordinatesFromURL: function( url ){
		var params = url.toQueryParams();
		return GLatLng.fromUrlValue( params.ll || params.sll );
	},
	
	setMaxZoomCenter: function( latlng ) {
		this.map.getCurrentMapType().getMaxZoomAtLatLng( latlng, function( response ){
			if( response && response['status'] == G_GEO_SUCCESS && response.zoom < this.map.getZoom() ){
				this.map.setCenter( this.bounds.getCenter(), response['zoom']);
			}
		}.bind(this));
	}
} );

var LocationInfoOverlay = function( map, loc, contentElement ){
   	this.map = map;
   	this.loc = loc;
   	this.contentElement = contentElement;
   	this.marker = new GMarker( this.loc );
		this.map.addOverlay( this.marker );	   	
   	GEvent.addListener( this.marker, "click", this.toggle.bind( this ) );
	
	var closeIcon = this.contentElement.select('.close')[0];
	if( closeIcon ) closeIcon.observe("click", this.toggle.bind(this));
	
	this.contentElement.select('a').each( function( link ){
		// Close Link no redirect to maps.goolge.com
		if( !link.hasClassName('close') ) $(link).writeAttribute('href', this.getGoogleMapsURL( $(link).readAttribute('id')))
	}.bind(this));
}

if( typeof GOverlay != "undefined" ) LocationInfoOverlay.prototype = new GOverlay();

LocationInfoOverlay.prototype.initialize = function( map ){
	this.map.getPane( G_MAP_MARKER_PANE ).appendChild( this.contentElement );
}

LocationInfoOverlay.prototype.redraw = function( force ){
	if( !force ) return;
	var anchorPoint = this.map.fromLatLngToDivPixel( this.marker.getLatLng() );
	this.contentElement.setStyle({
		left: (anchorPoint.x - 40 ) + 'px',
		top: (anchorPoint.y - this.contentElement.getHeight() + 50 ) + 'px',
		zIndex: ( GOverlay.getZIndex( this.marker.getLatLng().lat() ) + 1 )
	});
}

LocationInfoOverlay.prototype.remove = function(){
	this.map.getPane( G_MAP_MARKER_PANE ).removeChild( this.contentElement );
}	

LocationInfoOverlay.prototype.hide = function(){
	this.contentElement.setStyle({
		display:"none"
	})
	return this;
};

LocationInfoOverlay.prototype.copy = function(){
	return new LocationInfoOverlay( this.map, this.loc, this.contentElement );
}
	
LocationInfoOverlay.prototype.show = function(){
	var panFromPoint = this.map.fromLatLngToContainerPixel( this.marker.getLatLng() );
	var panOffset = new GSize( this.map.panToPoint.x - panFromPoint.x, this.map.panToPoint.y - panFromPoint.y );
	this.contentElement.setStyle({
		display: 'block',
		position: 'absolute'
	});
	
	var edge = this.contentElement.select('.address-edge')[0] || null;
	if( edge ) $(edge).pngHack();
	
	this.map.panBy( panOffset );
	return this;
};

LocationInfoOverlay.prototype.toggle = function(){
	if( this.map.active ){
		this.map.active.hide();
		this.map.active = this.map.active == this ? null : this.show();
		return;
	} else{
		this.map.active = this.show();
	}
};

LocationInfoOverlay.prototype.getAddressString = function(){
	return this.contentElement.readAttribute('title').split( ";" )[1];
};

LocationInfoOverlay.prototype.getGoogleMapsURL = function( linkId ){
	
	var urlParams = {
		sll: this.map.getBounds().getSouthWest().toUrlValue(),
		ll: this.marker.getLatLng().toUrlValue(),
		t: this.map.getCurrentMapType().getUrlArg(),
		q: this.getAddressString()
	}
	
	switch( linkId ){
		case "getDirections":
			urlParams.iwloc = "A";		
			urlParams.iwstate1 = "dir";
			break;
			
		case "searchNearby":
			urlParams.iwloc = "A";		
			urlParams.iwstate1 = "sn";
			break;
			
		case "saveToMyMaps":
			urlParams.iwloc = "A";
			urlParams.iwstate1 = "saveplace";
			break;
	}
	
	return "http://maps.google.com/maps?" + Object.toQueryString( urlParams );
};

var CountryMapTooltip = Class.create({
	
	initialize: function( dot ){
		this.trigger = $(dot);
		this.tooltip = $(this.trigger.readAttribute('rel'));
		this.trigger.observe('mouseover', this.mouseover.bind(this));
		this.trigger.observe('mouseout', this.mouseout.bind(this));
	},
	
	mouseover: function( ){
		this.tooltip.setStyle({visibility:"visible"});
	},
	
	mouseout: function(){
		this.tooltip.setStyle({visibility:"hidden"});
	}
});

var ResetButton = Class.create({
	
	initialize: function( button ){
		
		this.button = $(button);
		this.button.observe( 'click', this.onrelease.bind( this ));
		this.form = this.button.up('form');
	},
	
	onrelease: function( e ){
		this.form.select('select, input[type="text"], input[type="checkbox"]').each( function( elem ){
			
			var elem	= $(elem);
			var tag 	= elem.tagName.toLowerCase();
			var type	= elem.readAttribute('type');
			
			if( tag == 'select' ); elem.selectedIndex = elem.indexDefaultValue ? elem.indexDefaultValue : 0;
			if( tag == 'input' && type == 'text' ) elem.value = elem.readAttribute('title');
			if( tag == 'input' && type == 'checkbox' ) elem.checked = false;
			
			Event.stop( e );
		} );
	}
});

var PageFooter = Class.create({
	
	initialize: function( elem ){
		
		this.footer =  elem;
		this.section = $('page-section');
		this.sectionHeight = this.section.getHeight() + (parseInt(this.footer.getStyle('padding-bottom')));
		
		Element.observe(window, 'resize', this.onWindowResize.bind(this) );
		Element.observe(window, 'load', this.onWindowResize.bind(this) );
	},

	onWindowResize: function(){
		setTimeout( function(){
			var viewport = document.viewport.getDimensions();
			if( viewport.height > this.sectionHeight ){
				var space =  (viewport.height - this.sectionHeight);
				this.footer.setStyle({ position: 'relative', 'top': space + 'px' });
			} else {
				this.footer.setStyle({ position: 'relative', 'top': '0px' });
			}
		}.bind(this), 1); /* timeout, because swfobject's onLoad handler is registered 
				later and therefore executing after this onLoad Event, 
				so the flash height may not be set and the footer position could be wrong*/
	}
});

var HomepageSlider = Class.create({
	
	initialize: function( altSliderDiv ){
		this.mainDiv = altSliderDiv;
		this.textItems = [];
		this.redBlock = this.mainDiv.down('.red-block');
		this.claim = this.mainDiv.down('#alt-title-block-white');
		this.config = {
			initialRedBlockHeight: this.redBlock.getStyle("height"),
			initialRedBlockTop: this.redBlock.getStyle("top")
		}
		this.resetTimeout = null;
		this.textTimeout = null;
		this.currentText = null;
		
		this.mainDiv.select('.text-item').each( function( item ){
			this.textItems.push( $(item) );
		}.bind( this ))
		
		this.mainDiv.select('ul li').each( function( item, num ){
			var li = $(item);
			li.textItem = this.textItems[num];
			li.slider = this;
			li.observe('mouseover', this.over.bind( li ));
			li.observe('mouseout', this.out.bind( li ));
		}.bind( this ));
	},
	
	over: function( e ){
		
		if( this.slider.resetTimeout )
			clearTimeout( this.slider.resetTimeout );
		
		if( this.slider.textTimeout )
			clearTimeout( this.slider.textTimeout );
		
		this.setStyle({cursor:"pointer"});
		
		this.slider.redBlock.setStyle({
			height:"350px",
			top: "0px"
		});
		
		this.slider.claim.hide();
		
		if( this.slider.currentText !== this.textItem ){
			
			if( this.slider.currentText ){
				this.slider.currentText.setStyle({
					display:"none"
				});
			}
			
			this.slider.textTimeout = setTimeout( function(){
				this.textItem.setStyle({
					display:"block"
				});
				this.slider.currentText = this.textItem;
			}.bind(this), this.slider.currentText ? 50 : 0 );
		}
		
		Event.stop(e);
		return false;
	},
	
	out: function( e ){

		this.setStyle({cursor:"normal"});
		
		this.slider.resetTimeout = setTimeout( function(){
			this.slider.redBlock.setStyle({
				height: this.slider.config.initialRedBlockHeight,
				top: this.slider.config.initialRedBlockTop
			})
			
			this.slider.claim.show();
			
			if( this.slider.currentText ){
				this.slider.currentText.setStyle({
					display:"none"
				})
			}
			
			this.slider.currentText = null;
			
		}.bind(this), 1000 );

		Event.stop(e);
		return false;
	}
});

var CharCounter = Class.create({
	
	initialize: function( selector, placeholderText, maxChars ){
		
		this.placeHolderText = placeholderText;
		this.maxChars = maxChars;
		this.selector = selector;
		this.textarea = null;
		this.label = null;
		
		window.dksh.domReady.push(this.register.bind(this))
	},
	
	register: function(){
		this.textarea = $(this.selector);
		this.label = $$('label[for="'+this.selector+'"]')[0];
		if( this.textarea ){
			this.textarea.observe('keydown', this.update.bind(this) );
		}
	},
	
	update: function(){
		var charsLeft = this.maxChars - this.textarea.getValue().length;
		if( this.label ){
			this.label.update( this.placeHolderText.replace("[x]", charsLeft));
			charsLeft <= 0 ? this.label.setStyle({color:"#ab1032"}) : this.label.setStyle({color:"#000000"});
		}
	}
});

var ImageSlider = Class.create({
	
	initialize: function( container ){
		this.container = container;
		this.ulist = this.container.down('ul').addClassName("clearfix");
		this.container.observe("mouseover", this.mouseOver.bind(this));
		this.container.observe("mouseout", this.mouseOut.bind(this));
		this.boundMouseMove = this.mouseMove.bind(this);
		this.width = this.container.getWidth();
		this.contentWidth = 0;
		this.pointerX = 0;
		this.interval = null;
		this.marginLeft = 0;
		
		this.ulist.select('li').each( function( li ){
			this.contentWidth += parseInt(li.getWidth()) + 15;
			this.setupTooltip( li.down("a img") );
		}.bind(this));
		
		this.contentWidth -= 23;
		this.isOver = false;
		this.endTweenValueOfMarginLeft = 0;
		this.offsetLeft = parseInt( this.container.cumulativeOffset().left );
		this.tooltipContainer = new Element('span', {"class":"slider-tt"});
		$('page-section').insert(this.tooltipContainer);
		this.tooltipContainer.setStyle({"display":"none"});
		this.boundMoveTooltip = this.moveTooltip.bind(this);
		
		if( this.contentWidth > this.width ){
			this.marginLeft = (this.width - this.contentWidth);
			this.ulist.setStyle({marginLeft:(this.marginLeft)+"px"})
			this.interval = setInterval(this.render.bind(this), 40 );
			this.isOver = true;
		}
	},
	
	setupTooltip: function( img ){
		if( img ){
			var self = this;
			img.altText = img.alt;
			img.alt = "";
			img.observe("mouseover", function( e ){
				self.showTooltip(this, e)
			}.bind(img));
		
			img.observe("mouseout", function( e ){
				self.hideTooltip(this, e);
			}.bind(img));
		}
	},
	
	showTooltip: function(img, event){
		this.tooltipContainer.update(img.altText);
		this.container.observe("mousemove", this.boundMoveTooltip );
		this.tooltipContainer.setStyle({"display":"block", "left": event.pointerX()-5 + "px", "top": event.pointerY() + "px"});
	},
	
	hideTooltip: function( img, event ){
		this.container.stopObserving("mousemove", this.boundMoveTooltip );
		this.tooltipContainer.setStyle({"display":"none"});
	},
	
	moveTooltip: function( e ){
		this.tooltipContainer.setStyle({"display":"block", "left": e.pointerX()-5 + "px", "top": e.pointerY() + "px"});
	},
	
	mouseOver: function( e ){
		if( this.isTarget( e, this.container )){
			this.pointerX = e.pointerX()-this.offsetLeft;
			this.isOver = true;
			this.container.observe("mousemove", this.boundMouseMove );
			if( !this.interval ){
				clearInterval( this.interval );
				this.interval = setInterval(this.render.bind(this), 40 );
			}
		}
	},
	
	mouseOut: function( e ){
		if( this.isTarget(e, this.container)){
			this.isOver = false;
			this.ulist.stopObserving("mousemove", this.boundMouseMove );
		}
	},
	
	mouseMove: function( e ){
		this.pointerX = e.pointerX()-this.offsetLeft;
	},
	
	render: function(){
		
		var speedBooster = (( this.pointerX ) / this.width *2 ) - 1;
		
		if( this.isOver ){
			this.endTweenValueOfMarginLeft = this.marginLeft - ( 20 * speedBooster );
			if( this.endTweenValueOfMarginLeft < this.width - this.contentWidth ) this.endTweenValueOfMarginLeft = this.width - this.contentWidth;
			if( this.endTweenValueOfMarginLeft > 0 ) this.endTweenValueOfMarginLeft = 0;
		}
			
		var easing = 0.8 * Math.abs(speedBooster);
		var targetX = Math.round(this.endTweenValueOfMarginLeft);
		var dX = Math.round(targetX - (this.marginLeft));
		var vX = dX * easing;
			
		this.marginLeft += vX;		
		this.ulist.style.marginLeft = Math.round(this.marginLeft) + "px";
	},
	
	isTarget: function( e, search ){
		var relatedTarget = $(e.relatedTarget || e.fromElement);
        var target = Event.element(e);
		
		if( !target || !relatedTarget ) return false;
		
        if ((target == search || Element.descendantOf(target, search)) && !((relatedTarget == search) || Element.descendantOf(relatedTarget, search))){
			return true;
		}
		return false;
	}
});

(function(){

	/*
	Prototype PNG Hack
	http://code.google.com/p/pnghack/
	*/
	
	Element.addMethods({
		pngHack: function(el){
			var el = $(el);
			if (!Prototype.Browser.IE) return el;
			var gif = 'images/s.gif';
			if ((el.match('img')) && (el.src.include('png'))){
				var alphaImgSrc  = el.src;
				var sizingMethod = 'scale';
				el.src = gif;
	    	}
			else if (el.getStyle('backgroundImage').include('png')){
				var bgc = el.getStyle('backgroundColor') || '';
				var alphaImgSrc = el.getStyle('backgroundImage').gsub(/url\(|\)|'|"/, '');
				var sizingMethod = 'crop';
				el.setStyle({ background: [bgc, ' url(', gif, ') no-repeat'].join('') });
			} 
			else{
				return el;
			}
			
			el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="#{al}",sizingMethod="#{sz}")'.interpolate({ al: alphaImgSrc, sz: sizingMethod });
			return el;
		}
	});
	
	var dksh = window.dksh = window.dksh ? window.dksh : {domReady:[]}, gm, langDropDown, trackingLink, footer;
	
	dksh.domReady.push( function(){
		
		// change bullet styles for non IE browsers
		if( !Prototype.Browser.IE ){
			$$('li.bullet').each(function(li){
				$(li).setStyle({
					left: "14px",
					marginLeft:"0px",
					textIndent:"0px"
				});
			});
		
		}
		else{
		// changes bullet style for IE browsers
			$$("li.bullet").each(function(item){
				$(item.parentNode).setStyle({
					overflow:'auto', 
					zoom:'normal', //1
					paddingBottom:"20px"
				});
			});
			
		}
		
		$$('select[title!=""]').each( function( select ){
			new DependentDropdown( select );
		});
		
		$$('.acm-dot').each( function( elem ){
			new CountryMapTooltip( elem );
		});
		
		$$('input.reset').each( function( button ){
			new ResetButton( button );
		});
		
		$$('.jshidden').each( function( item ){
			item.setStyle({ display:'none' });
		});
		
		$$('.acm-dot').each(function( png ){
			$(png).pngHack();
		});
		
		$$('.mod-image-slider').each( function(slider){
			new ImageSlider(slider);
		});
		
		if( gm = $('gm-canvas') )
			new LocationMap( gm );
			
		if( trackingLink = $('MostVisitedTrackingLink'))
			new Ajax.Request( trackingLink );
		
		if( footer = $('page-footer')){
			new PageFooter( footer );
		}
		
		if( langDropDown = $('LanguageDropdown') )
			langDropDown.setStyle({ display:'inline' });
		
	});

	document.observe( 'dom:loaded', function(){
		var l = this.domReady.length;
		for( var i = 0; i < l; i++ ) this.domReady[i]();
	}.bind( dksh ) );
})();