
// Reference to logger
var Log, log;

var _pageTracker = null; 
var _GA_UA = 'UA-11407937-1';

function trackURL(url){
    url = url.replace(/^http\:\/\/[^\/]+/, '');
    Log("Track url  " + url);
    pageTracker._trackPageview(url);
}
function trackEvent(category, action, opt_label, opt_value){
    Log("Track event " + category + ' ' + action + ' ' + opt_label + ' ' + opt_value);
    if(opt_label && opt_value)
        pageTracker._trackEvent(category, action, opt_label, opt_value)
    else
        pageTracker._trackEvent(category, action)
}

/**
 * GS class
 */
var GS = {
    SNAP_GRID_SIZE:[16, 16],
    TIMEOUT:30 * 60000,
    widgets:{},    
    templates:{},
    classes:{},
    history:[],
    saved:[],
    data:{},

    register:function(cl, name){
        name = name.toLowerCase();
        GS.classes[name] = cl;
    },

    makeWidgetClass:function(name, o){
        var widget = $.inherit(o, GSWidgetBase)
        GS.register(widget, name);
    },

    getWidgetClass:function(widgetName){
        widgetName = widgetName.toLowerCase();
        if(GS.classes[widgetName])
            return GS.classes[widgetName];
        else {
            Log('No registered class: ' + widgetName);
            return false;
        }
    },

    getWidgetsByClass:function(className){
        var widgets = [];
        for(var i in GS.widgets)
            if(GS.widgets[i].name.toLowerCase() == className.toLowerCase())
                widgets.push(GS.widgets[i]);
        return widgets
    },

    positionSave:function(){
        $('.gs-col').each(function(ci, col){
            GS.saved[ci] = [];
            $('.gs-widget', col).each(function(wi, widget){ 
                GS.saved[ci].push(widget);
            })
        });
    },

    positionRestore:function(){
        // Clear
        var temp = document.createElement('div'); 
        $('.gs-col').each(function(ci, col){
            $('.gs-widget', col).each(function(wi, widget){ 
                $(widget).appendTo(temp);
            });
        });
        // Restore
        $('.gs-col').each(function(ci, col){
            for(var i in GS.saved[ci]){
                Log(GS.saved[ci][i]);
                $(GS.saved[ci][i]).appendTo(col);
            }
        });
        
    },

    navHide:function(){
       $('#nav-widget').fadeOut();
    },

    navShow:function(){
        $('#nav-widget').fadeIn();
    },

    open:function(suppress_large){
        var c = 0;
        for(var i in GS.widgets) {
            c += GS.widgets[i].is_open ? 1 : 0;
        }
        if(c == GS.widgets.length -1) { 
            for(var i in GS.widgets)
                GS.widgets[i].close();
        }
        else {
            for(var i in GS.widgets)
                GS.widgets[i].open(suppress_large);
        }
    },

    close:function(no_transition){

        Log('GS.close');
        var no_trans = no_transition || false;
        var hist = {}
        for(var i in GS.widgets) {
            var widget = GS.widgets[i];
            hist[widget.id] = {
                'is_open' : widget.is_open
            }
            Log('Add hist:' + widget.id + ' ' + widget.is_open);
            GS.widgets[i].close(no_trans);
        }
        GS.history.push(hist);

    },

    restore:function(){
        var hist = GS.history.pop();
        if(hist){
            for(var i in hist) {
                var h = hist[i];
                log('--' + i + ' ' + h.is_open);
                if(GS.widgets[i] && h.is_open) {
                    GS.widgets[i].open();
                }
            }
        }
    },

    more:   function(){ },
    less:   function(){ },
    refresh:function(){ },
    getData:function(key){
        if(key in GS.data){
            return GS.data[key];
        } else {
            return false;
        }
    },

    setData:function(key, data){
        GS.data[key] = data;
    },

    paneClose:function(){
        for(var w in GS.widgets){
            GS.widgets[w].paneClose();
        }
    },

    screensaverTimeout:function(){
        clearInterval(GS.screensaver_id);
        GS.screensaver_id = setInterval(function(){
            $(GS.screensaver).fadeIn(function(){
                $('#container').hide();    
            });
        }, GS.TIMEOUT);
    },
    screensaverInit:function(timout){
        GS.timout = timout || GS.timout
        var me = GS;
        GS.screensaver = $('<div id="screensaver"><div class="controls"></div></div></div>').prependTo('body');        

        $(GS.screensaver).click(function(){
            $('#container').show();    
            $(this).fadeOut();
            me.screensaverTimeout();
        });

        $('body').mousemove(function(){
            GS.screensaverTimeout();
        });
        GS.screensaverTimeout();
    }

}

GS.cache = {
    cache:{},
    timeout:1000 * 30,
    get:function(key){
        if(key in GS.cache.cache)  {
            var d = new Date();
            if(GS.cache.cache[key].expires > d.getTime()){
                Log('Cache hit for: ' + key)
                return GS.cache.cache[key].data;
            } else {
                Log('Cache timeout for: ' + key)
                delete GS.cache.cache[key];
                return false;
            }
        }
        else {
            Log('Cache miss for: ' + key)
            return false;
        }
    },
    set:function(key, val){ 
        Log("Cache set for: " + key);
        var d = new Date();
        GS.cache.cache[key] = {
            data:val,
            expires:d.getTime() + (GS.cache.timeout)
        }
    }
}



/**
 * Page Load
 */
$(document).ready(function(){

// Log container for ie
// if($.browser.msie){ $('<div id="console" style="width:200px"></div>').appendTo('body'); }

// Send log to firebug if not custom console 
Log = function(msg){
    if($.browser.msie) {
        //$('#console').append('<code>' + msg+ '</code>');
    }
    else {
        if('console' in this){
            try{ 
                console.log(msg); 
            } catch(e){ } 
        }
    }
}
log = Log;


/** 
 * Create a widgets 
 * use the title attribute 
 * to signify type
 */
$.fn.extend({
    gswidget:function(){
        this.each(function(){
            var k = $(this).attr('title');
            if(k) {
                var widgetClass = GS.getWidgetClass(k);
                Log('Widgetclass: ' + k);
                var widget = new widgetClass();
                widget.init(this);
                GS.widgets[widget.id] = widget;
                $(this).data('widget', widget);
            }
            return this;
        });
    }
})


GS.templates.WIDGET_TOOLS = '<div class="tools"><a class="close" href="/"> <img  src="/site_media/images/widget_close.gif" alt="Close" /> </a><a class="open" href="#"> <img src="/site_media/images/widget_open.gif" alt="Open" /> </a></div>';
GS.templates.PANE = '<div class="gs-pane"><div class="gs-pane-wrap"><div class="gs-pane-container"></div></div><div>';
GS.templates.PANE_HEADER = '<div class="gs-pane-header"><a class="exit" href="/"><img alt="Exit" src="/site_media/images/pane_exit.png"/></a><h2>People</h2></div>';


/**
 * Widget Base Class
 */
var GSWidgetBase = function(){};
GSWidgetBase.prototype = {
    name:'WidgetBase',
    id:'',
    is_movable:false,
    is_open:false,
    has_large:false,
    has_back:false,
    open_transition:'slideDown',
    close_transition:'slideUp',
    init:function(el)
    {

        this.el = $(el);
        this.widget = this.el;

        this.id = this.el.attr('id');
        this.content = $('.gs-widget-content', el).hide();            
        this.header = $('.gs-widget-header', el);            

        if(this.has_back)
            this.header.append(GS.templates.WIDGET_TOOLS);
        else
            this.header.append(GS.templates.WIDGET_TOOLS);

        this.btn_open = $('.gs-widget-header .open', el);            
        this.btn_close = $('.gs-widget-header .close', el);            

        // Add back arrow
        var arrow_img = document.createElement('img');
        arrow_img.src="/site_media/images/widget_arrow.gif";
        arrow_img.className = "arrow";

        if(this.has_back)  {
            $('.tools', this.header).append(arrow_img);
            this.btn_arrow = $('.tools .arrow', this.el)
        }

        this.addCoreEvents();

        $('.close', this.header).hide();

        if(this.el.hasClass('.is_open')) 
            this.open();
        else
            $('.arrow', this.el).hide()

        Log('Init for: ' + this.el.attr('id') + ' as ' + this.name);

        this.postInit();
    },
    addCoreEvents:function()
    {
        var me = this;
        this.btn_open.unbind().bind('click', function(e){
            trackEvent('Widget', 'Open', 'Name', me.name)
            me.open();                
            return false;
        }) 
        this.btn_close.unbind().bind('click', function(e){
            trackEvent('Widget', 'Close', 'Name', me.name)
            me.close();    
            return false;
        }) 
        if(this.has_back) {
            this.btn_arrow.unbind().bind('click', function(){
                me.backOpen();
                return false;
            });
        }
    },
    toggle_tools:function()
    {
        if(this.is_open) {
            if(!this.has_large)
                $('.open', this.header).hide();
            $('.close, .arrow', this.header).show();
        }
        else {
            $('.arrow', this.header).hide();
            $('.close', this.header).hide();
            $('.open', this.header).show();
        }
    },
    open:function(suppress_large)
    {
        var me = this;
        this.preOpen();
        GS.paneClose();
        if(this.is_open && this.has_large){

            // Open larger repr if available 
            if(!suppress_large) this.largeOpen();

        } else {

            this.content[this.open_transition](function(){
                me.postOpen();
            })

            me.is_open = true;
            me.load();
            me.toggle_tools();

        }
    },
    close:function(no_animation)
    {
        this.preClose();
        var me = this;
        if(no_animation)
            this.content.hide();
        else {
            this.content[this.close_transition](function(){
                me.postClose();
            })
        }
        me.is_open = false;
        me.toggle_tools();
    },
    closeAll:function(){
        GS.close(true);
    },
    paneCreate:function() {
        if(!this.pane) {
            this.pane_id = 'pane-' + this.id;
            this.pane = $(GS.templates.PANE).prependTo('#container').attr('id', this.pane_id).hide().dropShadow();
        }
        return this.pane;
    },
    paneDestroy:function(){
        if(this.pane){
            $(this.pane).remove();
            this.pane = null;
        }
    },
    iframeCreate:function(href, title){
        var me = this;
        if(!this.pane)
            this.paneCreate()
        $('.gs-pane-container', me.pane).html(
            GS.templates.PANE_HEADER + '<iframe class="gs-pane-iframe" src="' + href + '"></iframe>'
        );
        $('.gs-pane-header h2', this.pane).html(title);
        $('.exit', this.pane).click(function(){
            $('.gs-pane-container', me.pane).html('');
            me.paneClose(GS.restore);
            return false;
        });
    },
    paneLoading:function(stat){
        if(stat) {
            $('.gs-pane-wrap', this.pane).addClass('gs-pane-loading');
            $('.gs-pane-container', this.pane).hide();
            this.pane.fadeIn();
        }
        else {
            $('.gs-pane-wrap', this.pane).removeClass('gs-pane-loading');
            //this.paneOpen();
        }
    },

    paneOpen:function(){

        GS.navHide();
        GS.close();

        Log('open pane:' + this.pane.attr('id'));

        if(this.pane){
            this.el.hide();
            this.pane.fadeIn(function(){
                $('.gs-pane-container', this.pane).slideDown();
            });
        }

    },

    paneClose:function(completeFunc){
        GS.navShow();
        if(this.pane){
            var me = this;
            this.el.show();
            $('.gs-pane-container', this.pane).slideUp(function(){
                me.pane.fadeOut();    
                if(completeFunc) {
                    completeFunc();
                }
            });
            me.postPaneClose();
        }
    },
    loadFromHistory:function(){ },
    preOpen:function(){ },
    preClose:function(){ },
    postInit:function(){ },
    postOpen:function() { },
    postClose:function(){ },
    postPaneClose:function(){ },
    largeOpen:function(){ },
    backOpen:function(){ },
    load:function() { }
}


$.extend({
    inherit:function(child, parent){
        var F = function(){};
        F.prototype = $.extend(F, parent.prototype, child);
        return F;
    }
});


// Text 
var GSWidget_Text = $.inherit({
    'name' : 'Text',
    'has_large' : false 
}, GSWidgetBase);
GS.register(GSWidget_Text, 'Text');


// About
var GSWidget_About = $.inherit({
    'name' : 'About',
    'has_large' : false 
}, GSWidgetBase);
GS.register(GSWidget_About, 'About');

// Twitter
var GSWidget_Twitter = $.inherit({
    'name' : 'Twitter',
    'has_large' : false,
    postInit:function(){

    },
    largeOpen:function(){
        this.paneCreate();
        this.iframeCreate('http://twitter.com/thegreenspace', 'Twitter'); 
        GS.close();
        this.paneOpen();
    }
}, GSWidgetBase);
GS.register(GSWidget_Twitter, 'Twitter');

// YouTube 
var GSWidget_YouTube = $.inherit({
    'name' : 'About',
    'has_large' : true,
    postInit:function(){
       this.paneCreate();
    },
    largeOpen:function(){
        this.iframeCreate('http://www.youtube.com/user/thegreenspace', 'YouTube');
        GS.close();
        this.paneOpen();
    }
}, GSWidgetBase);
GS.register(GSWidget_YouTube, 'YouTube');


// Photoset 
var GSWidget_Photoset = $.inherit({
    'name' : 'Photoset',
    'has_large' : true,
    postInit:function(){
        this.paneCreate();
    },
    postOpen:function(){
        var me = this;
        $('li a', this.content).bind('click', function(){
            me.iframeCreate($(this).attr('href'), 'Flickr');
            me.paneOpen();
            return false;
        });
        var container = $('.photoset-wrap', this.el);
        $('.photoset', this.content).cycle({
            timeout:4000 + (Math.random() * 500),
            fit:false
        });
    },
    largeOpen:function(){
        $('li a:first', this.el).click();
    },
    preClose:function(){
        clearInterval(this.CYCLE_ID);
    }
}, GSWidgetBase);
GS.register(GSWidget_Photoset, 'Photoset');


// Time 
var GSWidget_Time = $.inherit({
    'name' : 'Time',
    'has_large' : false,
    'has_back' : true,
    postInit:function(){
        this.flash_id = 'flash_' + this.id;
        $('.clock', this.el).attr('id', this.flash_id);
        swfobject.embedSWF(
            "/site_media/swf/clock.swf", 
            this.flash_id, "210", "183", "9.0.0","expressInstall.swf",
            {widget_id:this.id}, {}, {}) 
    },
    backOpen:function(){
        try{
            log(this.flash_id);
            $('#' + this.flash_id).map(function(){this.flip()});
        } catch(e){
            log('TimeWidget Error: ' + e.message);
        }
    },
    preClose:function(){
        $('#' + this.flash_id).hide();
    },
    postOpen:function(){
        if(this.flash_id){
            $('#' + this.flash_id).show();
        }
    }
}, GSWidgetBase);
GS.register(GSWidget_Time, 'Time');


// Audio 
var GSWidget_Audio = $.inherit({
    'name' : 'Audio',
    'has_large' : false,
    'has_back' : true,
    postInit:function(){

        var me = this;

        // Get audio file list
        var playlist_url = $('.playlist', this.el).attr('href');

        this.flash_id = 'flash_' + this.id;

        $('.audio', this.el).attr('id', this.flash_id);

        swfobject.embedSWF(
            "/site_media/swf/audio.swf", 
           this.flash_id, "210", "183", "9.0.0","/site_media/swf/expressInstall.swf",
            {playlist_url : playlist_url}, 
            {widget_id : this.id}, 
            {}
        ) 

    },
    preClose:function(){
        $('#' + this.flash_id).hide();
    },
    postOpen:function(){
        if(this.flash_id){
            $('#' + this.flash_id).show();
        }
    }
}, GSWidgetBase);
GS.register(GSWidget_Audio, 'Audio');


// Weather  
var GSWidget_Weather = $.inherit({
    'name' : 'Weather',
    'has_large' : true,
    postInit:function(){
        var me = this;
        me.paneCreate();
        $('.weather', this.el).cycle({
            timeout:5000 + Math.round(Math.random()*1000)
        }); 
        $('.weather a', this.el).click(function(){
            me.iframeCreate($(this).attr('href'), 'Weather');  
            me.paneOpen();
            return false;
        });
    },
    largeOpen:function(){ }
}, GSWidgetBase);
GS.register(GSWidget_Weather, 'Weather');


// Links 
var GSWidget_Link = $.inherit({
    'name' : 'Link',
    'has_large' : false,
    postInit:function(){

        var me = this;

        this.paneCreate();

        $('.links li ul', this.el).hide(); 

        var triggers = $('.links h3').css('cursor', 'pointer');

        triggers.click(function(){
            triggers.not(this).next().slideUp();
            $(this).next().slideDown();
        })

        $('.links li a').click(function(){
            me.paneOpen();
            me.iframeCreate(this.href, $(this).html());
            return false;
        });

    }
}, GSWidgetBase);
GS.register(GSWidget_Link, 'Link');

// Calendar 
var GSWidget_Calendar = $.inherit({
    'name' : 'Calendar',
    'has_large' : false,
    'has_back' : true,
    postInit:function(){
        var me = this;
        var date = new Date();
        var year = date.getFullYear(); 
        var month = date.getMonth();
        var selected_day = parseInt($('.day td.on', this.el).get(0));
        var date_element = $('.calendar .date', this.el);
        $('.prev', this.el).click(function(){
            if(month == 0){
                month = 11;
                year -= 1;
            } else 
                month -= 1;
            var cal = $.calendar({month:month, year:year});
            $('.calendar-container', me.el).html(cal.html);
            date_element.html(cal.monthName + ', ' + cal.year);
            return false;
        });
        $('.next', this.el).click(function(){
            if(month == 11){
                month = 0;
                year += 1;
            } else 
                month += 1
            var cal = $.calendar({month:month, year:year})
            $('.calendar-container', me.el).html(cal.html);
            date_element.html(cal.monthName + ', ' + cal.year);
            return false;
        });
    },
    backOpen:function(){
        $('.day', this.el).toggle();
    }
}, GSWidgetBase);
GS.register(GSWidget_Calendar, 'Calendar');

// Calendar 
var GSWidget_Contact = $.inherit({
    'name' : 'Contact',
    'has_large' : true,
    lat:51.528246000000003,
    lng:-0.058258999999999998,
    postInit:function(){

        this.paneCreate();
        this.map_pane_id = this.id + '_pane_map';
        $('.gs-pane-container' ,this.pane).append(
            GS.templates.PANE_HEADER + '<div class="info content"></div><div class="map_pane" id="' + this.map_pane_id + '"></div>'
        );
        $('.gs-pane-header h2', this.pane).html('Contact');
        $('.info', this.pane).html($('.info', this.el).html());

        // Initialise maps
        var me = this;
        var map_id = this.id + '_map';

        google.setOnLoadCallback(function(){

            var map = new GMap2(document.getElementById(map_id));
            map.setMapType();
            map.addControl(new GSmallMapControl());
            var position = new GLatLng(me.lat, me.lng);
            map.setCenter(position, 14);

            // Marker
            var blueIcon = new GIcon(G_DEFAULT_ICON);
            var markerOptions = { icon:blueIcon };
            blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
            var marker = new GMarker(position, markerOptions);
            map.addOverlay(marker);

            // Marker click
            GEvent.addListener(marker,"click", function() {
                me.largeOpen();
            });
            
            
        });

    },
    largeOpen:function(){

        var me = this;
        this.paneOpen();

        if(this.street_view_added){
            // Street view already added 
        } 
        else 
        {
            $('a.exit', this.pane).unbind().click(function(){
                me.paneClose(GS.restore);
                return false;
            });

            // Add streetview 
            var mapOptions = { googleBarOptions : { style : "new" } }
            var map = new GMap2(document.getElementById(this.map_pane_id), mapOptions);
            var position = new GLatLng(me.lat, me.lng)
            map.setCenter(position, 14);
            var svOverlay = new GStreetviewOverlay();
            map.setUIToDefault();
            map.enableGoogleBar();
            
            // Marker
            var blueIcon = new GIcon(G_DEFAULT_ICON);
            var markerOptions = { icon:blueIcon };
            blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
            var marker = new GMarker(position, markerOptions);
            map.addOverlay(marker);

            this.street_view_added = true;
        }

    }
}, GSWidgetBase);
GS.register(GSWidget_Contact, 'Contact');

// Webcam 
var GSWidget_Webcam = $.inherit({
    'name' : 'Webcam',
    'has_large' : false,
    postInit:function(){

       // Refresh webcam image         
       var buffer = document.createElement('img');
       var image = $('.image', this.el)
       var image_url = image.attr('src').replace(/\?.*$/, '');

       $(buffer).load(function(){
            image.src = buffer.src 
       }).error(function(){
           // Load failed
       });

       function refresh(){
           var d = new Date();
           var url = image_url + '?' + d.getTime();
           buffer.src = url; 
       }

       this.REFRESH_ID = setInterval(refresh, 5000);

       image.click(refresh);

    }
}, GSWidgetBase);
GS.register(GSWidget_Webcam, 'Webcam');

// People 
var GSWidget_People = $.inherit({
    'name' : 'People',
    'has_large' : true,
    postInit:function(){

        var me = this;

        this.paneCreate();

        $('.people a', this.el).click(function(){
            me.paneOpen();
            me.peopleLoad();
            return false;
        });

        //$('.people li', this.el).hide().eq(0).fadeIn(5000);
        $('.people', this.el).cycle({
            timeout:5000              
        });

    },
    largeOpen:function(){
        $('.people a:first', this.el).click();
    },
    peopleLoad:function(url){
        var me = this;
        if(!url && this.pane_content != null)
            url = '/people/list/'
        else
            url = url || '/people/'
        trackURL(url); 
        var data = GS.cache.get(url)
        if(data)
            me.peopleLoaded(data)
        else
            $.post(url, {}, function(data){
                GS.cache.set(url, data);
                me.peopleLoaded(data);
            });
    },
    peopleLoaded:function(data){
        var me = this;
        if(this.pane_content == null)
        {
            $('.gs-pane-container', this.pane).html(data);
            this.pane_content = $('.gs-pane-content', this.pane);
            $('.gs-pane-header .people,.gs-pane-header .people_all', this.pane).click(function(){
                me.peopleLoad($(this).attr('href'));
                return false;
            })
            $('.gs-pane-header .people', this.pane).click(function(){
                me.peopleLoad('/people/list/');
                return false;
            });
        }
        else
        {
            this.pane_content.html(data);
        }

        // Add exit button
        $('.exit', this.pane).unbind().bind('click', function(){
            me.paneClose(GS.restore);
            return false;
        });

        $('.people-list li', this.pane).hover(function(){
            $(this).addClass('on');
        },function(){
            $(this).removeClass('on');
        });

        $('#people a', this.pane).click(function(){
            me.personLoad($(this).attr('href'));
            return false;
        });
    },
    personLoad:function(url){
        var me = this;
        var data = GS.cache.get(url)
        trackURL(url);
        if(data)
            me.personLoaded(data)
        else
            $.post(url, {}, function(data){
                GS.cache.set(url, data);
                me.personLoaded(data); 
            });
    },
    personLoaded:function(data){
        $('.gs-pane-content', this.pane).html(data);
    }
}, GSWidgetBase);
GS.register(GSWidget_People, 'People');

// Search 
var GSWidget_Search = $.inherit({
    'name' : 'Search',
    'has_large' : false,
    postInit:function(){
        var me = this;
        this.paneCreate();
        $('#search_form').submit(function(){
            var url = this.action;
            var q = $('input[name="q"]', this).val();
            me.iframeCreate(url + '?q=' + q, 'Google Search');
            me.paneOpen();
            return false;
        });
    }
}, GSWidgetBase);
GS.register(GSWidget_Search, 'Search');

// Blog 
var GSWidget_Blog = $.inherit({
    has_large:true,
    postInit:function(){

        var me = this;
        this.paneCreate();

        $('.posts a', this.el).bind('click', function(){
            if(me.pane_content == null)
                me.loadPosts(); 
            me.paneOpen();
            return false;
        });


    },
    largeOpen:function(){
        $('.posts a:first', this.el).click()
    },
    loadPost:function(url){
        var me = this;
        trackURL(url);
        $.post(url, {}, function(data){
            me.postsLoaded(data);
        });
    },
    loadPosts:function(url){
        var me = this;
        url = url || '/blog/'
        trackURL(url);
        $.post(url, {}, function(data){
            me.postsLoaded(data);
        });
    },
    postsLoaded:function(data){

        var me = this;
        if(this.pane_content != null)
        {
            $('.gs-pane-content', this.pane).html(data);
        }
        else
        {
            $('.gs-pane-container', this.pane).html(data);

            // Add exit button
            $('a.exit', this.pane).unbind().bind('click', function(){
                me.paneClose(GS.restore);
                return false;
            });

            var sort_btns = $('.blog_category, .blog_archive, .blog_people', this.pane);
            sort_btns.click(function(){
                sort_btns.not(this).removeClass('on');
                $(this).addClass('on');
                me.loadPosts($(this).attr('href'));
                return false;
            });

            // Sorting buttons
            $('.blog', this.pane).click(function(){
                me.loadPosts($(this).attr('href'));
                return false;
            });

            this.pane_content = $('.gs-pane-content', this.pane);

        }

        $('.gs-pane-header .years a, .gs-pane-header .users a', this.pane).click(function(){
            me.loadPosts($(this).attr('href'));
            return false;
        });

        $('.gs-pane-header .categories a, .posts .categories a', this.pane).click(function(){
            me.loadPosts($(this).attr('href'));
            return false;
        });

        $('.post-title a').click(function(){
            me.loadPosts(this.href); 
            return false;
        });

        // Init comments
        $.commentsInit($('.comment-trigger', this.pane));

    }
}, GSWidgetBase);
GS.register(GSWidget_Blog, 'Blog');

/**
 * Project Widget
 */


/**
 * Work Widget
 */
var GSWidget_Work = $.inherit({
    'name' : 'Work',
    has_large:true,
    loading:function(status){
        if(status) {
            //this.pane_container.addClass('gs-pane-loading');
        }
        else  {
            //this.pane_container.removeClass('gs-pane-loading');
        }
    },
    postInit:function(){

        this.paneCreate();
        this.pane_content = null; 

        var me = this;

        // Single project 
        if($('.work-project', this.el).length > 0) {
            $('.work-project a', this.el).click(function(){
                me.paneOpen();
                me.loadProject(this.href)
                return false;
            });
        }
        else
        {
            $('#projects_small a', this.content).click(function(){
                //me.closeAll();
                me.paneOpen();
                me.loadProjectList();    
                return false;
            });

            $('#projects_small', this.el).cycle({
                timeout:5000 + Math.round(Math.random() * 1000)    
            })
        }
    },

    loadFromHistory:function(obj){
        var me = this;
        //$(document).ready(function(){
            console.debug("load project " + obj.url); 
            me.loadProject(obj.url);
        // }); 
    },

    largeOpen:function(){
        $('#projects_small a:first', this.content).click();
    },

    postOpen:function(){
        // Start slide show of projects   
    },

    loadProjectList:function(obj){

        var me = this;
        obj = obj || {} 
        var filter = obj.filter || '';

        // Do we need to load the whole pane ? 
        if(this.pane_content != null)
        {
            Log('just load projects');
            var url = '/work/projects/';
            trackURL(url);
            var data = GS.cache.get(url);
            if(data)
                me.projectListLoaded(data);
            else 
                $.post(url, {filter:filter}, function(data){
                    GS.cache.set(url, data);
                    me.projectListLoaded(data)
                });
        } 
        else 
        {
           Log('Load whole pane'); 
           var url = '/work/';
           trackURL(url)
           var data = GS.cache.get(url);
           if(data)
                me.projectListLoaded(data)
           else
               $.post('/work/', {filter:filter}, function(data){
                   me.projectListLoaded(data)
               });
        }

    },

    projectListLoaded:function(data){

        var me = this;
        Log('Project list loaded ' + this.pane_content);

        if(this.pane_content != null) 
        {
            // Pane already loaded
            $('.gs-pane-content', this.pane).html(data)
            //this.paneLoading(false);
        }
        else
        {
            // Pane not loaded
            $('.gs-pane-container', this.pane).html(data)
            this.pane_content = $('.gs-pane-content', this.pane);
            this.headerInit();

        }
        this.projectsInit();

    },

    headerInit:function(){

        var me = this;

        //$('.gs-pane-header .exit', this.pane).after('<a href="#" class="next"><img src="/site_media/images/pane_prev.png" alt="" /></a>');
        // 
        this.paneLoading(false);

        $('.work_clients', this.pane).bind('click', function(){
            me.clientsLoad()
            return false;
        })

        $('.work_projects', this.pane).bind('click', function(){
            me.loadProjectList();
            return false;
        });

        $('.work_categories', this.pane).bind('click', function(){
            me.categoriesLoad();
            return false;
        });

        var topnav = $('.work_projects, .work_clients, .work_categories');
        topnav.click(function(){
            topnav.not(this).removeClass('on');
            $(this).addClass('on');
            return false;
        });

        // Add exit button
        $('a.exit', this.pane).unbind().bind('click', function(){
            $('.gs-pane-container', me.pane).slideUp(function(){
                me.paneClose(GS.restore);    
                //me.pane.fadeOut();
            });
            return false;
        });

    },

    projectsInit:function(){

        var me = this;


        // Category Buttons
        $('.categories a', this.pane).unbind().bind('click', function(){
            me.categoryLoad($(this).attr('href'));
            return false;
        });


        // Add the tooltip to the project thumbs
        // NOTE: refactor this to be in side loop below
        $('.projects .media', this.pane).simpletip({
            showEffect:'fade',
            hideEffect:'none',
            onBeforeShow:function(){
                this.update( 
                    '<span>' + $('img', this.getParent()).attr("alt").replace(/,/, '<br />') + '</span>'
                )
            },
            fixed:false,
            offset:[-20, -72]
        });

        // Add the load project events to image and title
        $('.projects > *', this.pane).each(function(i, el){
            $('.media a, a.title', el).click(function(){
                GS.addHistory(this.href);
                me.loadProject(this.href);
                return false;
            })
        })
        .hover(function(){
            $(this).addClass('hover');
            },function(){
            $(this).removeClass('hover');
        });

    },

    loadProject:function(url){
        Log('Load Project ' );
        var me = this;
        trackURL(url);

        if(this.pane_content == null) 
            url = url + '?with_header'

        var data = GS.cache.get(url);
        if(data) {
            me.projectLoaded(data);
        }
        else {
            $.post(url, {},  function(data){
                GS.cache.set(url, data);
                me.projectLoaded(data);            
            });
        }
    },

    render_video:function(obj, el){
        el.html('<div id="media"></div>');
        $(el).animate({height : 500}, function(){
            swfobject.embedSWF(
                "/site_media/swf/player.swf", "media", "934", "500", 
                "9.0.0","/site_media/swf/expressInstall.swf", 
                {video:obj.file, image:obj.image}, 
                {allowfullscreen:true}, 
                {}
            )
        });
    },

    render_image:function(obj, el){
        el.css('height', el.height());
        el.html('<h4 class="caption">' + obj.caption + '</h4>' + '<img src="' + obj.image + '" alt="" />');
        $('img', el).hide().load(function(){
            var im = $(this);
            $(el).animate({height:im.height()}, function(){
                im.fadeIn();    
            });
        });
    },

    render_swf:function(obj, el){
        el.html('<div id="media"></div>');
        $(el).animate({height : 500}, function(){
            swfobject.embedSWF(
                obj.file, 
                "media", "934", "500", "9.0.0",
                "/site_media/swf/expressInstall.swf",
                {}, {}, {}
            )
        });
    },

    get_media_type:function(path){

        var mtypes = {
            'video' : ['flv', 'f4v', 'mp4'],
            'image' : ['jpg', 'jpeg', 'png'],
            'swf' : ['swf']
        }
        var ext = String(path.match(/\.(\w+)$/)[1]);
        for(var t in mtypes) {
            if($.inArray(ext, mtypes[t]) > -1) {
                return t;
                break;
            }
        }
        return false;
    },

    render_media:function(obj, el){
        var html = '';
        var mtypes = {
            'video' : ['flv', 'f4v', 'mp4'],
            'image' : ['jpg', 'jpeg', 'png'],
            'swf' : ['swf']
        }
        if(obj.file){
            var ext = String(obj.file.match(/\.(\w+)$/)[1]);
            for(var t in mtypes) {
                if($.inArray(ext, mtypes[t]) > -1) {
                    this['render_' + t](obj, el);
                    break;
                }
            }
        } else {
            this.render_image(obj, el);
        }
        return false 
    },

    projectLoaded:function(data){

        var me = this; 

        // Add the html
        if(this.pane_content != null) 
        {
            // Pane already loaded
            $('.gs-pane-content', this.pane).html(data)
            this.paneLoading(false);
        }
        else
        {
            // Pane not loaded
            $('.gs-pane-container', this.pane).html(data)
            this.pane_content = $('.gs-pane-content', this.pane);
            this.headerInit();
        }

        // Returned html should set the project media 
        var media_div = $('.media', this.pane);
        var media = []; // GS.getData('project_media');
        var media_count = 0;
        var thumb_max = 13;

        //$('.media li', this.pane).css('position', 'absolute').hide();

        $('.media-thumbs li').each(function(i, el){
            var image = $('.image', el).attr('href');
            var file = $('.file', el).html('').attr('href');
            var caption = $('img', el).attr('alt');
            media.push({
                image:image,
                file:file == undefined ? '' : file,
                caption:caption
            });
        });

        // Init nav if more that one media item 
        if(media.length > 1) { 

            // Media item naviation 
            $('.media-container', this.pane).hover(function(){
                cancelTimeout();
                $('.next, .prev', this).fadeIn();
            },function(){
                timeout();
                $('.next, .prev', this).fadeOut();
            }).find('.next, .prev').hide();

            // Media Thumbs 
            if(media.length > thumb_max) {
                $('.media-thumbs', this.pane).hover(function(){
                    $('.small_medianav a', this).fadeIn();
                },function(){
                    $('.small_medianav a', this).fadeOut();
                }).find('.prev, .next').hide();
            } 

            $('.media-thumbs', this.pane).css({'overflow' : 'hidden'});
            var carousel_pos = 0;
            var itemWidth = 77;
            var items = $('.media-thumbs li', this.pane);
            var len = items.length;
            var container = $('.media-thumbs', this.pane);
            var holder = $('.media-thumbs ul', this.pane).css({'width' : itemWidth * len, 'left' : 0});
            var totalWidth = itemWidth * len;
            var overflow = len - Math.floor(container.width() / itemWidth);

            $('.media-thumbs .next', this.pane).click(function(){
                carousel_pos = carousel_pos > -overflow ? carousel_pos-1 : -overflow; 
                holder.animate({'left' : carousel_pos * itemWidth}, 250);
                $(this).blur();
                return false;
            });
            $('.media-thumbs .prev', this.pane).click(function(){
                carousel_pos = carousel_pos < 0 ? carousel_pos+1 : 0; 
                holder.animate({'left' : carousel_pos * itemWidth}, 250);
                $(this).blur();
                return false;
            });
        } 

        // Hide pagination for thumbs if less then 10 items
        if(media.length < thumb_max) {
            $('.media-thumbs .next, .media-thumbs .prev', this.pane).hide();
        }
        

        // Auto slide image
        timeout = function(){
            /*
            if(media.length > 1){
                if(me.interval_id)
                    clearInterval(me.interval_id);
                me.interval_id = setInterval(function(){
                    media_count = media_count < media.length-1 ? media_count+1 : 0;
                    Log(media + ' ' + media_count);
                    if(!media[media_count].file) 
                        $('.media-thumbs li', me.pane).eq(media_count).click();
                }, 6000);
            }
            */
        }
        cancelTimeout = function(){
            if(me.interval_id)
                clearInterval(me.interval_id);
        }

        // Thumb navigation 
        var media_thumbs = $('.media-thumbs li', this.pane); 

        $('.media-thumbs li', this.pane).click(function(){

            media_count = media_thumbs.index(this); 

            media_thumbs.css('opacity', .5).not(this).css('opacity', 1); 

            me.render_media(media[media_count], media_div);

            if(!media[media_count].file)
                timeout();
            else
                cancelTimeout()

            return false;
        });

        // Large next prev buttons
        if(media.length > 1) {

            $('.media-container .next', this.pane).click(function(){
                media_count = media_count < media.length-1 ? media_count+1 : 0;
                media_thumbs.eq(media_count).click();
                return false;
            });

            $('.media-container .prev', this.pane).click(function(){

                media_count = media_count > 0 ? media_count-1 : media.length-1;
                media_thumbs.eq(media_count).click();
                return false;
            });

        } else {

            $('.media-container .prev, .media-container .next').hide();

        }

        // Load first one
        media_thumbs.eq(0).click();

        // Init comments
        $.commentsInit($('.comment-trigger', this.pane));

    },

    postPaneClose:function(){
        clearInterval(this.interval_id);
    },

    clientsLoad:function(){
        var me = this;
        var url = '/work/clients/';
        trackURL(url)
        GS.addHistory(url);
        var data = GS.cache.get(url);
        if(data)
            me.clientsLoaded(data)
        else
            $.post(url, {}, function(data){
                GS.cache.set(url, data);
                me.clientsLoaded(data)
            })
    },

    clientsLoaded:function(data){
        var me = this;
        $('.gs-pane-content', this.pane).html(data);
        $('.clients a', this.pane).bind('click', function(){
            $.post($(this).attr('href'), {}, function(data){
                me.projectListLoaded(data);
            });
            return false;
        });
        $('.clients img:first-child').hide();
        $('.clients a', this.pane).hover(function(){
            $('img:eq(0)', this).show();
            $('img:eq(1)', this).hide();
        }, function(){
            $('img:eq(1)', this).show();
            $('img:eq(0)', this).hide();
        })
    },

    categoriesLoad:function(){
        var me = this;
        var url = '/work/categories';
        trackURL(url)
        GS.addHistory(url);
        var data = GS.cache.get(url);
        if(data)
            me.categoriesLoaded(data)
        else
            $.post('/work/categories/', {}, function(data){
                GS.cache.set(url, data);
                me.categoriesLoaded(data)
            })
    },

    categoriesLoaded:function(data){
        var me = this;
        $('.gs-pane-content', this.pane).html(data);
        $('.work-categories a', this.pane).click(function(){
            $.post($(this).attr('href'), {}, function(data){
                me.projectListLoaded(data);
            });
            return false;
        });

    },

    categoryLoad:function(url){
        trackURL(url)
        var me = this;
        var data = GS.cache.get(url);
        if(data)
            me.projectListLoaded(data)
        else
            GS.addHistory(url);
            $.post(url, {}, function(data){
                GS.cache.set(url, data);
                me.projectListLoaded(data); 
            })
    }

}, GSWidgetBase);
GS.register(GSWidget_Work, 'Work');
GS.register(GSWidget_Work, 'Project');

// News 
var GSWidget_News = $.inherit({
    'name' : 'News',
    'has_large' : true,
    postInit:function(){
        var me = this;
        this.paneCreate();
        $('.stories a', this.el).click(function(){
            me.loadStory(this.href, this.innerHTML);
            return false;
        });
    },
    loadStory:function(url, title){
        this.paneOpen();
        this.iframeCreate(url, title);
    },
    largeOpen:function(){
        $('.stories a:first').click();
    }
}, GSWidgetBase);
GS.register(GSWidget_News, 'News');


});



