/** 
 *  Common scripts file
 *  @version: 1.0 
 *  @require: jquery
 */

$(document).ready(function()
{

    section = $(document.body).attr('id');
	
	
	$('#slideshow').cycle({
		fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		timeout: 5000,  // milliseconds between slide transitions (0 to disable auto advance) 
		speed: 3000,
		delay: -3000, // prima animazione 
		requeueOnImageNotLoaded: true,
		
	});
	
    // protezione antispam per le email
    emailProtection('.email');
    
    // pulsanti stampa
    //printButtons('a.print');
    
    // menu fix per IE 6
    //loadNavbar('#nav ul.main li');
    
    //loadCarousel('div.photogallery ul', {'scroll': 3});
    
    //loadCarousel('#home #slidesItems', {'scroll': 3, 'wrap': 'both', 'initCallback': initCallback, 'buttonNextHTML': null, 'buttonPrevHTML': null});
    
    // uniform
    //$('button, input, textarea, select', '#content').uniform();
	equalHeights('div.description');
	equalHeights('div.bottom-equal');
    
    // nasconde/mostra il testo 'cerca' nel form
    showSearchText('input#sw');
	showSearchText('input#searchA'); 
    
    //$('#tabs').tabs();
    
    // fancybox
    addFancyBox('a.zoom');
    
    // social
    $('div.social').find('a.btn').click(function(e){ e.preventDefault(); condividi(this.rel); });

    // google map
    loadMap("#map");
	
});

$(window).load(function(){});


// Aggiunge fancybox
function addFancyBox(els)
{
    $(els).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 = this.value;
            $(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),
        lat = 0,
        lon = 0,
        html = '';
    if(map.length > 0) {
        lat = map.find('li.lat span').text();
        lon = map.find('li.lon span').text();
        html = map.find('li.text').html();
        map.gMap({
            //controls: ["GSmallMapControl", "GMapTypeControl"],
            markers:  [{ 
                latitude: lat,
                longitude: lon,
                popup: false,
                html: html,
                icon:{
                    image:              baseUrl +'img/mappa.png',
                    iconsize:           [32,36],
                    iconanchor:         [30,25],
                    infowindowanchor:   [30,25]
                },
            }],
            zoom: 16 
        });
    }
}

