$.log = function() {//Funzione per la scrittura sulla console di FF - su ie6 pianta tutto - metto controllo
    if ($.browser.mozilla) {
     var consoleExists = (typeof(console) == "object") && (typeof(console.log) == "function");
     if (consoleExists) { 
         if (navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1) { 
                                            console.log(arguments); 
         } else { 
           console.log.apply(this,arguments); 
         } 
     } 
    }
}



/* paolo */
/* var pathimg='';
var debug =true; */


//vale
var pathimg='/www.thecleanenergyleader.com/';
var debug =false;

var toClick;
var li;
var ulRot;
var start;

$(document).ready(function(){	
		
		
		if($('#home-top').is('div')){
			
			writeHpXml();
			
			
			

		};
		if($('div[class^="video_"]').is('div')){
			showVideo();
	
		};
		if($('#col_top .video').is('div') && $('#col_top .video .video_youTube a').attr('href').indexOf('.youtube.') >=0){
	
			playYoutube();
		}else if($('#col_top .video').is('div') && $('#col_top .video .video_youTube a').attr('href').indexOf('.flv') >=0){
	
			playFlv();
			
		};
		//alert($('#col_top .video  a').attr('href'));
		if($('#footer').is('div')){
			viewSitemap();
		};
		if($('#faq_cent').is('div')){
			scrollFaq();
		};
		if($('#contatti').is('div')){
			loadContatti();
		};
		if($('#maps_link').is('div')){
			
			loadMap();
		};
		if($('#faq').is('div')){
			carouselFaq();
			$('#faq .lightbox').lightbox();
		/*	if(langXml=="da"){
				$('.lightbox').lightbox({
					strings:{
						prevLinkTitle:"Forrige",
						nextLinkTitle:"N&aelig;ste",
						prevLinkText:"&laquo; Forrige",
						nextLinkText:"N&aelig;ste &raquo;",
						closeTitle:"LUK",
						image:"Billede ",
						of:" af "
					},
					fileBottomNavCloseImage : pathimg+'img/lightbox/dan/luklabel.gif'
				});
			}*/
		};
		if($('#gallery_int').is('div')){
			galleryInt()
		};
		if($('#carousel-top').is('div')){
			carouselTop();
			//$('#carousel-top .lightbox').lightbox();
		};
		if($('#contact').is('div')){
			styleSelect();
		};
		if($('#header-select').is('div')){
			showMarket();
		};
		if($('#col_sx ul li a').hasClass('on')){
			menuSec();
		};
			openchoosemarket();
			
		
});
function galleryInt(){
	carouselImg();
			
	if(langXml=="da"){
		$('#gallery_int .lightbox').lightbox({
			strings:{
				prevLinkTitle:"Forrige",
				nextLinkTitle:"N&aelig;ste",
				prevLinkText:"&laquo; Forrige",
				nextLinkText:"N&aelig;ste &raquo;",
				closeTitle:"LUK",
				image:"Billede ",
				of:" af "
			},
			fileBottomNavCloseImage : pathimg+'img/lightbox/dan/luklabel.gif'
		});
	}else{
		$('.lightbox').lightbox();
	}
}
function openchoosemarket(){
$('#change_market').click(function(){
				chooseMarket();
				return false;
				});
			}

function setMarket(){	
	if($.cookie('cel_url') && !$.cookie('cel_session') ){		
		window.location = $.cookie('cel_url');
		$.cookie("cel_session","true", { path: '/'});
	}
	if(!$.cookie('cel_url')){
		chooseMarket();
		$('#choose div ul a').click(function(){
		var url = $(this).attr('href');
		$.cookie("cel_url",url, {expires: 365, path: '/'});
		$.cookie("cel_session","true", { path: '/'});
		});
	}
}

function chooseMarket(){
	var h = $('#layout').innerHeight();	
	var h = $(document).height();
	$('body').append('<div class="fdr">&nbsp;</div>');
	$('.fdr').css({height:h});	
	$('#choose').show(function(){
		
		$('#close').click(function(){
			
			$('#choose').hide(300);
			$('.fdr').hide();
		});
	});
}

function menuSec(){
	$('.menu_secondo').show();
}

function showMarket(){
	var a = $('#market')
	a.removeClass('on');
	a.click(function(){
		$(this).toggleClass('on');
		$('#market-sel').slideToggle(300);
	});
}

function styleSelect(){
	$('select').sSelect();
}

function carouselFaq(){
	$('#carousel-faq').jCarouselLite({
		btnNext: '#next-faq',
		btnPrev: '#prev-faq',
		visible: 1
		
	});
	return false;
}

function carouselImg(){
	if($('#carousel-img img').length >=4){
		$('#carousel-img').jCarouselLite({
			btnNext: '#next-img',
			btnPrev: '#prev-img',
			visible: 4,
			circular:false 
		});
	};
	return false;
}

function carouselTop(){
	$('#carousel-top').jCarouselLite({
		btnNext: '#next-top',
		btnPrev: '#prev-top',
		visible: 1,
		circular:false 
	});
	return false;	
}

function playYoutube(){

	$('#col_top .video_youTube').each(function(cnt){
 	var video_path="http://www.youtube.com/v/"
	var video_link = $(this).find("a").attr('href');
	var idyoutube=	video_link.substring(video_link.indexOf("v=")+2,video_link.length);		
	if(idyoutube.indexOf("&")>0){
		idyoutube=idyoutube.substring(0,idyoutube.indexOf("&"));		
		}
		video_path=video_path+idyoutube+"&hl=it_IT&fs=1";

		var html="";
		html+='<object width="485" height="275">';
		html+='<param name="movie" value="'+video_path+'"></param>';
		html+='	<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>';
		html+='<embed src="'+video_path+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="485" height="275"></embed>';
		html+='</object>';
	$(this).html(html);

	});
}

function playFlv(){

		var video_path = $("#col_top .video .video_youTube a").attr('href');
		var img_thumb =  $("#col_top .video .video_youTube a img").attr('src');
	$('#col_top .video .video_youTube').media({
			width:     485,
			height:    275,
			bgColor: 'transparent',
			autoplay:  false,
			params:    {bgcolor : '#000000',scale:'noscale' , wmode:'transparent', allowfullscreen:'true'},
			attrs:     {bgcolor : '#000000',scale:'noscale' , wmode:'transparent'},
			src:       pathimg+'swf/player.swf',
			flashvars:  {file: video_path, image:img_thumb, frontcolor : '0xAAAAAA',backcolor : '0x000000',lightcolor:'0xEEEEEE', autostart:'false'},
			caption:   false			  
		});
}

function openVideo(img_thumb,video_path){	
		$(".contVideo div").media({
			width:     480,
			height:    270,
			bgColor: 'transparent',
			autoplay:  true,
			params:    {bgcolor : '#000000',scale:'noscale' , wmode:'transparent', allowfullscreen:'true'},
			attrs:     {bgcolor : '#000000',scale:'noscale' , wmode:'transparent'},
			src:       pathimg+'swf/player.swf',
			flashvars:  {file: video_path, image:img_thumb, frontcolor : '0xAAAAAA',backcolor : '0x000000',lightcolor:'0xEEEEEE', autostart:'true'},
			caption:   false			  
		});
}

function handleVideoYoutube(video_link){	
  
	var video_path="http://www.youtube.com/v/"	
	var idyoutube=	video_link.substring(video_link.indexOf("v=")+2,video_link.length);		
	if(idyoutube.indexOf("&")>0){
		idyoutube=idyoutube.substring(0,idyoutube.indexOf("&"));		
		}
		video_path=video_path+idyoutube+"&hl=it_IT&fs=1&autoplay=1";
        var html="";
        
        html+='<object width="480" height="385">';
        html+='<param name="movie" value="'+video_path+'"></param>';
        html+='<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>';
        html+='<embed src="'+video_path+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>';
        html+='</object>';
    $(".contVideo div").html(html);

	
}


function getLayerInfo(pathxml,iddiv){//url xml, div contenitore il dettaglio news, url della lista news
			var uid=pathxml.substring(pathxml.indexOf("uid=")+4,pathxml.length);
			
		
		$.ajax({
				type: "GET",
				url: pathxml,
				dataType: 'xml',
				success: function(msg){
					var news;
					if (uid!='') {   news = $(msg).find("Item[uid="+uid+"]");	}
					else { news=$(msg).get(0); }
					var testo = $("testo", news).text();
					
					$(iddiv).html(testo);
					
				},complete: function(){
					galleryInt();
				}

	});
}


function resizeCont(){
	var amp = $('.contVideo div').innerWidth();		
	$('.contVideo').css({width:amp});
	
}

function showVideo(){
	//valentina
		var videoA = $('div[class^="video_"]');
		videoA.each(function(){
			$(this).find("a").click(function(e){
			this_click=$(this);
				$('object, embed').css({'visibility':'hidden'});
				var percorso = this_click.attr('href');
			
				var img_t = this_click.find('img').attr('src');
				var h = $(document).height();
				var w = $('#layout').innerWidth();
				
				$('body').append('<div class="fdr">&nbsp;</div>');
				$('.showVideo').css({height:h, width:w});
				$('.fdr').css({height:h});
				$('.contVideo div').html("");
				$('.showVideo').show(700,function(){
					$('.contVideo div').removeClass().removeAttr('style');
					if(percorso.indexOf('.youtube.') >=0){
						//$('.contVideo div').removeClass('flv');
						handleVideoYoutube(percorso);
					}else if(percorso.indexOf('flv') >=0){
						$('.contVideo div').addClass('flv');
						openVideo(img_t,percorso);
					}else if(percorso.indexOf('.xml') >=0){
						$(".contVideo").find("div:first").addClass("novideo");
						getLayerInfo(percorso,".contVideo .novideo")
					};
					
					var fromtop=e.pageY-395;
					
					var fromtop = (fromtop < 0) ? "70px" : fromtop; 
					$('.contVideo').css({top:fromtop});
				});
				
				$('.contVideo a.close').click(function(){
						$('.showVideo').hide(100);
						$('.fdr').hide();
						$('object, embed').css({'visibility':'visible'});
						return false;
				});
				return false;
			});
		});
        
} 

function viewSitemap(){		
	var btn = $('.sitemap-click');	
	btn.click(function(){
		$(this).toggleClass('sitemap-btn');
		$('#sitemap').slideToggle(500, function(){
			$.scrollTo('#footer', 700);
		});			
		return false;
	});
	
}

function scrollFaq(){
	$.localScroll({
		duration:2000,
		hash:false
	});
}

function rotateMenu(){

	var current=ulRot.find(".on");
	var next=current.next();

	if (next.length==0) next=li.eq(0);
	current.removeClass("on");
	next.addClass("on");
	var indice=li.index(next);
	$('#tab ul').css({'background-image':'url("'+pathimg+'img/bg-ul'+indice+'.gif")'});
	
	var toShow = $('.img-home-cont');
	toShow.removeClass('show');
	toShow.eq(indice).addClass('show');
	var imgToclick = next.find("a").attr('rel'); 
	$('#home-top').css({'background-image':'url('+imgToclick+')'});		

}



function switchTab(){

	toClick.click(function(){
/* 		window.clearInterval(start);
		start=setInterval(rotateMenu,6000);*/ 
		li.removeClass('on');
		$(this).parents('li').addClass('on');
		var indice = $(this).parents('li').index();
		
		$('#tab ul').css({'background-image':'url("'+pathimg+'img/bg-ul'+indice+'.gif")'});
		var toShow = $('.img-home-cont');
		toShow.removeClass('show');
		toShow.eq(indice).addClass('show');
		var imgToclick = $(this).attr('rel'); 
		$('#home-top').css({'background-image':'url('+imgToclick+')'});		
		return false;
	});
}


function loadContatti(){
		$('#contatti').load('/www.thecleanenergyleader.com/other/contatti_'+langXml+'.html', function(){
				$("#sendContact").click(function(){						
						 var validEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
							 var formActive=$('#contactForm');
							 var formOk=true;
							 var name=$("#contactForm #name").val();
							 var email=$("#contactForm #email").val();
							 var note=$("#contactForm #message").val();
							 						 var object=$("#contactForm #object").val();
						
							 var privacy =$('#contactForm #privacy').attr('checked');
						
							if(name=='' || email=='' ||note=='' || object==''  || privacy!=true){
								alert(txtFormReqiured);
							
								formOk=false;
							}else if(!validEmail.exec(email)){
									alert(txtFormEmail);
								
								formOk=false;
							}
							if(formOk){
								
											formActive.submit();
									
	
							}
							
	
						return false;
					});

			var res = GetUrlParam('response');
			if(res=='ok'){
				$("#contatti").html(txtFormSend);
			}
			else if(res=='ko'){
				$("#contatti").html(txtFormNotSend);
			}
			else{
			
			$('#contactForm input[name=error]').val(window.location.toString()+"?response=ko");
			$('#contactForm input[name=forward]').val(window.location.toString()+"?response=ok");
			}

	});
}
	
function GetUrlParam(paramName){
  var oRegex = new RegExp( '[\?&]' + paramName + '=([^&]+)', 'i' ) ;
  var oMatch = oRegex.exec( window.top.location.search ) ;
  if ( oMatch && oMatch.length > 1 )
    return decodeURIComponent( oMatch[1] ) ;
  else
    return '' ;
}


function writeHpXml(){
	var urlxml=sRootPath+langXml+"/XML/HP/data.xml"
//var urlxml="DATA/data.xml"
    var i = 0;
	$.ajax({
			 type: "GET",
			 url: urlxml,
			 dataType: 'xml',
			 success: function(msg){
			 	
					   $(msg).find("Item").each(function(){
					   		var htmlimg = '';
					   		var htmllist = '';
					   					i++;
					   					var titolo = $("titolo ", this).text().replace(/(<([^>]+)>)/ig,"");
									   	var backgroundimg = $("background", this).text();
											var testo = $("testo", this).text();
											var descrizionebreve = $("descrizionebreve", this).text();
											var classlist='';
											if(i==1){
												classlist=' show';
											}
											
											
											htmlimg+='<div class="img-home-cont'+classlist+'">';
												htmlimg+='<div class="img-box">';
												htmlimg+=testo;
												htmlimg+='</div>';
												htmlimg+='<div class="img-box-layer"><img src="'+pathimg+'img/bg-box-home.gif" alt=""/></div>';
											htmlimg+='</div>';
											
											
										//htmlimg+='<img src="'+backgroundimg+'" alt="'+titolo+'"/>';

											$("#img-home").append(htmlimg);
									
											var classlist='';
											if(i==1){
												classlist=' on';
											}
											if(i==3){
												classlist=' no-mrg';
											}
											htmllist+='<li id="img-home'+i+'" class="'+classlist+'">';
											htmllist+='<h2><a href="#" rel="'+backgroundimg+'">'+titolo+'</a></h2>';
											htmllist+=descrizionebreve+'</li>';
											
											$("#tab ul").append(htmllist);
							
									   })
						
				 },complete: function(){	
				 			var imgToclick = $("#tab li.on a").attr('rel'); 
						$('#home-top').css({'background-image':'url('+imgToclick+')'});		
						
						toClick = $('#tab ul li h2 a');
						ulRot = $('#tab ul');
						li=ulRot.find("li");
if(window.location.toString().indexOf("cms.")<0){
						setMarket();
}						
						start=setInterval(rotateMenu,5000);
						li.hover(
							function()
							{
								window.clearInterval(start);
							},
							function()
							{
								start=setInterval(rotateMenu,5000);
							}
						)
						switchTab();
									
						///////////////img-box
						var layerdiv = $('.img-box');
						layerdiv.each(function(){
							$(this).find("a").click(function(e){
									this_click=$(this);
									var percorso = this_click.attr('href');
									if(percorso.indexOf('.youtube.') >=0 || percorso.indexOf('flv') >=0 || percorso.indexOf('.xml') >=0){
										$('.contVideo div').html("");
										$('object, embed').css({'visibility':'hidden'});
										var img_t = this_click.find('img').attr('src');
										var h = $(document).height();
										var w = $('#layout').innerWidth();
										$('body').append('<div class="fdr">&nbsp;</div>');
										$('.showVideo').css({height:h, width:w});
										$('.fdr').css({height:h});
										$('.showVideo').show(700,function(){
											$('.contVideo div').removeClass().removeAttr('style');
											if(percorso.indexOf('.youtube.') >=0){
												//$('.contVideo div').removeClass('flv');
												handleVideoYoutube(percorso);
											}else if(percorso.indexOf('flv') >=0){
												$('.contVideo div').addClass('flv');
												openVideo(img_t,percorso);
											}else if(percorso.indexOf('.xml') >=0){
												percorso=percorso.replace("/pag/","/");
												$(".contVideo").find("div:first").addClass("novideo");
												getLayerInfo(percorso,".contVideo .novideo")
											};
											var fromtop=e.pageY-395;
											var fromtop = (fromtop < 0) ? "70px" : fromtop; 
											$('.contVideo').css({top:fromtop});
										});
					
										$('.contVideo a.close').click(function(){
												$('.showVideo').hide(100);
												$('.fdr').hide();
												$('object, embed').css({'visibility':'visible'});
												return false;
										});
											return false;
									}
										return true;;
								});
						});
						///////////////
				 		
				 	}
				 
		   });
}



var gmarkers = [];
function loadMap(){

    if (GBrowserIsCompatible()) {
              function createMarker(point,name,html,icon) {
                    var marker = new GMarker(point, {icon:icon});                      
                         GEvent.addListener(marker, "click", function() {
                      				 marker.openInfoWindowHtml(html, {maxWidth:500, maxHeight:470, autoScroll:true});               
                            });
                     gmarkers.push(marker);
                    return marker;
             		 }
                var urlmap=sRootPath+langXml+"/XML/MAPS/data.xml";
                var countmap=0;
              GDownloadUrl(urlmap, function (doc) {
                    var gmarkers = [];
                    var xmlDoc = GXml.parse(doc);
                    var markers = xmlDoc.documentElement.getElementsByTagName("Item");

                    for (var i = 0; i < markers.length; i++) {

                        var lat = parseFloat(markers[i].getElementsByTagName("coordinate")[0].childNodes[0].getAttribute('lat'));
                        var lng = parseFloat(markers[i].getElementsByTagName("coordinate")[0].childNodes[0].getAttribute('long'));
                        var zoom = 2
                        if(zoom==""){
                            zoom=0;
                        }
                        var point = new GLatLng(lat,lng);
                        var markDefault  = new GIcon(G_DEFAULT_ICON);
                        var point = new GLatLng(lat,lng);
                        var html='<div id="number'+countmap+'" class="info" >';
                        var descrizione = markers[i].getElementsByTagName("txtballoon")[0].childNodes[0].childNodes[0]+'';
                            if(descrizione!='undefined' && descrizione!='null'){
                                        html+='<p>'+markers[i].getElementsByTagName("txtballoon")[0].childNodes[0].childNodes[0].nodeValue+'</p>'
                            }                         
                        html += '<br/></div>';
                        var marker = createMarker(point,"",html,markDefault);
                        gmarkers.push(marker);
                        countmap++;
                    }
                    var myLink = $('#maps_link a').attr('href');
                    var myLat =  getQuerystring("ll", "0", myLink).split(',')[0];
                    var myLong = getQuerystring("ll", "0", myLink).split(',')[1];
                    var myZoom = getQuerystring("z", "0", myLink);
                    var newZoom = parseInt(myZoom);
                    var map = new GMap2(document.getElementById("themap"));
                    map.addControl(new GLargeMapControl());
                    map.addControl(new GMapTypeControl());
                    map.setCenter(new GLatLng(myLat, myLong), newZoom);
                    map.setMapType(G_NORMAL_MAP);
                    map.enableDoubleClickZoom();
                    var mm = new GMarkerManager(map, {borderPadding:1});
                    mm.addMarkers(gmarkers,zoom);
                    mm.refresh();
   
                  })
            

    }
    else {
            alert("Sorry, the Google Maps API is not compatible with this browser");
    }

}

function getQuerystring(key, default_, url){
	if (default_==null) default_="";
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(url);
	if(qs == null)
		return default_;
	else
		return qs[1];
}


