/** 
 *  Common scripts file
 *  @version: 1.0 
 *  @require: jquery
 */

$(document).ready(function()
{
	// recupero la sezione
    page = $(document.body).attr('id');
	section = $(document.body).attr('class');
	
	// la sezione "home"
	if(page == 'home') {
		highlightPanel();
		altreAttivita();
		$('#works-slide').jcarousel({
			//start:1, 
			scroll:2, 
			wrap:'both', 
			initCallback:mycarousel_initCallback, 
			buttonNextHTML:null, 
			buttonPrevHTML:null
		});
	};
	
	// sezione "aree-attivita"
	if(page == 'aree-attivita' || section == 'aree-attivita') {
		tabs('activities');
	};
	
	// sezione "portfolio"
	if(section == 'portfolio') {
		altreAttivita();
	};
	
	
	// sezione "contatti"
	if(page == 'contatti') {
		loadMap("#map");
	};
	
	// sezione "lavori-realizzati"
	if(page == 'lavori-realizzati') {
		var frm = $('#searchWork').find('form'),
			btn = frm.find('#s'),
			txt = frm.find('#sw'),
			sel = frm.find('select');
		sel.change(function(){
			if(txt.attr('value') == 'Inserisci la parola chiave') {
				txt.attr('disabled','disabled');
			}
			frm.submit();
		});
		btn.click(function(){
			if(txt.attr('value') != 'Inserisci la parola chiave' && txt.attr('value') != '' && txt.attr('value').length > 2) {
				frm.submit();
			}
		});
		$('#works-slide').jcarousel({
			//start:1, 
			scroll:3,
			//visible:3, 
			wrap:'both', 
			initCallback:mycarousel_initCallback, 
			buttonNextHTML:null, 
			buttonPrevHTML:null
		});
	}   
	
    // protezione antispam per le email
    emailProtection('.cemail, .email');
    
    // pulsanti stampa
    printButtons('a.print');
    
    // menu fix per IE 6
    loadNavbar('#menu ul.main li');
    
    // uniform
    //$('button, input, textarea, select', '#content').uniform(); 
    
    // nasconde/mostra il testo 'cerca' nel form
    showSearchText('input[name="keyword"]'); 
    
    // fancybox
    addFancyBox('a.iframe');
	addFancyBox('a.zoom');
    
    // social
    $('div.shareIcons').find('a.btn').click(function(e){ 
		e.preventDefault(); 
		condividi(this.rel);
	});
	
	$('select.wSec').change(function(){
		
	});

});

$(window).load(function()
{
    // sezione "lavori-realizzati"
	if(page == 'lavori-realizzati' || page == 'clienti-mister-wolf') {
		equalHeights('ul.works li');
	}   
	
	// sezione "aree-attivita"
	if(page == 'aree-attivita') {
		equalHeights('ul.aree li');
	}   
});

function altreAttivita()
{
	$('ul.tipContent').jcarousel({
			vertical: true,
			hoverPause:true,
			auto:3,
			animation:'slow',
			visible:1,
			scroll:1, 
			wrap:'last', 
			buttonNextHTML:null, 
			buttonPrevHTML:null
		});
}

// funzione per i tabs
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');
			}
		});
		
	});	
}

function mycarousel_initCallback(carousel)
{

	// navigazione (sommo 1 perchè il carousel inizia da 1 e non da 0)
	$('.bullets a').bind('click', function() {
		numScroll = ($(this).attr('rel') * carousel.options.scroll) + 1;
		carousel.scroll(numScroll);
		$('.bullets a').removeClass('current');
		$(this).addClass('current');
		return false;
	});	

};

// 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": el.attr('class') || 'mail',//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;
}

// funzione per i social network
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 +'mw-mappa.png',
                    iconsize:           [32,36],
                    iconanchor:         [16,38],
                    infowindowanchor:   [16,0]
                },
            }],
            zoom: 15 
        });
    }
}

// funzione per il blocco "highlight"
function highlightPanel()
{
	var $highlight = $('#highlight'),
		$panels = $highlight.find('div.panel'),
		$tabs = $highlight.find('li.tab');
	// preload..
	$panels.each(function(){
		var src = $(this).css('background-image').replace('url(', 'src=');
		src = src.substring(0,src.length-1);
		$('<img src="'+ src +'" />');
	});
	$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');
			}
		});		
	});		
}
