$(document).ready(function() {
    SmokinApps.init();
});

var SmokinApps = {
    theme_url: '/wp/wp-content/themes/smokinapps',
    
    init: function() {
        SmokinApps.rating.init();
        SmokinApps.filters.init();
        SmokinApps.search.init();
        SmokinApps.submit.init();
        SmokinApps.tabs.init();
        SmokinApps.subscribe.init();
        SmokinApps.links.init();
        SmokinApps.register.init();
        SmokinApps.login.init();
        SmokinApps.review.init();
        SmokinApps.profile.init();
        SmokinApps.single.init();
        SmokinApps.callout.init();
        SmokinApps.featured.init();
        SmokinApps.featured_vert.init();
        
        $.blockUI.defaults.css = {};
        $.blockUI.defaults.overlayCSS = {};
        
        var images = [
            SmokinApps.theme_url + '/img/hovermenu-bg.png',
            SmokinApps.theme_url + '/img/hovermenu-tail.png',
            SmokinApps.theme_url + '/img/star-rating-red.png',
            SmokinApps.theme_url + '/img/star-rating-red-sm.png'
        ];
        SmokinApps.preload_images(images);
        $('#login-bar .explore a').hovermenu($('#login-bar .hovermenu'));

        $('.star-rating').star_rating();
        SmokinApps.rating.events();
    },
    
    preload_images: function(images) {
        for (var i = 0; i < images.length; i++) {
            var img = new Image();
            img.src = images[i];
        }
    },
    
    trunc_title: function(title, max_len) {
        if (max_len < title.length) {
            max_len = max_len - 3;
            var words = title.split(/[ ]+/);
            
            title = '';
            for (i in words) {
                if (max_len >= title.length + words[i].length) {
                    title = title + words[i] + ' ';
                }
            }
            
            title = title.substr(0, title.length-1) + '...';
        }
    
        return title;	
    },

    featured_vert: {
        viewable_items: 3,
        
        init: function() {
            $('.featured-vert .featured-items').each(function() {
                var div = this;

                var max_height = 0;
                $('.post', div).each(function(i){
                    var height = $(this).height();
                    if (height > max_height)
                        max_height = height;
                });
                
                $('.post', div).each(function() {
                    var h = $(this).height();
                    var new_h = $('.subtitle', this).height() + (max_height - h);
                    $('.subtitle', this).height(new_h);
                });
                
                var li_height = $('ul.featured-apps li.post', div).outerHeight();
                
                var li_num = $('ul.featured-apps li.post', div).size();

                if (li_num <= SmokinApps.featured.viewable_items) {
                    return;
                }

                var div_height = li_height * SmokinApps.featured_vert.viewable_items;
                $('.featured-wrap', div).height(div_height);
                
                $('ul.featured-apps', div).css({
                    height: (li_num * li_height) + 'px',
                    top: 0,
                    position: 'relative'
                });
    
                $(div).append('<a href="#" class="control up" style="display:none;">Up</a>');
                $(div).append('<a href="#" class="control down">Down</a>');
                
                $('.up', div).click(function() {
                    SmokinApps.featured_vert.scroll(this, div, 1);
                    return false;
                });
                $('.down', div).click(function() {
                    SmokinApps.featured_vert.scroll(this, div, -1);
                    return false;
                });
            });
        },
        
        scroll: function(button, div, direction) {
            var ul_height = $('ul.featured-apps', div).height();
            var li_height = $('ul.featured-apps li.post', div).outerHeight();
            var stage_height = li_height * SmokinApps.featured.viewable_items;
            var current = $('ul.featured-apps', div).css('top');
            current = parseFloat(current.replace('px', ''));
            var dist = (direction * li_height) + current;
            if (dist % li_height != 0) {
                return;
            }
            if (dist > 0 || ul_height - stage_height < Math.abs(dist)) {
                return;
            }
            $('ul.featured-apps', div).animate({
                top: dist + 'px'
            }, function() {
                var current = $('ul.featured-apps', div).css('top');
                current = parseFloat(current.replace('px', ''));
                $('.control', div).show();
                var dist = (direction * li_height) + current;
                    if (dist > 0 || ul_height - stage_height < Math.abs(dist)) {
                    $(button).hide();
                }
            });
        }
    },
        
    featured: {
        viewable_items: 4,
        
        init: function() {
            $('.featured-horz .featured-items').each(function() {
                var div = this;

                $('.post', div).show();
                
                var max_height = 0;
                $('.post', div).each(function(i){
                    var height = $(this).height();
                    if (height > max_height)
                        max_height = height;
                });
                
                $('.post', div).each(function() {
                    var h = $(this).height();
                    var new_h = $('.subtitle', this).height() + (max_height - h);
                    $('.subtitle', this).height(new_h);
                });
            
                var li_width = $('ul.featured-apps li.post', div).outerWidth();
                var li_num = $('ul.featured-apps li.post', div).size();
                
                $('ul.featured-apps', div).css({
                    width: (li_num * li_width) + 'px',
                    left: 0,
                    position: 'relative'
                });
                
                if (li_num <= SmokinApps.featured.viewable_items) {
                    return;
                }
    
                $(div).append('<a href="#" class="control previous" style="display:none;">Previous</a>');
                $(div).append('<a href="#" class="control next">Next</a>');
    
                
                $('.previous', div).click(function() {
                    SmokinApps.featured.scroll(this, div, 1);
                    return false;
                });
                $('.next', div).click(function() {
                    SmokinApps.featured.scroll(this, div, -1);
                    return false;
                });
            });
        },
        
        scroll: function(button, div, direction) {
            var ul_width = $('ul.featured-apps', div).width();
            var li_width = $('ul.featured-apps li.post', div).outerWidth();
            var stage_width = li_width * SmokinApps.featured.viewable_items;
            var current = $('ul.featured-apps', div).css('left');
            current = parseFloat(current.replace('px', ''));
            var dist = (direction * li_width) + current;
            if (dist % li_width != 0) {
                return;
            }
            if (dist > 0 || ul_width - stage_width < Math.abs(dist)) {
                return;
            }
            $('ul.featured-apps', div).animate({
                left: dist + 'px'
            }, function() {
                var current = $('ul.featured-apps', div).css('left');
                current = parseFloat(current.replace('px', ''));
                $('.control', div).show();
                var dist = (direction * li_width) + current;
                    if (dist > 0 || ul_width - stage_width < Math.abs(dist)) {
                    $(button).hide();
                }
            });
        }
    },
    
    single: {
        init: function() {
            if (!$('#content.single').get(0)) return;
            
            var max_height = 0;
            var count = $('.review').size();
            $('.review').each(function(i){
                var height = $('.content', this).height();
                if (height > max_height)
                    max_height = $('.content', this).height();
                
                if ((i + 1) % 3 == 0 || i == count - 1) {
                    $(this).addClass('review-last');
                    
                    $('.review').each(function(j){
                        if (j < (i - (i % 3)) || j > i) return;
                        $('.content', this).height(max_height);
                    });
                    
                    max_height = 0;
                }
            });
        }
    },

    profile: {
        init: function() {
            if (!$('#content.profile').get(0)) return;
            
            var max_height = 0;
            var post_count = $('.post').size();
            $('.post').each(function(i){
                var height = $(this).height();
                if (height > max_height)
                    max_height = $(this).height();
                
                if ((i + 1) % 4 == 0 || i == post_count - 1) {
                    if ((i + 1) % 4 == 0) {
                        $(this).addClass('post-last');
                    }
                    
                    $(this).after('<div class="post-separator"></div>');
                    
                    $('.post').each(function(j){
                        if (j < (i - (i % 4)) || j > i) return;
                        var h = $(this).height();
                        var new_h = $('.subtitle', this).height() + (max_height - h);
                        $('.subtitle', this).height(new_h);
                    });
                    
                    max_height = 0;
                }
            });

            $('.post').each(function(){
                $('.my-rating .write-review', this).hovermenu($('.hovermenu', this));
            });
        }
    },

    reset_password: {
        popup: function(url) {
            $.get(url + '?ajax=1', function(data) {
                SmokinApps.popup.update(data);
                SmokinApps.reset_password.events();
            });
        },
        
        events: function() {
            $('.blockMsg form').submit(function() {
                var form_data = $('.blockMsg form').serialize();
                $.post('/reset-password/?ajax=1', form_data, function(new_form) {
                    // nothing returned means success
                    if (!new_form) {
                        window.location.reload();
                    }
                    else {
                        SmokinApps.popup.update(new_form);
                        $('.blockMsg form').hide().fadeIn();
                        SmokinApps.reset_password.events();
                    }
                });
                return false;
            });
            
            $('.blockMsg .continue a').click(function() {
                $.unblockUI();
                return false;
            });

            $('.blockMsg input.text').eq(0).focus();
        }
    },

    review: {
        init: function() {
            $('.write-review').click(function() {
                var url = $(this).attr('href') + '&ajax=1';
                SmokinApps.review.popup(url);
                return false;
            });
        },

        popup: function(url) {
            $.get(url, function(data) {
                if (data == 'LOGGED OUT!') {
                    SmokinApps.login.popup(function() { SmokinApps.review.popup(url); });
                    return;
                }
                SmokinApps.popup.update(data);
                SmokinApps.review.events();
            });
        },
        
        events: function() {
            $('.blockMsg form').submit(function() {
                var form = $('.blockMsg form');
                var form_data = form.serialize();
                var url = form.attr('action') + '&ajax=1';
                $.post(url, form_data, function(new_form) {
                    // nothing returned means login success
                    if (!new_form) {
                        window.location.reload();
                    }
                    else {
                        SmokinApps.popup.update(new_form);
                        $('.blockMsg form').hide().fadeIn();
                        SmokinApps.review.events();
                    }
                });
                return false;
            });
            
            $('#send-twitter, #send-facebook').click(function() {
                var field = $(this).attr('id').replace('send-', '');
                field = $('.blockMsg .field-' + field + '-msg');
                if ($(this).attr('checked')) {
                    field.show();
                }
                else {
                    field.hide();
                }
            });

            $('#send-twitter').click(function() {
                SmokinApps.review.update_status_msg('twitter');
            });
            
            $('#send-facebook').click(function() {
                if ($(this).attr('checked')) {
                    FB.ensureInit(function() {
                        FB.Connect.showPermissionDialog('status_update');
                    });
                    SmokinApps.review.update_status_msg('facebook');
                }
            });
            
            $('.blockMsg textarea').eq(0).focus();
        },
        
        update_status_msg: function(service) {
            var tag = '[review]';
            var tmpl = $('#' + service + '-tmpl').val();
            var field = $('#' + service + '-msg');
            var review = $('#review').val();
            
            var max_len = 140 - tmpl.length + tag.length;
            
            review = SmokinApps.trunc_title(review, max_len);
            var msg = tmpl.replace(tag, review);
            
            field.val(msg);
        },
        
        twitter: function() {
            window.open("/wp/wp-content/plugins/twitconnect/start.php?a=&twcver=2&loc=", "twcWindow","width=800,height=400,left=150,top=100,scrollbar=no,resize=no");
        }
    },
            
    login: {
        init: function() {
            $('.button-login').click(function() {
                SmokinApps.login.popup();
                return false;
            });
        },

        popup: function(callback) {
            $.get('/login/?ajax=1', function(data) {
                SmokinApps.popup.update(data);
                SmokinApps.login.events(callback);
            });
        },
        
        events: function(callback) {
            $('.blockMsg form').submit(function() {
                var form_data = $('.blockMsg form').serialize();
                $.post('/login/?ajax=1', form_data, function(new_form) {
                    // nothing returned means login success
                    if (!new_form) {
                        if (callback) {
                            callback();
                        }
                        else {
                            window.location.reload();
                        }
                    }
                    else {
                        SmokinApps.popup.update(new_form);
                        $('.blockMsg form').hide().fadeIn();
                        SmokinApps.login.events();
                    }
                });
                return false;
            });
            
            $('.blockMsg input.text').eq(0).focus();
            
            $('.blockMsg .reset-password a').click(function() {
                var url = $(this).attr('href');
                SmokinApps.reset_password.popup(url);
                return false;
            });

            $('.blockMsg .register a').click(function() {
                SmokinApps.register.popup();
                return false;
            });
        }
    },
    
    callout: {
        init: function() {
            $('.callout .silence .remind').click(function() {
                $.cookie('silence_callout', 1);
                $(this).parents('.callout').eq(0).fadeOut();
                return false;
            });

            $('.callout .silence .permanent').click(function() {
                $.cookie('silence_callout', 1, { expires: 1000 });
                $(this).parents('.callout').eq(0).fadeOut();
                return false;
            });
        }
    },
    
    register: {
        init: function() {
            $('.button-register').click(function() {
                SmokinApps.register.popup();
                return false;
            });
        },
        
        popup: function(update) {
            $.get('/register/?ajax=1', function(data) {
                SmokinApps.popup.update(data);
                SmokinApps.register.events();
            });
        },
        
        events: function() {
            $('.blockMsg form').submit(function() {
                var form_data = $('.blockMsg form').serialize();
                $.post('/register/?ajax=1', form_data, function(new_form) {
                    // nothing returned means registration success
                    if (!new_form) {
                        window.location.reload();
                    }
                    else {
                        SmokinApps.popup.update(new_form);
                        $('.blockMsg form').hide().fadeIn();
                        SmokinApps.register.events();
                    }
                });
                return false;
            });

            $('.blockMsg input.text').eq(0).focus();            
        }
    },
    
    update_msg : function(content) {
        if (!$('#login-bar .msg').get(0)) {
            $('#login-bar').append('<div class="msg"></div>');
        }
        $('#login-bar .msg').html(content);
    },
    
    popup: {
        update: function(content) {
            if (!$('.blockMsg').get(0)) {
                SmokinApps.popup.create(content);
            }
            else {
                $('.blockContent').html(content);
            }
        },
        
        create: function(content) {
            $.blockUI({
                message: '<div class="blockContent"></div>'
            });
            SmokinApps.popup.update(content);
            $('.blockMsg').center().append('<div class="close">Close</div>');
            $('.blockMsg .close, .blockOverlay').click($.unblockUI);
        }
    },
    
    links: {
        init: function() {
            $('a').each(function() {
                var href = $(this).attr('href');
                if (href && href.match(/^https?:\/\//) && !href.match(/^https?:\/\/([^\.]+.)?smokinapps.com/)) {
                    $(this).attr('target', '_blank');
                }
            });
        }
    },
    
    tabs: {
        init: function() {
            $('#sidebar .widget-subscribe .tabs').each(function() {
                if ($('li', this).size() > 1) {
                    $('li a', this).click(function() {
                        var li = $(this).parents('li:first');
                        li.addClass('current').siblings('li').removeClass('current');
                        var id = li.attr('id');
                        if (id) {
                            id = id.replace('tab-', '');
                        }
                        $('#tab-content-' + id).show().siblings('.tab-content').hide();
                        return false;
                    });
                }                
            });
        }
    },
    
    input_text: function(txtbox, msg) {
        if (txtbox.val() == '') {
            txtbox.val(msg);
        }
        
        txtbox.focus(function() {
            if (msg == $(this).val()) {
                $(this).val('');
            }
        }).blur(function() {
            if ($(this).val() == '') {
                $(this).val(msg);
            }
        });
    },
    
    subscribe: {
        init: function() {
            var txtbox = $('#sidebar .widget-subscribe input.text');
            var msg = 'Enter Email Here';
            SmokinApps.input_text(txtbox, msg);
        }
    },
    
    rating: {
        init: function() {
            $('.post a.rating').click(function() {
                var url = $(this).attr('href') + '&ajax=1';
                var anchor = $(this);
                jQuery.get(url, function(votes) {
                    if (!anchor.hasClass('voted')) {
                        anchor.addClass('voted');
                    }
                    
                    $('.votes', anchor).html(votes);
                });
                return false;
            });
        },

        events: function() {
            var header = '';
            $('.post .rating-stars').hover(function() {
                var h2 = $('h2 a', this);
                header = h2.html();
                h2.html('Rate Now');
                $(this).addClass('rating-stars-current');
            },
            function() {
                var h2 = $('h2 a', this);
                h2.html(header);
                $(this).removeClass('rating-stars-current');
            });
        }
    },
    
    filters: {
        init: function() {
            $('.filter form select').change(function() {
                this.form.submit();
            })
        }
    },
    
    search: {
        init: function() {
            var txtbox = $('#content div.filter form.keyword input.text');
            var msg = 'Enter Keyword Or App Name';
            SmokinApps.input_text(txtbox, msg);
        }
    },
    
    submit: {
        dls: 0,
        
        init: function() {
            if ($('div.field-dls').get(0)) {
                var obj = $('div.field-dls');
                SmokinApps.submit.dls = $('ul li', obj).size();

                $(obj).append('<p><a href="" class="add">+ Add More</a></p>');

                $('a.add', obj).click(function() {
                    var field_name = 'dls[' + SmokinApps.submit.dls + ']';
                    SmokinApps.submit.dls++;
                    var li = $('ul li:last', obj);
                    li.after(li.clone());
                    li = $('ul li:last', obj);
                    $('.error', li).remove();
                    $('select', li).val('').attr('name', field_name + '[category_id]');
                    $('input.text', li).val('').attr('name', field_name + '[download_url]');
                    return false;
                });
                
                /*
                $('ul li', obj).each(function(i) {
                    if (i == 0) return;
                    $('.error', this).append(' <a href="" class="remove">Remove</a>');
                    $('.error .remove', this).click(function() {
                        $(this).parents('li:first').remove();
                        return false;
                    });
                })
                */
            }            
            
            if ($('div.field-review').get(0)) {
                $('div.field-review input[type=radio]').change(function() {
                    if ($(this).val() != 'normal') {
                        $('div.controls input[type=submit]').hide();
                        $('div.controls input[type=image]').show();
                    }
                    else {
                        $('div.controls input[type=submit]').show();
                        $('div.controls input[type=image]').hide();
                    }
                });
            }
        }
    }
};

/* jQuery Center Plugin */
jQuery.fn.center = function() {
        // Always return each...
        return this.each(function() {
                var t = jQuery(this);

                var leftMargin = t.outerWidth() / 2;
                var topMargin = t.outerHeight() / 2;

                if( typeof( window.pageYOffset ) == 'number' ) {
                    // Netscape
                    var scrollOffset = window.pageYOffset;
                } else if( document.body && document.body.scrollTop ) {
                    // DOM
                    var scrollOffset = document.body.scrollTop;
                } else if( document.documentElement && document.documentElement.scrollTop ) {
                    // IE6 standards compliant mode
                    var scrollOffset = document.documentElement.scrollTop;
                }
                else {
                    var scrollOffset = 0;
                }

                var topOffset = (jQuery(window).height() / 2) + scrollOffset - topMargin;
                var leftOffset = (jQuery('body').width() / 2) - leftMargin;
                
                if (topOffset < 0)
                    topOffset = 0;

                t.css({
                    position: 'absolute',
                    left: leftOffset + 'px',
                    top: topOffset + 'px'
                });
        });
};

jQuery.fn.hovermenu = function(content) {
    return this.each(function() {
        var t = jQuery(this);
        var pos = t.offset();

        var topOffset = pos.top + t.outerHeight();
        var leftOffset = pos.left;

        $('body').append(content);
        content.css({
            position: 'absolute',
            left: leftOffset + 'px',
            top: topOffset + 'px'
        });
        
        var timer = null;
        var settimer = function() {
            timer = setTimeout(function() { content.fadeOut(); }, 500);
        };
        
        var cleartimer = function() {
            if (content.css('display') == 'none') {
                content.css({
                    'top': topOffset + 'px',
                    'opacity': 0
                });
                content.show();
                var top = topOffset + 10;
                content.animate({
                    'top': top + 'px',
                    'opacity': 1
                }, 500);
            }
            clearTimeout(timer);
        };
        
        t.hover(cleartimer, settimer);
        content.hover(cleartimer, settimer);
    });
}

jQuery.fn.star_rating = function() {
    return this.each(function() {
        var t = jQuery(this);
        
        var saved;
        
        $('.star a', t).hover(function() {
            saved = $('.star a.current', t);
            $('.star a', t).removeClass('current');
            $(this)
                .addClass('current')
                .parents('.star').prevAll('.star').find('a').addClass('current');
        },
        function() {
            $('.star a', t).removeClass('current');
            saved.addClass('current');
        })
        .click(function() {
            var url = $(this).attr('href');
            $.get(url + '&ajax=1', function(data) {
                var post = t.parents('.post');
                if (data == 'LOGGED OUT!') {
                    var id = post.attr('id');
                    SmokinApps.login.popup(function() { window.location.replace(url + '#' + id); });
                }
                else {
                    $('.rating-widget', post).replaceWith(data);
                    $('.star-rating', post).star_rating();
                    $('.write-review', post).click(function() {
                        var url = $(this).attr('href') + '&ajax=1';
                       SmokinApps.review.popup(url);
                       return false;
                    });
                    SmokinApps.rating.events();
               }
            });
            return false;
        });
    });
}

jQuery.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
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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;
    }
};