var Color = Color || {};

var __showFilterDialog = true;

(function(){
    var filter = function(){
        var departments = ['skate', 'music', 'art', 'film', 'life', 'fashion', 'magazine'];

        this.hidden = {};
        for(var i in departments) {
            this.hidden[departments[i]] = false;
        }
        
        this.nodes = [];
        
        this.add = function(elem, depts) {
            if(depts.length == 0 || depts[0] == '')
                return;
            
            elem.departments = depts;
            this.nodes.push(elem);
            
            var hide = true;
            for(var d in depts) {
                hide = (this.hidden[depts[d]])? hide: false; // should only be true if all departments that this node has is hidden.
            }
            
            if(hide) {
                $(elem).hide();
            }
        }
        
        this.toggle = function(dept) {
            if(this.hidden[dept]) {
                this.show(dept);
            } else {
                this.hide(dept);
            }
        }
        
        this.hide = function(dept) {
            this.hidden[dept] = true;
            var hide = false;
            for(var i in this.nodes) {
                hide = true;
                for(var d in this.nodes[i].departments) {
                    hide = (this.hidden[this.nodes[i].departments[d]])? hide: false; // should only be true if all departments that this node has is hidden.
                }
                
                if(hide) {
                    $(this.nodes[i]).hide();
                }
            }
        }
        
        this.show = function(dept) {
            this.hidden[dept] = false;
            var show = false;
            for(var i in this.nodes) {
                show = false;
                for(var d in this.nodes[i].departments) {
                    if(this.hidden[this.nodes[i].departments[d]] == false)
                        show = true;
                }
                
                if(show) {
                    $(this.nodes[i]).show();
                }
            }
        }
        
        this.get = function(dept) {
            
        }
    }
    
    Color.filter = new filter();
})();

$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }

        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$.fn.colorPaginator = function(options) {
    var o = $.extend({
        ajax: false,
        nextText: 'Older ►',
        prevText: '◄ Newer'
    }, (options? options : {}));
    
    return this.each(function(){
        var $this = $(this);
        var c = $this.children();
        //if(c.length > 1) {
            var $overlay = $('<div class="overlay"><a class="prev" href="#">'+o.prevText+'</a> / <a class="next" href="#">'+o.nextText+'</a></div>');
            $this.parent().append($overlay).hover(function(){$overlay.fadeIn()}, function(){$overlay.fadeOut()});
            var p = o.ajax? new Ctrl_Paginator_Ajax(c, o) : new Ctrl_Paginator(c, o);
            $overlay.find('a').click(function(){
                if(this.className == 'next')
                    p.next();
                else
                    p.prev();
                return false;
            });
        //}
    });
}

$.fn.colorMenu = function(options) {
    var o = $.extend({
        collapsible: true,
        selected : -1,
        select: function(event, ui) {
            var u = $.data(ui.tab, 'load.tabs');
            var h = location.href;
            if(u) {
                
                if(h.indexOf(u) !== -1 && h.substr(h.indexOf(u)+u.length).match(/|\/?page\/\d+/) !== null) {
                    $(ui.tab).parent().addClass('ui-state-active ui-tabs-selected');
                    return false;
                } else {
                    if(!$(ui.tab).parent().hasClass('ui-state-active')) {
                        location.href = u;
                    }
                    
                    return false;
                }
                
            }
            return true;
        },
        load: function(event, ui) {
            return false;
        }

    }, options);
  
    return this.tabs(o);
}

$(window).bind('load', function(){ // bound to onLoad to make sure it fires after dom ready events, where the nodes are initialized
    // init filter from cookie
    var c = $.cookie('_color_content_filter');
    if(null == c) {
        $.cookie('_color_content_filter', JSON.stringify(Color.filter.hidden));
    } else {
      try { c = JSON.parse(c);} catch(e) { $.cookie('_color_content_filter', JSON.stringify(Color.filter.hidden)); c = Color.filter.hidden;  }
    }
    if(c) {
        __showFilterDialog = false;
        for(var i in c) {
            if(c[i] === true) {
                $('#filter li.'+i+' a').click();
                
            }
        }
        __showFilterDialog = typeof c.__showFilterDialog == "undefined"? true : c.__showFilterDialog;
    }    
});

$().ready(function(){
    var filterDialog = new Ctrl_Dialog({
        contents: '#filter-dialog',
        width: 400,
        height: 200,
        resizable: false,
        draggable: false
    });
    
    $('#filter a').click(function(){
        var $this = $(this);
        var dept = $this.parent().attr('class');
        $this.toggleClass('off');
        Color.filter.toggle(dept);
        $.cookie('_color_content_filter', JSON.stringify(Color.filter.hidden)); //I'd really like to NOT do this here, every time.
        
        var h = [];
        for(var d in Color.filter.hidden) {
            if(Color.filter.hidden[d])
                h.push('<span class="'+ d +'">'+ d +'</span>');
        }
        
        $('.departments', filterDialog.elem).html(h.join(' / '));
        
        if(h.length > 0 && __showFilterDialog && $this.hasClass('off'))
            filterDialog.open();
        
        return false;
    });
    
    $('#show-filter-dialog').change(function(){
        __showFilterDialog = !this.checked;
        c = $.extend(Color.filter.hidden, {__showFilterDialog : false}, {});
        $.cookie('_color_content_filter', JSON.stringify(c));
        
    });
    
    $('div.share').hover(
        function(){ 
            $(this).closest('.post').css({'z-index': 2222}).end().children('.share-inside').show();
        }, 
        function(){ 
            $(this).closest('.post').css({'z-index': 1}).end().children('.share-inside').hide();
        }
    );
    
    // login dialog
    Color.loginDialog = new Ctrl_Dialog_Ajax({
        autoLoad: false,
        resizable: false, 
        draggable: false, 
        width: 675,
        title: 'Log in / Sign up to colormagazine.ca'
    }, Ctrl.Config.baseUrl + '/login?format=html');
    $('#login, a.login').click(function(){ Color.loginDialog.load(function(){Color.loginDialog.open()});  return false; });
    
    $('form.search input')
    .each(function(){ if($(this).val() == '') { $(this).val($(this).attr('title')) } })
    .focus(function() { if($(this).val() == $(this).attr('title')) { $(this).val('').removeClass('tip'); }})
    .blur(function() { if($(this).val() == '') { $(this).val($(this).attr('title')).addClass('tip'); } })
    .parents('form').submit(function() {
        var field = $(this).find('input');
        if(field.val() == field.attr('title'))
            field.val('');
    });
    
});

function ap_stopAll() {};
