var places = {
    config: {},
    init: function(){
        places.el.wrapper = $('#places');
		// no places
        if (!places.el.wrapper.length)
            return false;
		// no google maps
        if (typeof(google.maps) !== 'object')
            return false;

        places.el.wrapper.hide();
        // create map
        places.createMap();
        // find items and create locations
        places.el.items = places.el.wrapper.children('.item');
        places.el.items.each(function(){
            places.createLocation($(this));
        });
    },
    createMap: function() {
	var pmc = $('#placesMapCenter').text();
	var pos = "";
	var zoom = 7;

	if (pmc != undefined && pmc.indexOf("|") >= 0) {
		var arr = pmc.split("|");
		pos = arr[0];
		zoom = (parseInt(arr[1]) <= 0) ? zoom : parseInt(arr[1]);
	} else {
		pos = pmc;
	}

        // get gps coords
        var latlng = places.parseGps(pos);
        // define center of map
        var mapCenter = new google.maps.LatLng(latlng[0], latlng[1]);
        // define map options
        var mapOptions = {
            zoom: zoom,
            center: mapCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
			      disableDefaultUI: false,
			      mapTypeControl: false,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            navigationControl: true,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.ZOOM_PAN,
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            scaleControl: false,
            scaleControlOptions: {
                position: google.maps.ControlPosition.TOP_LEFT
            }
        };
        // create map from options and center
        places.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    },
    createLocation: function(el){
        var locoptions = {};

        var ico = "gmap-marker.png";
        var loc = el.find('.location').text();
        if (loc == undefined || loc == "") {
        	ico = "gmap-marker1.png";
        	loc = el.find('.location1').text();
	 }

        // get gps coords
        var latlng = places.parseGps(loc);
        // create gps location
        locoptions.markerPos = new google.maps.LatLng(latlng[0], latlng[1]);

        // create marker
        locoptions.marker = new google.maps.Marker({
            position: locoptions.markerPos,
            title: el.find('.title').text(),
            icon: '/public/images/' + ico,
            map: places.map
        });

		// create content
        var htmlContent = '';
        htmlContent += '<div class="popup popupMap"><div class="popupA"><div class="popupB"><div class="popupC"><div class="popupD"><div class="popupE"><div class="popupF"><div class="popupInner"><div class="cleaned">';
        htmlContent += el.html();
        htmlContent += '</div><span class="arrow"><!--  --></span></div><!-- #popupInner --></div></div></div></div></div></div></div><!-- .popup -->';

        // create info window
        locoptions.infoWindow = new InfoBox({
            // infoWindow compatible
            content: htmlContent,
            //pixelOffset: 10,
            //position: markerPos,
            maxWidth: 320,
            //infoBox only
            disableAutoPan: false,
            pixelOffset: new google.maps.Size(-64, -188),
            zIndex: null,
            boxStyle: {
                width: "320px"
            },
            closeBoxMargin: "0",
            closeBoxURL: "/public/images/icon-close.png",
            infoBoxClearance: new google.maps.Size(20, 20),
            isHidden: false,
            pane: "floatPane",
            enableEventPropagation: true
        });

        // on infoBox open
        google.maps.event.addListener(locoptions.infoWindow, 'domready', function(){
            // set class to close button
		$('.popupMap').prev('img').attr('style','').addClass('popupClose');
        });

        // bind open info window on marker click event
        google.maps.event.addListener(locoptions.marker, 'click', function(){
			// close all boxes
			for(var i = 0; i < places.locations.length; i++)
			{
				places.locations[i].infoWindow.close();
			}
            locoptions.infoWindow.open(places.map, locoptions.marker);
        });

        // store link to array
        places.locations[places.locations.length] = locoptions;
    },
    parseGps: function(text){
        return text.replace(/\s/, '').split(/,|;/);
    },
    el: {},
    locations: []
};

window.onload = function(){
    //    init_map();
    places.init();
};
//--------------------------------------------------------------------------

$(document).ready(function() {

	$("ul#bannerMenu").tabs(".tabsContent > div.tab", {history: true});


	// select #flowplanes and make it scrollable. use circular and navigator plugins
	$("#flowpanes").scrollable({circular: true,

		onSeek: function () {
			n=this.getIndex();
			//alert("dddd "+n);

			$('.items div.narrow').not('.items div.narrow:eq('+n+')').fadeOut("slow");
			$('.items div.narrow:eq('+n+')').fadeIn("slow");

		}


	}).navigator({

		// select #flowtabs to be used as navigator
		//navi: "#flowtabs",

		// select A tags inside the navigator to work as items (not direct children)
		naviItem: 'a',

		// assign "current" class name for the active A tag inside navigator
		activeClass: 'current',

		// make browser's back button work
		history: true

	}).autoscroll({
		interval: 3000
	});


	$("#flowpanes2").scrollable({circular: true,
		onSeek: function () {
			n=this.getIndex();
			$('.items div.narrow').not('.items div.narrow:eq('+n+')').fadeOut("slow");
			$('.items div.narrow:eq('+n+')').fadeIn("slow");
		}
	}).navigator({
		// select #flowtabs to be used as navigator
		//navi: "#flowtabs",
		// select A tags inside the navigator to work as items (not direct children)
		naviItem: 'a',
		// assign "current" class name for the active A tag inside navigator
		activeClass: 'current',
		// make browser's back button work
		history: true
	}).autoscroll({
		interval: 3000
	});

    $("#accordion").accordion();

    $("#accordion h3").click(function(){
		$("#accordion h3 ").next("div").removeClass("active");
    	$(this).next("div").addClass("active");
		//$(this).next().toggle();
		//return false;
    })



	Cufon.replace('h1, h2, h3:not(.titleAddress)', { fontFamily: 'AvalonCE', hover: true });
	Cufon.replace('#mainContainer .news h2 a, #mainContainer .news a.more, .news1 a.more, #footerContainer .firstColumn .line, .products .group .productBox a, .productBox a.more, .refBox a.more', { fontFamily: 'AvalonCE', hover: true });
	Cufon.replace('#popmenu a, .popupMap h3.title, #bannerMenu a, #footerContainer h3 a', { fontFamily: 'AvalonCE', hover: true });

	//$("div.galleryNone .photogallery").hide();
	$("div.galleryNone a.clickTitle").click(function () {
			var obj1 = $(this).parents(".galleryNone");
			obj1.children(".photogallery").slideToggle("slow");
			return false;
	});

	//menu
	Cufon.replace('#menu li a', { fontFamily: 'AvalonCE', hover: true });
	Cufon.replace('#top>li>a', { fontFamily: 'AvalonCE', hover: true });

	$('#menu>ul>li').hover(function(){},function(){
	  var color = '#CFCFD0';
	  if($(this).hasClass('selected'))
	  {
	    color = '#000000';
	  }
	  Cufon.replace($(this).children('a'), { fontFamily: 'AvalonCE', hover: true, color: color });
	});

	$('#bannerMenu a').click(function(){
      Cufon.replace($('#bannerMenu a'), { fontFamily: 'AvalonCE', hover: true, color: '#ffffff' });
	  if($(this).hasClass('current'))
	  {
	    Cufon.replace($(this), { fontFamily: 'AvalonCE', hover: true, color: '#000000' });
	  }
	});

	$('#footerContainer .firstColumn').hover(function(){
		Cufon.replace($(this).children('.line'), { fontFamily: 'AvalonCE', hover: true, color: '#000000' });
	},function(){
		Cufon.replace($(this).children('.line'), { fontFamily: 'AvalonCE', hover: true, color: '#848286' });
	});

	$('#footerContainer .secondColumn').hover(function(){
		Cufon.replace($(this).children('h3').children('a'), { fontFamily: 'AvalonCE', hover: true, color: '#E5007D' });
	},function(){
		Cufon.replace($(this).children('h3').children('a'), { fontFamily: 'AvalonCE', hover: true, color: '#848286' });
	});

	$('#footerContainer .thirdColumn').hover(function(){
		Cufon.replace($(this).children('h3').children('a'), { fontFamily: 'AvalonCE', hover: true, color: '#009EE3' });
	},function(){
		Cufon.replace($(this).children('h3').children('a'), { fontFamily: 'AvalonCE', hover: true, color: '#848286' });
	});

	$('#footerContainer .fourthColumn').hover(function(){
		Cufon.replace($(this).children('h3').children('a'), { fontFamily: 'AvalonCE', hover: true, color: '#00963F' });
	},function(){
		Cufon.replace($(this).children('h3').children('a'), { fontFamily: 'AvalonCE', hover: true, color: '#848286' });
	});

	/**
	* CAROUSEL
	*/
	if( $('#carousel .item').length + $('#carousel .item1').length > 5 ) {
		var selectedIndex = $('#carousel .selected').index();
		var startIndex = (selectedIndex) ? selectedIndex : 0;
		startIndex = (startIndex < 0) ? 0 : startIndex;

		$('#carousel .outer').height($('#carousel .items').height()).before('<a href="#" class="larrow" onclick="return false"><!--  --></a>').after('<a href="#" class="rarrow" onclick="return false"><!--  --></a>');
		$('#carousel .outer').serialScroll({
			items:'li',
			prev:'#carousel a.larrow',
			next:'#carousel a.rarrow',
			offset: 0,
			start: startIndex,
			duration:1100,
			force:true,
			stop:true,
			lock:false,
			cycle:true,
			easing:'easeOutQuart',
			jump: false,
			exclude: 5
		});
	} else if($('#carousel').length) {
		$('#carousel .outer').height($('#carousel .items').height());
	}

	if($('#slides').length) {
		$('#slides').slides({
			effect: 'fade',
			preload: true,
			preloadImage: '../slides/img/loading.gif',
			play: 2000,
			pause: 2500,
			hoverPause: true,
			crossfade: true
		});
	}

});

jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

jQuery.easing.easeOutExpo = function (x, t, b, c, d) {
	return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
}

;(function(c){var a=c.scrollTo=function(f,e,d){c(window).scrollTo(f,e,d)};a.defaults={axis:"xy",duration:parseFloat(c.fn.jquery)>=1.3?0:1};a.window=function(d){return c(window)._scrollable()};c.fn._scrollable=function(){return this.map(function(){var e=this,d=!e.nodeName||c.inArray(e.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!d){return e}var f=(e.contentWindow||e).document||e.ownerDocument||e;return c.browser.safari||f.compatMode=="BackCompat"?f.body:f.documentElement})};c.fn.scrollTo=function(f,e,d){if(typeof e=="object"){d=e;e=0}if(typeof d=="function"){d={onAfter:d}}if(f=="max"){f=9000000000}d=c.extend({},a.defaults,d);e=e||d.speed||d.duration;d.queue=d.queue&&d.axis.length>1;if(d.queue){e/=2}d.offset=b(d.offset);d.over=b(d.over);return this._scrollable().each(function(){var l=this,j=c(l),k=f,i,g={},m=j.is("html,body");switch(typeof k){case"number":case"string":if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(k)){k=b(k);break}k=c(k,this);case"object":if(k.is||k.style){i=(k=c(k)).offset()}}c.each(d.axis.split(""),function(q,r){var s=r=="x"?"Left":"Top",u=s.toLowerCase(),p="scroll"+s,o=l[p],n=a.max(l,r);if(i){g[p]=i[u]+(m?0:o-j.offset()[u]);if(d.margin){g[p]-=parseInt(k.css("margin"+s))||0;g[p]-=parseInt(k.css("border"+s+"Width"))||0}g[p]+=d.offset[u]||0;if(d.over[u]){g[p]+=k[r=="x"?"width":"height"]()*d.over[u]}}else{var t=k[u];g[p]=t.slice&&t.slice(-1)=="%"?parseFloat(t)/100*n:t}if(/^\d+$/.test(g[p])){g[p]=g[p]<=0?0:Math.min(g[p],n)}if(!q&&d.queue){if(o!=g[p]){h(d.onAfterFirst)}delete g[p]}});h(d.onAfter);function h(n){j.animate(g,e,d.easing,n&&function(){n.call(this,f,d)})}}).end()};a.max=function(j,i){var h=i=="x"?"Width":"Height",e="scroll"+h;if(!c(j).is("html,body")){return j[e]-c(j)[h.toLowerCase()]()}var g="client"+h,f=j.ownerDocument.documentElement,d=j.ownerDocument.body;return Math.max(f[e],d[e])-Math.min(f[g],d[g])};function b(d){return typeof d=="object"?d:{top:d,left:d}}})(jQuery);
;(function(a){var b=a.serialScroll=function(c){return a(window).serialScroll(c)};b.defaults={duration:1e3,axis:"x",event:"click",start:0,step:1,lock:!0,cycle:!0,constant:!0};a.fn.serialScroll=function(c){return this.each(function(){var t=a.extend({},b.defaults,c),s=t.event,i=t.step,r=t.lazy,e=t.target?this:document,u=a(t.target||this,e),p=u[0],m=t.items,h=t.start,g=t.interval,k=t.navigation,l;if(!r){m=d()}if(t.force){f({},h)}a(t.prev||[],e).bind(s,-i,q);a(t.next||[],e).bind(s,i,q);if(!p.ssbound){u.bind("prev.serialScroll",-i,q).bind("next.serialScroll",i,q).bind("goto.serialScroll",f)}if(g){u.bind("start.serialScroll",function(v){if(!g){o();g=!0;n()}}).bind("stop.serialScroll",function(){o();g=!1})}u.bind("notify.serialScroll",function(x,w){var v=j(w);if(v>-1){h=v}});p.ssbound=!0;if(t.jump){(r?u:d()).bind(s,function(v){f(v,j(v.target))})}if(k){k=a(k,e).bind(s,function(v){v.data=Math.round(d().length/k.length)*k.index(this);f(v,this)})}function q(v){v.data+=h;f(v,this)}function f(B,z){if(!isNaN(z)){B.data=z;z=p}var C=B.data,v,D=B.type,A=t.exclude?d().slice(0,-t.exclude):d(),y=A.length,w=A[C],x=t.duration;if(D){B.preventDefault()}if(g){o();l=setTimeout(n,t.interval)}if(!w){v=C<0?0:y-1;if(h!=v){C=v}else{if(!t.cycle){return}else{C=y-v-1}}w=A[C]}if(!w||t.lock&&u.is(":animated")||D&&t.onBefore&&t.onBefore(B,w,u,d(),C)===!1){return}if(t.stop){u.queue("fx",[]).stop()}if(t.constant){x=Math.abs(x/i*(h-C))}u.scrollTo(w,x,t).trigger("notify.serialScroll",[C])}function n(){u.trigger("next.serialScroll")}function o(){clearTimeout(l)}function d(){return a(m,p)}function j(w){if(!isNaN(w)){return w}var x=d(),v;while((v=x.index(w))==-1&&w!=p){w=w.parentNode}return v}})}})(jQuery);



