$(document).ready(function(){

    jQuery.fn.extend({
        /**
         * Add Dropp Shadow
         */
        dropShadow:function(){
            var e = $(this).wrapInner( '<div class="sh-1"><div class="sh-2"><div class="sh-3"><div class="sh-4"></div></div></div></div>')
                    .addClass('has-drop-shadow'); 
            $('.sh-1', this).prepend('<div class="c-a"></div><div class="c-b"></div>');
            return e;
        }
    });


jQuery.extend({
    commentsInit:function(trigger_selector){
        /**
         * Load the comments and form
         */
        var loader_html = '<div class="comment-loader"></div>';

        trigger_selector.each(function(i, el){

            var trigger = el;
            var loader = $(loader_html).insertAfter(el);
            var dummy = $('.comment-link', el).eq(0);
            var count = $('.count', trigger);

            $(el).css('cursor', 'pointer').click(function(){

                if($(trigger).data('commentsLoaded')){

                    dummy.slideToggle();
                    loader.slideToggle();                     

                    if(count.hasClass('count-open')){
                       count.removeClass('count-open'); 
                    } else {
                       count.addClass('count-open');
                    }

                }
                else
                {
                    dummy.toggle();
                    count.addClass('count-open');
                    var url = $('a', el).attr('href');
                    $(loader).load(url, {}, function(){
                        $(el).data('commentsLoaded', true);
                        $.commentsSetup(loader);
                        $("input[name='name']", loader).focus()
                    });
                }

                return false;

            });

        })

    },

    commentsSetup:function(loader){
        /**
         * Init the comments form
         */
        var comments = $('.comments li', loader);
        var body = $(loader)
        var form = $('form', loader);

        var trigger = this; 

        var status = $('<span class="status"></span>').insertBefore(form);

        function validate(){

            var valid = true;
            var default_error_message = "This field is required";
            var errors = {};
            var name = $("input[name='name']", form);
            var comment = $("textarea[name='comment']", form);

            if($.trim(name.val()) == '') {
                valid = false ; 
                errors.name = default_error_message ;
            }
            if($.trim(comment.val()) == '') {
                valid = false ; 
                errors.comment = default_error_message ;
            }
            return valid ? false : errors;

        }

        form.submit(function(){

            var action_url = form.attr('action');
            var data = form.serialize();
            var errors = validate();

            $(form, 'input, textarea').removeClass('error');

            if(errors != false) {

                for(var n in errors){
                    var f = $("[name='" + n + "']", form);
                    f.addClass('error');
                } 

            }
            else {

                status.html('Posting comment, please wait ...').show();
                form.hide();

                $.ajax({

                    url:action_url, 
                    type:"POST",
                    data:data, 
                    dataType:"json",
                    success:function(data){

                        if(data['status'] == 'ok')  form[0].reset();
                        if(data['message'])         status.html(data['message'])

                        setInterval(function(){
                            status.fadeOut(function(){
                                form.slideDown();    
                            });
                        }, 2000);

                    }

                });
            }
            return false

        });

    }
})

// Set container width to columns to avoid floats wrapping
$('#container').css("width", $('.gs-col').length * 238);

// Init dropp shadows 
$('.gs-widget, .gs-pane').dropShadow();


// Initialize scrollable regions
$('.gs-widget .scrollable').jScrollPane({
    showArrows:true,
    scrollbarWidth:17,
    dragMinHeight:20
});


/* Initialize all widgets */
$('.gs-widget').gswidget();

var screen_height = $(window).height();

/* Make widgets sortable */
$('.gs-col').sortable({
    connectWith: '.gs-col',
    //grid:GS.SNAP_GRID_SIZE,
    items: '.is_draggable',
    handle:'.gs-widget-header', 
    delay:150,
    revert:true,
    revertDuration:100,
    cursor:'move',
    update:function() { },
    start:function(){
        $('.gs-col').css({'padding-bottom' : 100});
    },
    stop:function(){
        $('.gs-col').css({'padding-bottom' : 0});
    }
});                


// Save order
GS.positionSave();


// Make floating widgets draggable 
$('#nav-widget').draggable({
    grid:GS.SNAP_GRID_SIZE
})


function layout(){
    var width = $(window).width();
    var height = $(window).height(); 
    screen_height = height;
    var nav = $('#nav-widget');
    var nw = parseInt(nav.css('left').replace('px', '')) + nav.width(); 
    var nh = parseInt(nav.css('top').replace('px', '')) + nav.height(); 
    Log(width + ' ' + nw);
    if(nw > width)
        nav.css('left', width-nav.width());
    if(nh > height)
        nav.css('top', height-nav.height());
}


$(window).resize(function(){
    layout();
});


layout();

// Floating Navigation 
var nav = $('#nav_widget').eq(0);

$('.nav .open').click(function(){ 
    trackEvent('Nav', 'Open all', '', '')
    GS.open(true); return false;
});

$('.nav .close').click(function(){ 
    trackEvent('Nav', 'Close all', '', '')
    GS.close(); return false;
});

$('.nav .refresh').click(function(){ 
    trackEvent('Nav', 'Refresh', '', '')
    GS.positionRestore(); return false; 
});
// $('.nav .more').click(function(){ GS.more(); return false; });


// Setup history
GS.addHistory = function(url){
    var u = url.replace(/^http:\/\/[^/]+\//, '');
    Log('Add: ' + u);
    window.location.href = '#' + u;
    //$.history.load(u);
}

// Callback for history 
function historyCallback(url){
    if(url){
        var segs = url.split('/')
        var widget = segs.shift();
        Log('History: ' + url);
        Log('Widget: ' + widget);
        Log('Vars: ' + segs);
        var matches = GS.getWidgetsByClass(widget);
        if(matches.length > 0){
            // matches[0].loadFromHistory({url:url, vars:segs}); 
        }
    }
};
$.history.init(historyCallback);


// Init Screensaver 
GS.screensaverInit(30 * 60000);


}); // close onload


var Calendar;

(function(){
    var caches = {};
    $.extend({
        calendar:function(conf){

            // this is the current date
            var current_date = new Date(); 

            // these are labels for the days of the week
            var cal_days_labels = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];

            // these are human-readable month name labels, in order
            var cal_months_labels = ['January', 'February', 'March', 'April',
                                 'May', 'June', 'July', 'August', 'September',
                                 'October', 'November', 'December'];

            // these are the days of the week for each month, in order
            var cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

            var html = []; 

            // Defaults
            $.extend({
               month:current_date.getMonth(),
               year:current_date.getFullYear(),
               selected_date:current_date,
               days_outside:true
            }, conf);

            // Return object
            var ret = { 
                year:conf.year,
                month:conf.month
            }

            // get first day of month
            var firstDay = new Date(conf.year, conf.month, 1);
            var startingDay = firstDay.getDay();
              
            // find number of days in month
            var monthLength = cal_days_in_month[conf.month];

            var prevMonthLength = cal_days_in_month[conf.month-1 < 0 ? 11 : conf.month-1]
            Log('Prev month length');
              
            // compensate for leap year
            if (conf.month == 1) { // February only!
              if((conf.year % 4 == 0 && conf.year % 100 != 0) || conf.year % 400 == 0){
                  monthLength = 29;
              }
            }
            if (conf.month-1 == 1) { // February only!
              if((conf.year % 4 == 0 && conf.year % 100 != 0) || conf.year % 400 == 0){
                  prevMonthLength = 29;
              }
            }
              
            // do the header
            var monthName = cal_months_labels[conf.month]
            ret.monthName = cal_months_labels[conf.month]
            html.push('<table class="calendar-table" cellspacing="0" cellspacing="0">');
            //html.push('<tr><th colspan="7">');
            // Add month name
            //html.push(monthName + "&nbsp;" + conf.year);
            //html.push('</th></tr>');
            html.push('<tr class="calendar-header">');
            for(var i = 0; i <= 6; i++ ) {
              html.push( '<th>' + cal_days_labels[i] + '</th>');
            }
            html.push('</tr><tr>');

            // fill in the days
            var day = 1;
            var prevDay = startingDay > 0 ? prevMonthLength-(startingDay)+1 : 0;
            var postDay = 1;
            // this loop is for is weeks (rows)
            for (var i = 0; i < 9; i++) {
              // this loop is for weekdays (cells)
              for (var j = 0; j <= 6; j++) { 
                if (day <= monthLength && (i > 0 || j >= startingDay)) {
                  html.push('<td class="calendar-day">');
                  html.push(day < 10 ? '0' + day : day);
                  day++;
                }
                else if(j < startingDay && day <= monthLength){
                  html.push('<td class="disabled">');
                  html.push(prevDay < 10 ? '0' + prevDay : prevDay);
                  prevDay++;
                }
                else {
                    html.push('<td class="disabled">');
                    html.push(postDay < 10 ? '0' + postDay : postDay);
                    postDay++;
                }
                html.push('</td>');
              }
              // stop making rows if we've run out of days
              if (day > monthLength) {
                break;
              } else {
                html.push('</tr><tr>');
              }
            }
            html.push('</tr></table>');
            ret.html = html.join('');
            return ret;
        }
    });
})();


// Align nav widget
$(window).ready(function(){
    //$('.gs-widget').show();
    $('#site-loading').remove();
    $('body').removeClass('gs-loading').addClass('gs-loaded');
    // Set nav widget position
    var o = $('.gs-col:last .gs-widget:last').offset();
    var h = ($('.gs-col:last .is_open').length * 238)
            + ($('.gs-col:last .gs-widget').not('.is_open').length * 54) + 10;
    $('#nav-widget').css({
        'left' : o.left + 7,
        'top' : h
    });
});




