$(document).ready(function (){
    if ($('DIV').is('.products .box')){
        var items = $('.products .box');
        var i=1;
        $.each(items,function(){
            if(i%3 == 0) {
                $(this).after("<div style='clear:both;'></div><div class='hr1'></div>");
                $(this).css('border-right','none');
            }
            i++;
        });
        if( (items.length % 3)<2) {
            $('.products .box').last().after("<div class='box'></div>");
        }
    }   

    if ($('DIV').is('#people .box')){
        var container=('#people');
        var selector= '#people .box'
        var items = $(selector);
        var i=0;
        var cols = 4;
        var module=(items.length % cols);
        for(y=0;y<cols;y++){
            $(container).append("<div id='col"+y+"' class='container one_col'></div>");
        }
        $.each(items,function(){
            id='#col'+(i%cols);
            $(this).appendTo($(id));
            i++;
        });
        /*
        if(module<cols-1 && !(module==0) ) {
            for(i=0;i<=module;i++){
                $(selector).last().after("<div class='box'></div>");
            }
        }
        */
        $('.hilink').click(function(){
            $(this).parent().css('height',"auto");
            //$(this).parent().parent().css('height',"auto");
            $('.one_col').css('height',"auto");
            $(this).parent().find('.toggle').toggle();
            equalHeight($('.one_col'));

            if($(this).text()=="+MORE"){
                $(this).text("-LESS");
            } else {
                $(this).text("+MORE");
            }
            return false;
        });

        // Wait for images being loaded
        $('body').waitForImages(
            function() {
                setTimeout(function(){
                    equalHeight($('.equal'));
                    equalHeight($(selector)); 
                    equalHeight($(".container"));
                    equalHeight($('.one_col'));
                }, 200);
            },
            function(loaded, total) {
                // Actions to do during loading
            }
        );

    }
    
    if ($('DIV').is('.rack .map')){
        for(i=1;i<$('.rack .map').length+1;i++){
            initializeMap('map',i);
        }
    }

    //last_blog();
    last_tweets();
    waitAjax();
});

var blog_done=false;
var tweet_done=false;
var equalized=false;

function waitAjax(){
    if(!equalized) {
        if(!equalized && (!tweet_done || !blog_done)) {
            setTimeout(waitAjax, 50)
            return;
        }
        equalizeColumns();
    }
}

var mesi_it = new Array( 'Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre');

function equalizeColumns(){
    if ($('DIV').is('.box')){
        equalHeight($(".box"));
    }
    if ($('DIV').is('.container')){
        equalHeight($(".container"));
    }
    equalized=true;
}

function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
            var thisHeight = $(this).height();
            if(thisHeight > tallest) {
                    tallest = thisHeight;
            }
    });

    return group.each(function() {
            $(this).height(tallest);
    });

   // group.height(tallest);
}

function strelapsed(data) {

    t = (data.getTime()/1000);

    var foo = new Date;
    var unixtime_ms = foo.getTime();
    var now = parseInt(unixtime_ms / 1000);

    t = now-t;
    if (t < 60) {
        return t+" secondi";
    }
    if (t < 3600) {
        m = Math.floor(t/60);
        if(m == 1)
                return m+" minuto";
        else
                return m+" minuti";
    }
    if (t < (3600*48)) {
        h = Math.floor(t/3600);
        if(h == 1)
                return h+" ora";
        else
                return h+" ore";
    }
    d = Math.floor(t/(3600*24)); if(d == 1)
                return d+" giorno";
        else
                return d+" giorni";
}

function autolink(text) {
  link=text.replace(/(https?:\/\/[-\w\.]+:?\/[\w\/_\-\.]*(\?\S+)?)/g, "<a href='$1'>$1</a>");
  return link;
}

function massageTweet(text) {
  text = text.replace(/^.* @\w+: /, "");

  return autolink(text);
}

function last_tweets() {
    var $last_tweets = $("#last_tweets");
    if ($last_tweets.length == 0) return;

    var $ul = $last_tweets.find("ul");
    var count = parseInt($last_tweets.attr("tweet-count")) || 4;
    var username;
    var url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=false&include_rts=false&screen_name=simplicissimus&count='+count+'&callback=?';

    $.ajax({  
        url: url,  
        dataType: 'json',  
        async: false,  
        success: function(res){  
            //success code  
            $.each(res,function() {
                d=new Date(this.created_at);
                data=strelapsed(d)+ " fa";
                username=this.user.screen_name;
                text=this.text;

                tweet = "<li onclick=\"window.location=$(this).find('a').attr('href');\">" +
                        "<a href='http://twitter.com/"+username+
                            "/statuses/"+this.id_str+"' title='"+username+"'>"+username+":</a> "+
                            massageTweet(text)+"<br>"+
                            "<a href='http://twitter.com/"+username+
                                "/statuses/"+this.id_str+"' title='"+username+"'>"+
                                "<span class='date'>"+data+"</span>"+
                                "</a>"+
                        "</li>";
                $ul.append(tweet);
            });
        },
        complete: function () {
            tweet_done=true;
        }
    });

}

function last_blog(){
    var $last_blog = $("#last_blog");
    if ($last_blog.length == 0) return;
    var $div = $last_blog.find("div");
    var count = parseInt($last_blog.attr("post-count")) || 4;

    $.jGFeed('http://www2.simplicissimus.it/feed',
        function(feeds){
            if(!feeds) return;
            $.each(feeds.entries,function() {
                d=new Date(this.publishedDate);
                data=d.getDate()+" "+mesi_it[d.getMonth()]+" "+d.getFullYear();
                text = this.title.replace(/\[.*\]/, "");
                $div.append(
                    "<a href='"+this.link+"'>"+
                        "<div>"+
                            "<span class='from'>Da: <span class='red'>"+this.author+"</span></span><br>"+
                            "<span class='date'>"+data+"</span>"+
                            "<p>"+text+"</p>"+
                        "</div>"+
                    "</a>"
                );
            });
        }, count);
}

(function($){
  $.extend({
    jGFeed : function(url, fnk, num, key){
        // Make sure url to get is defined
        if(url == null) return false;
        // Build Google Feed API URL
        var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
        if(num != null) gurl += "&num="+num;
        if(key != null) gurl += "&key="+key;

        $.ajax({  
            url: gurl,  
            dataType: 'json',  
            async: false,  
            success: function(data){  
                //success code  
                if(typeof fnk == 'function') {
                    fnk.call(this, data.responseData.feed);
                } else {
                    return false;
                }
            },
            complete: function () {
                blog_done=true;
            }
        });
    }
  });
})(jQuery);





var maps = Array();
var infowindow = Array();
var marker = Array();

function initializeMap(id,n) {
    
    var lat = $('#'+id+n).attr("lat");
    var lon = $('#'+id+n).attr("lon");
    var title = null; //$('#'+id+n).attr("title");
    var content = $('#'+id+n).attr("content");

    var myOptions = {
        center: new google.maps.LatLng(lat, lon),
        mapTypeControl: false,
        streetViewControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    
    maps[n] = new google.maps.Map(document.getElementById(id+n),myOptions);
    locations=Array({'title':title,'lat':lat,'lon':lon,'n':1,'content':content});

  var bounds = new google.maps.LatLngBounds();
  var image = new google.maps.MarkerImage('images/pointpin.png',
      new google.maps.Size(16, 20),
      new google.maps.Point(0,0),
      new google.maps.Point(4, 20));
  var shadow = new google.maps.MarkerImage('images/pointflag_shadow.png',
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML <area> element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [
        1, 1,
        1, 18,
        8, 18,
        8 , 1
      ],
      type: 'poly'
  };

        //icon: image,
  for (var i = 0; i < locations.length; i++) {
    var point = locations[i];
    var myLatLng = new google.maps.LatLng(point.lat, point.lon);
    marker[n] = new google.maps.Marker({
        position: myLatLng,
        map: maps[n],
        //shadow: shadow,
        animation: google.maps.Animation.DROP,
        //shape: shape,
        title: point.title,
        zIndex: point.n
    });

    bounds.extend(myLatLng);
    infowindow[n] = new google.maps.InfoWindow({
        content: $('#'+point.content).html()
    });
    google.maps.event.addListener(marker[n], 'click', function() {
        infowindow[n].open(maps[n],marker[n]);
    });
  }
  //map.fitBounds(bounds);
    maps[n].setZoom(15);
//  infowindow.open(map,marker[n]);

}








/*
 * waitForImages 1.3.4
 * -----------------
 * Provides a callback when all images have loaded in your given selector.
 * http://www.alexanderdickson.com/
 *
 *
 * Copyright (c) 2011 Alex Dickson
 * Licensed under the MIT licenses.
 * See website for more info.
 *
 */

;(function($) {
    // Namespace all events.
    var eventNamespace = 'waitForImages';

    // CSS properties which contain references to images. 
    $.waitForImages = {
        hasImageProperties: [
        'backgroundImage',
        'listStyleImage',
        'borderImage',
        'borderCornerImage'
        ]
    };
    
    // Custom selector to find `img` elements that have a valid `src` attribute and have not already loaded.
    $.expr[':'].uncached = function(obj) {
        // Firefox will always return `true` even if the image has not been downloaded.
		    // Doing it this way works in Firefox.
        var img = document.createElement('img');
        img.src = obj.src;
        return $(obj).is('img[src!=""]') && ! img.complete;
    };
    
    $.fn.waitForImages = function(finishedCallback, eachCallback, waitForAll) {

        // Handle options object.
        if ($.isPlainObject(arguments[0])) {
            eachCallback = finishedCallback.each;
            waitForAll = finishedCallback.waitForAll;
            finishedCallback = finishedCallback.finished;
        }

        // Handle missing callbacks.
        finishedCallback = finishedCallback || $.noop;
        eachCallback = eachCallback || $.noop;

        // Convert waitForAll to Boolean
        waitForAll = !! waitForAll;

        // Ensure callbacks are functions.
        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
            throw new TypeError('An invalid callback was supplied.');
        };

        return this.each(function() {
            // Build a list of all imgs, dependent on what images will be considered.
            var obj = $(this),
                allImgs = [];

            if (waitForAll) {
                // CSS properties which may contain an image.
                var hasImgProperties = $.waitForImages.hasImageProperties || [],
                    matchUrl = /url\((['"]?)(.*?)\1\)/g;
                
                // Get all elements, as any one of them could have a background image.
                obj.find('*').each(function() {
                    var element = $(this);

                    // If an `img` element, add it. But keep iterating in case it has a background image too.
                    if (element.is('img:uncached')) {
                        allImgs.push({
                            src: element.attr('src'),
                            element: element[0]
                        });
                    }

                    $.each(hasImgProperties, function(i, property) {
                        var propertyValue = element.css(property);
                        // If it doesn't contain this property, skip.
                        if ( ! propertyValue) {
                            return true;
                        }

                        // Get all url() of this element.
                        var match;
                        while (match = matchUrl.exec(propertyValue)) {
                            allImgs.push({
                                src: match[2],
                                element: element[0]
                            });
                        };
                    });
                });
            } else {
                // For images only, the task is simpler.
                obj
                 .find('img:uncached')
                 .each(function() {
                    allImgs.push({
                        src: this.src,
                        element: this
                    });
                });
            };

            var allImgsLength = allImgs.length,
                allImgsLoaded = 0;

            // If no images found, don't bother.
            if (allImgsLength == 0) {
                finishedCallback.call(obj[0]);
            };

            $.each(allImgs, function(i, img) {
                
                var image = new Image;
                
                // Handle the image loading and error with the same callback.
                $(image).bind('load.' + eventNamespace + ' error.' + eventNamespace, function(event) {
                    allImgsLoaded++;
                    
                    // If an error occurred with loading the image, set the third argument accordingly.
                    eachCallback.call(img.element, allImgsLoaded, allImgsLength, event.type == 'load');
                    
                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };
                    
                });

                image.src = img.src;
            });
        });
    };
})(jQuery);

