(function($){
    window.NowFashion = {
        config: {
            show_width:378,
            thumb_width:106,
            toggled: false, //for thumbnails toggle
            index: 0, //the index of current photo showing.
            thumb_offset: 0, //int index
            thumb_moving: 0,  // sample value "-10px"
            start: 0, //the start position of photo list
            adv_count: 0, //log time for showing adv
            adv_time: 0, //show banner every adv_time, 0 to disable
            adv_delay: 10000, //hide banner after 10 second
            adv_timeout: 0,
            startX: 0,
            startY: 0,
            lock: false,
            init: false
        },

        gallery: function(){
            var prev = $('.nfGallery_show_prev'),
                next = $('.nfGallery_show_next'),
                list = $('.nfGallery_show_list'),
                link = $('.nfGallery_show_list .nfGallery_show_photo'),
                left = 0,
                speed = 400;

            $(".nfGallery_show_prev,.nfGallery_show_next").animate({
                "opacity":'0.66'
            },0);

            prev.click(function() {
                NowFashion.gallery_slide(NowFashion.config.index-1);
            });
            next.click(function() {
                NowFashion.gallery_slide(NowFashion.config.index+1);
            });
            var body = $('body');
            link.click(function(){
                var info = $(this).parent().next();
                $(".nfGallery_show_comments,.nfGallery_show_links").hide();
                info.fadeIn();

                /*
                list.mousedown(function(event) {
                    NowFashion.config.startX = event.clientX;
                    body.mousemove(function(event) {
                        offset = event.clientX - NowFashion.config.startX;
                        NowFashion.config.thumb_moving += offset; 
                        if (offset > 0) {
                            op = "-=";
                        }
                        NowFashion.config.startX = event.clientX;
                        var moving = [op,offset,'px'].join('');
                        list.animate({"left":moving},0);
                    })
                }).mouseup(function(event) {
                    NowFashion.lock = true;
                    body.unbind("mousemove");
                });
                */
                return false;
            });

            /*
            var last = 0;
            var offset = 0;
            list.draggable({ 
                axis: "x",
                start: function(event,ui) {
                    if  (typeof ui.position === 'object'){
                        last = ui.position.left;
                    }
                },
                drag: function(event,ui) {
                },
                stop: function(event,ui) {
                    if (typeof ui.position === 'object'){
                        offset = ui.position.left - last;
                        if (offset > 0) {
                            list.animate({"left":"-=" + offset*3 + "px"},500)
                        } else {
                            list.animate({"left":"+=" + offset*3 + "px"},500)
                        }
                    }
                    
                },
                cursor: "move"
            });

            */

            $(".nfGallery_show_info_close").click(function() {
                $(".nfGallery_show_info").fadeOut();
            });

            this.gallery_thumb();
            this.gallery_nail();
            this.gallery_album();
            this.gallery_banner();
            this.gallery_pager(0);
        },

        gallery_thumb: function() {
            var toggle = $(".nfGallery_thumb_toggle"),
                nail = $('.nfGallery_thumb_nail'),
                strong = toggle.find('strong'),
                speed = 400,
                prev = $('.nfGallery_thumb_prev'),
                next = $('.nfGallery_thumb_next'),
                list = $('.nfGallery_thumb_list'),
                content = strong.text(),
                thumb = $('.nfGallery_thumb'),
                lock = false;
                toggled = NowFashion.config.toggled;

            toggle.click(function() {
                if (toggled === false) {
                    strong.html("Hide Thumbnails");
                    thumb.animate({
                        "height":"+=120px"
                    },speed);
                } else {
                    strong.html("Show Thumbnails");
                    thumb.animate({
                        "height":"-=120px"
                    },speed);
                }
                nail.animate({
                    "height":"toggle",
                    "opacity":"toggle"
                },speed);
                toggled = !toggled;
                return false;
            });

            var len = list.find('li').length;
            var total = 106 * len;
            var offset = 0;
            var w = Math.abs(106*(len-9));
            list.css({
                "width": total+'px'
            });
            prev.click(function(){
                //NowFashion.gallery_slide(NowFashion.config.index-1);
                offset = NowFashion.getInt(list.css('left'));
                if (offset <= 274 ) {
                    if (!lock) {
                        lock = true;
                        list.animate({"left":"+=318px"},function() {
                            lock = false;
                        });
                        NowFashion.config.thumb_offset = NowFashion.config.thumb_offset -3 ;
                    }
                }
            });
            next.click(function(){
                //NowFashion.gallery_slide(NowFashion.config.index+1);
                offset = NowFashion.getInt(list.css('left'));
                if (Math.abs(offset) < w) {
                    if (!lock ) {
                        lock = true;
                        list.animate({"left":"-=318px"},function() {
                            lock = false;
                        });
                        NowFashion.config.thumb_offset = NowFashion.config.thumb_offset +3 ;
                    }
                }
            });
        },

        getInt: function(str) {
            var num = /[-]{0,1}\d+/i.exec(str)[0];
            num = window.parseInt(num);
            return num;
        },

        getOp: function(num) {
            num = num || 0;
            var op = "-=";
            if (num < 0) {
                op = "+=";
            }
            return [op,Math.abs(num),"px"].join("");
        },

        getQueryString: function(name) {
            var regex = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var result = window.location.search.substr(1).match(regex);
            if (result!==null) {
                return unescape(result[2]);
            }
            return null;
        },

        gallery_nail: function() {
            var ul = $('.nfGallery_thumb_list'),
                li = ul.find('li'),
                index = NowFashion.config.index,
                offset = 0,
                step = 10,
                op = "+=";
                NowFashion.lock = true;

            li.click(function(event) {
                var self = $(this),
                    index = li.index(self);
                NowFashion.gallery_slide(index);
                NowFashion.lock = true;
                ul.unbind("mousemove");
                return false;
            });
            /* 
            ul.mousedown(function(event) {
                NowFashion.config.startX = event.clientX;
                ul.mousemove(function(event) {
                    offset = event.clientX - NowFashion.config.startX;
                    NowFashion.config.thumb_moving += offset; 
                    if (offset > 0) {
                        op = "-=";
                    }
                    NowFashion.config.startX = event.clientX;
                    var moving = [op,offset,'px'].join('');
                    ul.animate({"left":moving},0);
                })
            }).mouseup(function(event) {
                NowFashion.lock = true;
                ul.unbind("mousemove");
            });
            */
            
        },
        gallery_load_all_pics: function(){
            var last_id=$('#lastid').val();
            if(last_id){
                return false;
            }
            var gallery_page_id=$('#gallery_page_id').val();
            if(!gallery_page_id){
                window.clearInterval(gallery_wait);
                return false;
            }
            $.ajax({
                type: "POST",
                url: siteurl+"/postrank/load_all_pics/?gallery_page_id="+gallery_page_id,
                success: function(msg){
                    if(msg=='1') location.reload();
                }
            });
        },

        gallery_load_new_pic: function(){
            var last_id=$('#lastid').val();
            if(!last_id){
                if(!$('.null_tips').html()){
                    return false;
                }else{
                    last_id = -999;
                }
            }
            $.ajax({
                type: "POST",
                url: siteurl+"/postrank/load_new_pic/?last_id="+last_id,
                success: function(msg){
                    if(!msg){
                        $('.nfGallery_thumb_pager strong').remove();
                    }else{
                        eval(" var msg="+msg);
                        if(msg.count && msg.lastid>last_id){
                            if(last_id==-999){
                                if(confirm("The Live Show has begun. Would you like to view it?")){
                                    window.location.replace(siteurl);
                                }
                                return false;
                            }
                            $(msg.big_html).appendTo('.nfGallery_show_list');
                            $(msg.thumb_html).appendTo('.nfGallery_thumb_list');

                            NowFashion.gallery_init_width();
                            
                            var total_count = $('.nfGallery_show_list li').length;
                            $('.nfGallery_thumb_pager small').html(total_count);
                            $('.nfGallery_thumb_pager strong').remove();
                            $(total_count+"&nbsp;<strong>(New: "+msg.count+")</strong>").appendTo('.nfGallery_thumb_pager small');
                            $('#lastid').val(msg.lastid);
                        }else{
                            $('.nfGallery_thumb_pager strong').remove();
                        }
                    }
                }
            });
        },

        gallery_init_width:function(){
            var tmp_show_width = NowFashion.config.show_width;
            var tmp_thumb_width = NowFashion.config.thumb_width;

            var show_width=$('.nfGallery_show_list').find('li').length*tmp_show_width;
            var thumb_width=$('.nfGallery_thumb_list').find('li').length*tmp_thumb_width;

            $('.nfGallery_show_list').css('width',show_width+'px');
            $('.nfGallery_thumb_list').css('width',thumb_width+'px');
        },

        /*
         * @param index {int}
         */
        gallery_slide: function(index) {
            var obj=$('.nfGallery_show_comment_text').eq(index);
            $(obj).load(siteurl+"/postrank/loadcomment/?postid="+postid+"&pid="+$(obj).attr('id'));
            var show = $('.nfGallery_show_list'),
                show_width = NowFashion.config.show_width,
                thumb = $(".nfGallery_thumb_list"),
                thumb_width = NowFashion.config.thumb_width,
                max  = thumb.find('li').length,
                image = $("img.nfGallery_show_photo").eq(index),
                image2 = $("img.nfGallery_show_photo").eq(index+1),
                offset = 0,
                speed = 400;
            NowFashion.gallery_init_width();
            if (index >= max) {
                index = 0;
            }
            else if (index < 0) {
                index = max-1;
            }
            offset = NowFashion.config.index - index;


            if (image.attr('lazy_url') !== undefined) {
                image.attr('src',image.attr('lazy_url'));
            }

            if (image2.attr('lazy_url') !== undefined) {
                image2.attr('src',image2.attr('lazy_url'));
            }

            NowFashion.config.index = index;//Set current imgage
            NowFashion.gallery_pager(index);
            NowFashion.gallery_banner();
//            var next_index;
//            var pre_index;
//            next_index = index+1 >max ? 1 : index+1;
//            pre_index = index-1 <0 ? max : index-1;
//            $('.nfGallery_show_list li table').eq(index).css('width','368px');
//            $('.nfGallery_show_list li table').eq(next_index).css('width','280px');
//            $('.nfGallery_show_list li table').eq(pre_index).css('width','280px'); 
            var go = function(width) {
                var op = "";
                if (offset <= 0 ) {
                    op = "-=";
                }
                else if (offset >= 0 ) {
                    op = "+=";
                } else  {
                    return;
                }
                $(".nfGallery_show_comments,.nfGallery_show_info,.nfGallery_show_links").fadeOut();
                var total = width*Math.abs(offset);
                var ret =  [op,total,'px'].join('');
                return ret;
            };

            var getBack = function() {
                var op = "-=";
                if (NowFashion.config.thumb_offset > 0) {
                    op = "+=";
                }
                var ret = [op, Math.abs(NowFashion.config.thumb_offset)*thumb_width, "px"].join("");
                NowFashion.config.thumb_offset = 0; //reset offset
                return ret;
            };

            var getBackWidth = getBack();
            var getBackMoving = NowFashion.getOp(NowFashion.config.thumb_moving);

            show.animate({
                "left": go(show_width)
            });
            thumb.animate({
                "left": go(thumb_width)
            },function() {
                thumb.animate({
                    "left": getBackWidth
                });
            });
            NowFashion.lightbox_close();

            _TEMP_.pid = $(obj).attr('id');
            read_rank($(obj).attr('id'));
        },

        gallery_photo: function() {
            var pid = NowFashion.getQueryString('pid');
            if (pid !== null) {
                var ul = $("ul.nfGallery_show_list");
                var list = ul.find("li");
                list.each(function(index) {
                    if ($(this).attr("pid") == pid) {
                        NowFashion.gallery_slide(index);
                        return false;
                    }
                });
            }
        },

        gallery_pager: function(start) {
            start = start || 0;
            var pager = $(".nfGallery_thumb_pager"),
                total = $(".nfGallery_thumb_list a").length,
                first = pager.find('span'),
                last = pager.find('small');

            start++;
            if (start > total ) {
                start = total;
            }
            first.text(start);
            last.text(total);
        },

        gallery_album: function() {
            var title = $(".nfGallery_thumb_title a"),
            lists = $(".nfGallery_thumb_list");

            title.click(function() {
                if ($('.nfGallery_album').length === 0) {
                    var html = '<div class="nfGallery_album"><div class="nfGallery_album_popup"><ul class="nfGallery_album_list"></ul></div></div>';
                    $('body').prepend(html);
                } else {
                    $('.nfGallery_album').fadeOut(function() {
                        $('.nfGallery_album').remove();
                    });
                    return false;
                }

                var album = $(".nfGallery_album");
                var list = $(".nfGallery_album_list");
                list.html(lists.html());
                var link = list.find('li a');
                var scrollTop = document.body.scrollTop;  
                if(scrollTop === 0){  
                    scrollTop = document.documentElement.scrollTop;
                }
                album.css({
                    "top":scrollTop
                });

                link.click(function() {
                    var index = link.index(this);
                    album.fadeOut(function(){
                        album.remove();
                        NowFashion.gallery_slide(index);
                    });
                    return false;
                });

                NowFashion.lightbox();
                album.fadeIn();
                return false;
            });
        },

        gallery_banner: function() {
            NowFashion.config.adv_count++;
            var banner = $(".nfGallery_show_banner"),
            close = $(".nfGallery_show_banner_close");
            close.click(function() {
                banner.fadeOut();
            });
            if (NowFashion.config.adv_time === 0) {
                return false; //disabled.
            }
            if (NowFashion.config.adv_count % NowFashion.config.adv_time === 0 ) {
                banner.fadeIn();
                banner[0].scrollIntoView();
                NowFashion.config.adv_timeout = window.setTimeout(function(){
                    banner.fadeOut();
                },NowFashion.config.adv_delay);
            } else {
                //banner.fadeOut();
            }
        },

        meta_search: function() {
            var search = $('#meta_search'),
            text = search.attr('value');
             
            search.focus(function() {
                if ($(this).attr('value') == text) {
                    $(this).attr('value','');
                }
            }).blur(function() {
                if ($(this).attr('value') === '') {
                    $(this).attr('value',text);
                }
            });
        },

        popup: function() {
            $('#meta_login,#meta_register,#footer_signup').click(function() {
                var self = $(this);
                var href = self.attr('href');
                NowFashion.lightbox();
                $('#boxing').load(href);
                if (/login/i.test(href)) {
                    $("#boxing").css({
                        "top":"40%"
                    });
                } else {
                    $("#boxing").css({
                        "top":"25%"
                    });
                }
                goto_top();
                return false;
            });
        },

        lightbox: function() {
            var box = $("#box"),
                boxing = $("#boxing");
            box.animate({
                "opacity":0.20
            },0).fadeIn();
            boxing.show();
            box.click(function() {
                NowFashion.lightbox_close();
                return false;
            });
            $('.close_popup').live('click',function(){
                boxing.html('');
                NowFashion.lightbox_close();
                return false;
            });
        },

        lightbox_close: function() {
            $('#box,#boxing,.nfGallery_album_popup').fadeOut(function() {
                $('#box,#boxing,.nfGallery_album_popup').html('');
            });
        },

        digg: function() {
            var like = $(".nfGallery_show_like"),
            dislike = $(".nfGallery_show_dislike");
            like.click(function() {
                return false;
            });
            dislike.click(function() {
                return false;
            });
        },

        show: function() {
            var next = $(".latest_shows_next"),
                prev = $(".latest_shows_prev"),
                list = $("#latest_shows_list"),
                ul = $("#latest_shows_list ul"),
                top = 0,
                speed = 400,
                lock = false;

            next.click(function() {
                if (lock === false) {
                    top = /\d+/i.exec(ul.css('top'));
                    if (top < (ul.height()-384)) {
                        lock = true;
                        ul.animate({
                            "top":"-=202px"
                        },speed,function() {
                            lock  = false;
                        });
                    }
                }
            });
            prev.click(function() {
                if (lock === false) {
                    top = /\d+/i.exec(ul.css('top'));
                    if (top !== 0) {
                        lock = true;
                        ul.animate({
                            "top":"+=202px"
                        },speed,function() {
                            lock  = false;
                        });
                    }
                }
            });
        },

        comment: function() {
            var item = $(".nfGallery_show_comment"),
                input = $(".nfGallery_show_area"),
                loading = "nfGallery_show_area_loading";

            item.click(function() {
                if (NowFashion.check_login() === true) {
                    var li = $(this).parent().parent().parent().parent().parent();
                    $('.nfGallery_show_info,.nfGallery_show_links').hide();
                    li.find('.nfGallery_show_comments').animate({
                        "height":"toggle"
                    });
                }
                return false;
            });

            input.keydown(function(event) {
                var index=$(input).index($(this));
                if (event.keyCode == 13) {
                    var forms = $('.commentform').eq(index);
                    var value = $(this).attr('value');
                    var text = $(this).prev();
                    var user = NowFashion.user();
                    var str = ["<div>","<span>",user,": </span>",value,"</div>"].join('');
                    var lock = false;
                    if (lock === false && value !== '') {
                        lock = true;
                        $.ajax({
                            type: "POST",
                            url: siteurl+"/postrank/comment/",
                            data: forms.serialize(),
                            success: function(msg){
                                lock=false;
                                if(msg){
                                    $('.nfGallery_show_comment_text').eq(index).html(msg);
                                    return;
                                }
                                $('.nfGallery_show_comment_text').eq(index).load(siteurl+"/postrank/loadcomment/?postid="+postid+"&pid="+$('.nfGallery_show_comment_text').eq(index).attr('id'));
                                text.append(str);
                                text.scrollTop(text.scrollTop()+1000);
                                input.attr('value','');
                            }
                        });
                    }
                }
            });

            var value = "Write a comment";
            input.focus(function() {
                var self = $(this);
                if (self.attr('value') == value) {
                    self.attr('value','');
                }
            }).blur(function() {
                var self = $(this);
                if (self.attr('value') === '') {
                    self.attr('value',value);
                }
            });
        },

        check_login: function() {
            if (typeof is_login == 'undefined') {
                is_login = false;
            }
            if (!is_login) {
                NowFashion.open_signin();
                return false;
            }
            return true;
        },

        open_signin: function() {
            var meta = $("#meta_login");
            if (meta.length) {
                var href = $('#meta_login').attr('href');
                NowFashion.lightbox();
                document.getElementById("boxing").scrollIntoView();
                $('#boxing').load(href);
            }
        },

        link: function() {
            var links = $('.nfGallery_show_link');
            links.click(function() {
                var li = $(this).parent().parent().parent().parent().parent();
                var item = li.find(".nfGallery_show_links");
                $(".nfGallery_show_comments,.nfGallery_show_info").hide();
                item.animate({
                    "height":"toggle",
                    "opacity":"toggle"
                });
                return false;
            });
        },

        review: function() {
            var item = $(".nfGallery_show_review"),
                info = $(".nfGallery_show_info");
            item.click(function() {
                var li = $(this).parent().parent().parent().parent().parent().parent();
                li.find('.nfGallery_show_info').animate({
                    "opacity":"toggle"
                });
                $(".nfGallery_show_comments,.nfGallery_show_links").hide();
                return false;
            });
        },

        fav: function() {
            $('.messages_text a').click(function() {
                if (NowFashion.check_login() === true) {
                    var p = $(this);
                    $.ajax({
                        type: "POST",
                        url: p.attr('href'),
                        data: "",
                        success: function(msg){
                            if(msg=='1'){
                                p.find('.img_src').hide();
                                p.find('.link_text').show();
                            }
                            if(msg=='2'){
                                p.find('.link_text').hide();
                                p.find('.img_src').show();
                            }
                            //alert(msg);
                            //self.remove();
                            //p.prepend('added!');
                            var href=p.attr('href');
                            var rel=p.attr('rel');

                            p.attr('href',rel);
                            p.attr('rel',href);
                        }
                    });
                }
                return false;
            });
        },

        set_cookie: function(key, value, expires, path, domain, secure ){
            var cookie_string = key + "=" + escape ( value );
            if (expires) {
                cookie_string += "; expires=" + expires.toGMTString();
            }
            if (path) {
                cookie_string += "; path=" + escape(path);
            }
            if (domain) {
                cookie_string += "; domain=" + escape(domain);
            }
            if (secure) {
                cookie_string += "; secure";
            }
            document.cookie = cookie_string;
        },

        get_cookie: function(cookie_name){
            var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
            if (results)
                return (unescape(results[2]));
            else
                return null;
        },

        del_cookie: function(cookie_name){
            var cookie_date = new Date(); //current date & time
            cookie_date.setTime(cookie_date.getTime() - 1);
            document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
        },

        user: function() {
            //NowFashion.set_cookie('username',"jimmy");
            return NowFashion.get_cookie('username');
        },

        lookbook: function() {
            var addthis = '<div class="addthis_toolbox addthis_default_style fixaddthis">';
                addthis += '<a class="addthis_button_facebook"></a>';
                addthis += '<a class="addthis_button_twitter"></a>';
                addthis += '</div>';
                addthis += '<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=nowfashion"></script>';
            $('.nfGallery_show_lookbook').html(addthis);
        },

        init: function(){
            if (NowFashion.config.init === false) {
                NowFashion.config.init = true;
                this.gallery();
                this.meta_search();
                //this.lookbook();
                this.comment();
                this.popup();
                this.show();
                this.fav();
                this.digg();
                this.link();
                this.review();
                var gallery_wait=window.setInterval("NowFashion.gallery_load_all_pics()",5000);
                window.setInterval("NowFashion.gallery_load_new_pic()",60000);
            }
        }
    };

    $(document).ready(function() {
        NowFashion.init();
        $(document)[0].oncontextmenu = function() {return false;}; //disable mouse right button 
        $(".nfGallery_show_list").animate({"left":"290px"});
        $(".nfGallery_thumb_list").animate({"left":"380px"});
        NowFashion.gallery_photo();
        $(".nfGallery_thumb_toggle").trigger("click");
    });

})(jQuery);
