/** 
 *  Common scripts file
 *  @version: 1.0 
 *  @require: jquery
 */
 
var pane = false,
	section = false,
	api = false,
	doScroll = true;

function loadScrollPane()
{
	pane = $('#panel');
	//console.log(pane.width());
	if(pane.width() < 220) {
		pane.parent().find('p.thumb').hide();
	} else {
		pane.parent().find('p.thumb').show();
	}
	
	pane.jScrollPane({
		animateScroll: true
		//,autoReinitialise: true
	});
	
	api = pane.data('jsp');
}

function scrollPane()
{
	if (doScroll) {
		if(api.getPercentScrolledY() < 1) {
			api.scrollBy(0, 210);
		} else {
			api.scrollTo(0, 0);
		}
	}
	return false;
}

$(document).ready(function()
{
    // section
	section = page.section;
	
    // protezione antispam per le email
    emailProtection('.email');    
    	
	if(section == 'home') {
		// accordion home
		$('#accordion').accordion({
			autoheight: false,
			active: false,
			alwaysOpen: false,
			collapsible: true
		});
		
		// tabs home
		//tabs('realizzati');
		
		// logo flash
		if (isiPhone() || isiPad()){
			$('#logoHome').attr('id', 'logo');
		} else {
			flashLogo();
		}
		
		// news scroll	
		loadScrollPane();		
		pane.mouseover(function(){
			doScroll = false;
		}).mouseout(function(){
			doScroll = true;
		});
		setInterval("scrollPane()", 3000);
		//setTimeout(function(){setInterval("scrollPane()", 3000);}, 3000);
		
		
		$(window).resize(function() {
			loadScrollPane();
		});
		
		
	}	
	
	if(section == 'faq') {
		// accordion home
		$('#accordion').accordion({
			autoHeight: false,
			active: false,
			alwaysOpen: false,
			collapsible: true 
		});
	}
	
	if(section == 'mega-impianto-solis') {
		$('#megaimpianto').preloadify({ imagedelay:500 });
		
		$('#megaimpianto').find('a.megaImpiantoBoxes')
			.each(function(){
				$(this)
					.mouseenter(function(e){
						$(this).find('img').animate({'top': '-=100'});
						//$(this).find('img').css('top', -100);
					})
					.mouseleave(function(e){
						$(this).find('img').animate({'top': '0'});
						//$(this).find('img').css('top', 0);
					});
			});
		$('#megaimpianto').find('a.tipis').qtip({
			position: {
               my: 'bottom center', // Use the corner...
               at: 'top center' // ...and opposite corner
            }
		});
		
		posiziona();
		$(window).resize(function() {
			loadScrollPane();
			posiziona();
		});
	}
	
	
	
	// pulsanti stampa
    //printButtons('a.print');
    
    // menu fix per IE 6
    //loadNavbar('#nav ul.main li');
    
	// Carousel pubblicità e comunicazione    
    $('#slidesItems').jcarousel({auto:0, scroll:1, wrap: 'none', initCallback:mycarousel_initCallback, buttonNextHTML:null, buttonPrevHTML:null});
    
    // uniform
    //$('button, input, textarea, select', '#content').uniform(); 
    
    // nasconde/mostra il testo 'cerca' nel form
    showSearchText('input.src_text');
	
	// equalHeights
	//equalHeights('#impianti ul li p');  
    
    // fancybox
    addFancyBox('a.zoompage, a.zoom, a.zoomtxt, p.mp3 a, a.banner');
    
    // social
    //$('div.social').find('a.btn').click(function(e){ e.preventDefault(); condividi(this.rel); });

    // google map
    loadMap("#map");
	
	
	// login
	if ($('#login-box')){
		$('li.login').click(function() {
			$('#login-box').toggle();
		});
	}
	

});

$(window).load(function(){});

function posiziona()
{
  var txtWidth = $('#centralText').width(),
      txtCont = $('#megaimpianto').width();

  $('#centralText').css('left', ((txtCont/2) - (txtWidth/2)) - 30);
}

function mycarousel_initCallback(carousel)
{
	
	// navigazione (sommo uno perchè il carousel inizia da q e non da 0)
	$('.bullets .bull a').bind('click', function(e) {
		e.preventDefault();
		numScroll = ($(this).text() * 2) + 1;
		carousel.scroll(numScroll);
		$('.bullets a').removeClass('current');
		$(this).addClass('current');

	});

	$('.bullets li.next a').bind('click', function(e) {
		e.preventDefault();
		carousel.next();

	});

	$('.bullets li.prev a').bind('click', function(e) {
		e.preventDefault();
		carousel.prev();
	});

}

function tabs(str){
	var $tabBox = $('#'+str),
		$panels = $tabBox.find('div.panel'),
		$tabs = $tabBox.find('li.tab');
	$tabs.find('a').click(function(e){
		e.preventDefault();
		var tId = $(this).parent().attr('id').substring(3);
					
		$panels.each(function(){
			var $this = $(this),
				pId = $this.attr('id').substring(5);
			if (tId != pId) {
				$(this).addClass('hidden');
				$('#tab'+ pId).removeClass('current');
			} else {
				$(this).removeClass('hidden');
				$('#tab'+ pId).addClass('current');
			}
		});
		
	});	
}

/* logo flash */
function flashLogo()
{
	$('#flashLogo').flash({
		src: baseUrl+'logo.swf',
		width: 111,
		height: 120,
		wmode: 'transparent',
		quality:'high'
	});
};

// check if device is iPhone/iPod
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

// check if device is iPad
function isiPad(){
    return (navigator.platform.indexOf("iPad") != -1);
}

// Aggiunge fancybox
function addFancyBox(els)
{	
	$(els).each(function(){
        $this = $(this);
		
		if ($this.hasClass('zoom') && !$this.hasClass('hidden')) {
			$this.prepend('<span class="lens">&nbsp;</span>');
		}
		
		if ($this.hasClass('banner')) {
			$this.fancybox({
				'width': 610,
				'height': 470,
				'transitionIn': 'fade',
				'transitionOut': 'fade',
				'type': 'iframe',
				'autoScale': true,
				'href': this.href
			});
			
		} else if($this.parent().hasClass('mp3')) {
            $this.fancybox({
                'width': 360,
                'height': 22,
                'type': 'swf',
                'padding': 0,
                'href': baseUrl +'lib/mediaplayer/player.swf?autostart=true&volume=100&file='+ this.href,
                'transitionIn'    : 'elastic',
                'transitionOut'    : 'elastic'
            }); 
			
        } else {
            $this.fancybox({
				'titlePosition': 'over',
				'overlayShow'  : false,
				'transitionIn' : 'elastic',
				'transitionOut': 'elastic',
				'titleFormat'  : function(title, currentArray, currentIndex, currentOpts) 
					{
						if(currentArray.length > 1) {
						return '<p id="fancybox-title-over">'+
							   '<span class="right">Immagine ' + (currentIndex + 1) + ' / ' + currentArray.length + '</span>' +
							   '<strong>'+ title +'</strong>'+
							   '</p>';
						}
					}
			});
        }
    });
	
}


// Mostra/nasconde il testo nelle searchbox
function showSearchText(els)
{
    if ($(els).length > 0) {
        $(els).each(function(i){ 
            var oldTxt = defaultSearchText;
            this.value = oldTxt;
            $(this).focus(function(){
                if (this.value == oldTxt) {
                    this.value = '';
                }
            }).blur(function(){
                if (this.value == '') {
                    this.value = oldTxt;
                }
            });
        });
    }
}

// Carica il menu di navigazione
function loadNavbar(els)
{
    $(els).each(function(){
        $(this)
        .mouseenter(function(e){
                e.preventDefault();
                $(this).addClass('hover')
            })
        .mouseleave(function(e){
                e.preventDefault();
                $(this).removeClass('hover');
            });
    });
}

// Antispam per le email
function emailProtection(elClass)
{
    $(elClass).each(function(){
        var el = $(this);
        var mail = el.text().replace('[AT]','@');
        var text = el.attr('title') || mail;
        var a = $("<a>", {
            "class": elClass.substring(1),
            "href": 'mailto:' + mail,
            text: text
        });
        el.replaceWith(a);
    });
}

// Aggiunge l'azione "stampa"
function printButtons(elClass)
{
    $(elClass).click(function(e){
        e.preventDefault();
        window.print();
    });
}

// Converte un oggetto in string
// eg. {'key1':'value1','key2','value2'} -> key1=value1&key2=value2 
function object2String(obj) {
    var val, sep1 = "=", sep2 = "&", output = "";
    if (obj) {    
        for (var i in obj) {
            val = obj[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += i + sep1 + array2String(val) + sep2;
                    } else {
                        output += i + sep1 + object2String(val) + sep2;
                    }
                    break;
                case ("string"):
                    output += i + sep1 + val + sep2;
                    break;
                default:
                    output += i + sep1 + val + sep2;
            }
        }
        output = output.substring(0, output.length-1);
    }
    return output;
}

function condividi(via)
{
    var url = '',
        pageUrl = encodeURIComponent(document.location.toString()),
        pageTitle = encodeURIComponent(document.title.toString());

    switch(via){
        case 'facebook':
            url = 'http://www.facebook.com/sharer.php?u=' + pageUrl + '&amp;t=' + pageTitle;
        break;
        
        case 'twitter':
            url = 'http://twitter.com/home?status=' + pageTitle + ':+' + pageTitle;
        break

        case 'digg':
            url = 'http://digg.com/submit?url=' + pageUrl;
        break;

        case 'myspace':
            url = 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + pageUrl;
        break;

        case 'buzz':
            url = 'http://www.google.com/reader/link?url='+ pageUrl +'&title='+ pageTitle;
        break;
        
        case 'delicious':
            url = 'http://del.icio.us/post?url='+ pageUrl +'&title='+ pageTitle;
        break;
    
        case 'friendfeed':
            url = 'http://friendfeed.com/share/bookmarklet/frame#title=' + pageTitle + '&url=' + pageUrl;
        break;
                    
        case 'oknotizie':
            url = 'http://oknotizie.virgilio.it/post?url='+ pageUrl +'&title='+ pageTitle;
        break;
    }

    if (url != '') { //console.log(pageUrl, pageTitle);
        window.open(url, '_blank', 'scrollbars=yes,menubar=no,border=0,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); 
    }
}

// Imposta la stessa altezza agli elementi in una riga
function equalHeights(sel)
{
    var currentTallest = 0,
         currentRowStart = 0,
         rowDivs = new Array(),
         $el,
         topPosition = 0;
    
     $(sel).each(function() {
    
       $el = $(this);
       topPostion = $el.position().top;
    
       if (currentRowStart != topPostion) {
    
         // we just came to a new row.  Set all the heights on the completed row
         for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
           rowDivs[currentDiv].height(currentTallest);
         }
    
         // set the variables for the new row
         rowDivs.length = 0; // empty the array
         currentRowStart = topPostion;
         currentTallest = $el.height();
         rowDivs.push($el);
    
       } else {
    
         // another div on the current row.  Add it to the list and check if it's taller
         rowDivs.push($el);
         currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
    
      }
    
      // do the last row
       for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
         rowDivs[currentDiv].height(currentTallest);
       }
    
     });
}

// Carica la mappa
function loadMap(el)
{
    var map = $(el),
		markers = [];
	
    if(map.length > 0) {
		
		map.find('ul').each(function(){
			var $this = $(this),
				lat   = parseFloat($this.find('li.lat span').text()),
				lon   = parseFloat($this.find('li.lon span').text()),
				txt   = $this.find('li.text').html();				
			markers.push({ 
                latitude:  lat,
                longitude: lon,
                popup:     false,
                html:      txt,
                icon:      {
								image:              baseUrl +'solis-marker.png',
								iconsize:           [90,58],
								iconanchor:         [26,58],
								infowindowanchor:   [16,0]
							}
            });
			
		});		
        map.gMap({
            controls: ["GSmallMapControl", "GMapTypeControl"],
            markers:  markers,
			scrollwheel: false,
            zoom: 10 
        });
    }
}

