/*
* Shad'o Soft tm 2010! 
*/
                
var initSnow = true; //christmass fun
var usePostsFade = false;
var lazyPopup;


$extend(Selectors.Pseudo, {
    sizeCheck: function() {
        return this;
    }
});

// browser exception global var
isRefBrowser = 
        (navigator.userAgent.match(/iPad/i) != null) || 
        (navigator.userAgent.match(/iPhone/i) != null);
        
        
function displayLoad(mode, message){
    var load = $('loading');

    if (!isRefBrowser){
        if (load){
            
            // Update the message if have one.
            if (message)
                load.set('html',message);        
            
            // If we have an action to perform show/hide, do it.
            if (mode != null)
                if (mode)
                    load.fade(0.6);    
                else
                    load.fade(0.0);    
        }
    } else {
        // skip
    }
};

// Request manager
var requestManager = new Class({
    initialize:function(){
    },
    send:function(requestData,callback,xtra){
        var jsonRequest = new Request.JSON({
            // Asking to the request server
            url: '/server/request', 
            data:((requestData)?requestData:{'action':'none'}),
            method:'post',
            onSuccess: function(person){
                // ...
            },
            onRequest: function(r){
                //must display the loading here
                displayLoad(true, 'Loading...');
            },
            onComplete: function(r){
                //hide loading here!
                displayLoad(false);
                // Calling my callback function
                if (callback)eval('callback(r,xtra)');
            }
        }).send();
    }
});

var shadWeb = new Class({
    initialize:function(){
        myObj = this;
        var self = this;
        
        this.render = $('posts');
        this.currentCat = null;
        var request = new requestManager().send({
            'action':'getPost',
            'postid':postid,
            'cat':catid,
            'page':page,
            'day':day,
            'year':year,
            'month':month,
            'keywords':searchKeyword
        },self.getArticlesCallback,self);
        
        $$('input[id=hs_search]').addEvent('keypress', function(el){
            if (el.key == 'enter'){
                var request = new requestManager().send({
                    'action':'getPost',
                    'postid':postid,
                    'cat':catid,
                    'page':page,
                    'keywords':this.get('value')
                },self.getArticlesCallback,self);
            }
        });
        
        $$('a[name=cat]').addEvent('click',function(){
            var myFx = new Fx.Scroll(window).toElement('posts');
            self.currentCat = this.get('catid');
            var request = new requestManager().send({
                'action':'getPost',
                'cat':self.currentCat
            },self.getArticlesCallback,self);
            return false;
        });

        var request = new requestManager().send({
            'action':'calendar'
        },self.getCalendarCallback,'posts');
        
          
        var testScroll = function(){
            
            if (window.getScrollTop() > 600){
                if (!displayed){
                    $('sroll_top').fade(0.6);    
                    displayed = true;
                }    
            }  else {
                if (displayed){
                    $('sroll_top').fade(0);
                    displayed = false;
                }    
            }
            
        };
          
        var toTop = $('sroll_top');
        if (toTop){
            var displayed; 
            
            toTop.setStyle('display', '');
            toTop.fade('hide');
            testScroll();
            //$('sroll_top').setOpacity(0);
            window.addEvent("scroll", function(el){
                testScroll();    
                
            });
            
            toTop.addEvent('click', function(){
                var myFx = new Fx.Scroll(window).toElement('posts');
            });
        }
        
        
    },
    getCalendarCallback : function(r){
        //new version test : no table!
        var days = ['S','M','T','W','T','F','S'];
        var body = new Element('div',{'class':'cal_body'});
        var day = 0;
        row = new Element('div');
        body.adopt(row); 
        $each(days,function(data,key){
            row.adopt(new Element('div',{'class':'cal_block'}).set('html',data));
        });        
        $each(r.data.calendar.days,function(data,key){
            if ((day==0) || (day==8)){
                row = new Element('div',{'class' : 'cal_row'});
                body.adopt(row); 
                day=1;
            };    
            if ((data) && (data.post)){
                col = new Element('div',{'class':'cal_block'}).adopt(
                    new Element('a',{'href':
                        '/display/period/'+r.data.calendar.year+'/'+r.data.calendar.monthi+'/'+(((data) && (data.day))?data.day:'&nbsp;')
                        ,'events':{'click':function(){
                        var myFx = new Fx.Scroll(window).toElement('posts');
                        var request = new requestManager().send({
                            'action':'getPost',
                            'cat':myObj.currentCat,
                            'day':data.day,
                            'year':r.data.calendar.year,
                            'month':r.data.calendar.monthi
                        },myObj.getArticlesCallback,$('posts'));
                        return false;
                    }}}).set('html',(((data) && (data.day))?data.day:'&nbsp;'))
                );
            } else {
                col = new Element('div',{'class':'cal_block'}).set('html',(((data) && (data.day))?data.day:'&nbsp;'));
            };       
            row.adopt(
                col    
            );
            day+=1;            
        });
        
        // fill calendar! v2 no more table!!
        $('calendar').empty().adopt(
            new Element('div'/*table*/).adopt(
                new Element('div'/*thead*/).adopt(
                    new Element('div'/*tr*/).adopt(
                        new Element('div',{'style':'width:20px; float:left; text-align: center'}).adopt(
                            new Element('a',{'class':'link', 'events':{'click':function(){
                                r.data.calendar.monthi=parseInt(r.data.calendar.monthi)-1;
                                if (r.data.calendar.monthi<1){
                                    r.data.calendar.monthi=12;
                                    r.data.calendar.year=parseInt(r.data.calendar.year)-1;
                                }
                                var request = new requestManager().send({
                                    'action':'calendar',
                                    'month':r.data.calendar.monthi,
                                    'year':r.data.calendar.year
                                },myObj.getCalendarCallback,'posts');
                            }}}).set('text','<<')                        
                        ),
                        new Element('div'/*th*/,{'class':'cal_title'}).set('html',r.data.calendar.month+' '+r.data.calendar.year),
                        new Element('div',{'style':'width:20px; float:right; text-align: center'}).adopt(
                            new Element('a',{'class':'link','events':{'click':function(){
                                r.data.calendar.monthi=parseInt(r.data.calendar.monthi)+1;
                                if (r.data.calendar.monthi>12){
                                    r.data.calendar.monthi=1;
                                    r.data.calendar.year=parseInt(r.data.calendar.year)+1;
                                }
                                
                                var request = new requestManager().send({
                                    'action':'calendar',
                                    'month':r.data.calendar.monthi,
                                    'year':r.data.calendar.year
                                },myObj.getCalendarCallback,'posts');
                            }}}).set('text','>>')                        
                        )
                    ),
                    new Element('div',{'style':'clear: both'})
                ),
                body, // o__O and if I got to body now for transition? mmmmh let seeee... later!
                new Element('br', {'clear':'left'})
            )
        )
    },
    postEdit: function(post, postData){
        // ...
    },
    likeCB: function(a,b){
        
    },
    postDisplay: function(post, postData){
        // displayed
        var postInfo = [];
        postInfo.push(new Element('span').set('html',postData.post_date));
        if (postData.update_date)
            postInfo.push(new Element('span',{'class':'post_update_date'}).set('html','Last update '+postData.update_date));
        var postTitle = [];
        postTitle.push(new Element('a').set('html',postData.post_title));

        //edit mode o_O
        if (editMode)
        postTitle.push(
            new Element('div',{'class':'post_tools'}).adopt(
                new Element('img',{'src':'/pictures/load/edit_icon.png'}).addEvent('click',function(){
                    var request = new requestManager().send({
                        'action':'editPost',
                        'sub':'ask'
                    });
                })
            )
        );
        
        var likeForm = 
            new Element('div', {'style':'width:130px; float:right;'});
            
        var likeCounter = 
            new Element('div',{'class':'like', 'style':'display:'+((postData.likes_done)?'':'none')+''}).adopt(
                new Element('span').set('text',((parseInt(postData.likes) == postData.likes)? postData.likes : 0) + ' ').adopt(
                    
                ),
                new Element('img',{'class':'nopreload', 'border':'0','src':'/pictures/load/like.gif'})
            );
        
        if (!postData.likes_done)
            likeCounter.setOpacity(0);
        
        var actionReady = true;
        // wow need to make some clean here o___O repetitive @____@
        var likeActionPanel = 
            new Element('div',{'style':'display:'+((postData.likes_done)?'none':'')+';'}).adopt(
                new Element('a',{'events':{'click':function(){
                    if (actionReady){
                        actionReady = false;
                        var request = new requestManager().send({
                            'action':'like',
                            'post_id':postData.post_id,
                            'like':true
                        },myObj.likeCB,{likeActionPanel:likeActionPanel, likeCounter:likeCounter});
                        
                        var likes = new Fx.Tween(likeActionPanel);
                        likes.start('opacity', 0).chain(function(){
                            likeActionPanel.setStyle('display', 'none');
                            likeCounter.setStyle('display', '');
                            var likes = new Fx.Tween(likeCounter);
                            likes.start('opacity', 1);
                        });
                    }
                    
                }},'class':'smallbutton smallbutton-pale left'}).adopt(
                    new Element('span').set('text','Like').adopt(
                        new Element('img',{'border':'0','src':'/pictures/load/like.gif'})
                    )
                ),
                new Element('a',{'events':{'click':function(){
                    if (actionReady){
                        actionReady = false;
                        var request = new requestManager().send({
                            'action':'like',
                            'post_id':postData.post_id,
                            'like':false
                        },myObj.likeCB,{likeActionPanel:likeActionPanel, likeCounter:likeCounter});
                        var likes = new Fx.Tween(likeActionPanel);
                        likes.start('opacity', 0).chain(function(){
                            likeActionPanel.setStyle('display', 'none');
                            likeCounter.setStyle('display', '');
                            var likes = new Fx.Tween(likeCounter);
                            likes.start('opacity', 1);
                        });
                    }
                }},'class':'smallbutton smallbutton-pale right'}).adopt(
                    new Element('span').set('text','Dislike').adopt(
                        new Element('img',{'border':'0','src':'/pictures/load/dislike.gif'})
                    )
                )
            );
        
        if ((postData.use_like == '1')){
            likeForm.adopt(
                likeActionPanel
            );
            likeForm.adopt(
                likeCounter
            );
        }
        return [
            new Element('h2',{'class':'post_title', 'id':'post_' + postData.post_id}).adopt(
                postTitle
            ),
            new Element('p',{'class':'post_info'}).adopt(
                postInfo
            ),
            new Element('div',{'class':'post_data'}).set('html',postData.post_content),
            new Element('div',{'style':'width:100%;height:30px;'}).adopt(
                likeForm,
                new Element('br',{'clear':'right'})
            )
        ]
    },
    getArticlesCallback : function(r,xtra){
        if (r.search){
            var myFx = new Fx.Scroll(window).toElement('posts');
        }
        var self = this;
        if (usePostsFade){
            myObj.render.setOpacity(0);
        }
        displayLoad(true);
        if (myObj.render) myObj.render.empty();
        if (r.data.pages){
            myObj.render.adopt(
                myObj.makePages(r)
            );
            
            $each(r.data.posts,function(postData){
                var post = new Element('div');
                post.adopt(
                    myObj.postDisplay(post, postData)
                );
                myObj.render.adopt(
                    post    
                )
            });
            
            myObj.render.adopt(
                myObj.makePages(r,true)
            );
            
        } else {
            myObj.render.adopt(
                new Element('h2',{'class':'post_title'}).adopt(
                    new Element('center').adopt(
                        new Element('a').set('html','No post found')
                    )
                )
            );
        };
        
        // update title with the current category title
        document.title = document_title;
        
        // A little part for check img loading o_O
        var imgList = $$('img[class!=preload]:sizeCheck');
        
        // small cheat with the preload
        var imgCount = imgList.length;
        var ImgLoadedCount = 0;
        
        // If we have picture to load on page
        if (imgCount>0){
            $$('img').each(function(el){
                
                // found the preload picture and remove it
                if (el.get('class') == 'preload'){
                    // destroy preloader
                    el.destroy();;                    
                } else {
                    // for other pictures, let's do normal work
                    
                    // lets work with parent div                
                    var p = el.getParent().getParent();
                    var loadImg = new Element('div', {'style':'width:100%; text-align : center; margin : 1px 2px 5px 2px'}).adopt(
                        new Element('img', {'src' : '/images/ajax-loader.gif'})
                    );
                    
                    if (el.get('class') != 'nopreload')
                        p.adopt(loadImg);
                    
                    // remove for a while the picture
                    el.setStyle('display', 'none');
                    
                    if (1){
                        el.addEvent('load', function(){
                            ImgLoadedCount+=1;
                            
                            // destroy the image from the dom
                            if (el.get('class') != 'nopreload')
                                loadImg.destroy();
                                
                            // remove predefined size!!
                            p.setStyle('height', '');
                            
                            // welcome back
                            el.setStyle('display', '');
                            
                            el.setOpacity(0);
                            el.fade(1.0);
                            
                            displayLoad(null, 'Loading... '+parseInt(ImgLoadedCount/imgCount*100)+'%');
                            
                            // if we loaded all pictures, I can hide loading progress
                            if (ImgLoadedCount >= imgCount) {
                                displayLoad(false);
                                if (!initSnow){
                                    snowStorm();
                                    initSnow = true; //owki you can go away o_O
                                }
                            }
                        })
                    }
                }
            });
            
        } else {
            displayLoad(false);
        }
        
        if (!isRefBrowser)
            Mediabox.scanPage();
        if (usePostsFade){
            myObj.render.fade(1);
        }
        
        $$('a[href^="http://download."]').addEvent('click', function(el){
            lazyPopup.show(this.get('href'));
            return false;
        })
        
    },
    makePages:function(r,totop){
        var pagesup = new Element('div',{'class':'pages'});
        if (r.data.pages)
        if (r.data.pages.length>1){
            pagesup.appendText('page < ');
            $each(r.data.pages,function(value,key){
                if (r.data.currentPage==value){
                    pagesup.appendText(value);
                } else {
                    pagesup.adopt(
                        new Element('a',{'href':'/display/cat/'+((myObj.currentCat)?myObj.currentCat:1)+'/'+value,'events':{'click':function(){
                            var myFx = new Fx.Scroll(window).toElement('posts');
                            var page = value;
                            var request = new requestManager().send({
                                'action':'getPost',
                                'cat':myObj.currentCat,
                                'page':page
                            },myObj.getArticlesCallback,$('posts'));
                            return false;//remove click
                        }}}).set('html',value)
                    );
                };  
                pagesup.appendText(' ');  
            });
            pagesup.appendText(' >');    
            
        } else {
            if (totop){
                pagesup.adopt(
                    new Element('a',{'events':{'click':function(){var myFx = new Fx.Scroll(window).toElement('posts');}}}).set('html','move to top')
                )
            } else {
                pagesup.set('html','&nbsp;');
            }    
        }
        return pagesup;
    }
    
});

function downloadPopup(){
    var me = this;
    var displayed = false;
    var downloadLink = new Element('a', {'target':'_blank'}).set('html', 'Download the file');
    var myPopup = new Element('div', {'style':'text-align: center; background: none repeat scroll 0% 0% white; border: 1px solid rgb(86, 103, 119); position: absolute; left: 50%; top: 50%; font: 12px/25px Verdana,Geneva,Arial,Helvetica,sans-serif; margin-left: -225px; width: 300px; height: 100px; text-align: center; z-index: 100;'}).adopt(
        new Element('div', {'style':'text-align: right; margin-right: 10px;'}).adopt(new Element('a', {'style':'cursor: pointer; font-weight: bold;'}).set('html', 'X').addEvent('click', function(){
            me.hide();    
        })),
        new Element('div').adopt(downloadLink),
        new Element('div', {'style' : ' margin: 10px;'}).adopt($('twitter'))
    );
    
    // lets hide my poor popup
    myPopup.setOpacity(0);
    myPopup.fade(0);
    

    this.hide = function(){
        myPopup.fade(0);
        displayed = false;
    };
    
    downloadLink.addEvent('click', function(){
        me.hide();
    });
    
    var body = $$('body');
    body.adopt(myPopup);
    body.addEvent('click', function(){});
    var getDocumentScrollTop = function(doc){
        doc = doc || document;    
        return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
    };
    this.show = function(url){
        myPopup.setStyle('margin-top', -75 + getDocumentScrollTop() + 'px');
        downloadLink.set('href', url);
        if (!displayed){
            displayed = true;
            myPopup.fade(1);
        }
    }
};

/*
* Let start our fun!! 
*/
window.addEvent('domready',function(){
    var load = $('loading');
    if (load){
        load.setStyle('display','');
        load.fade('hide');
    }
    
    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
    lazyPopup = new downloadPopup();        
    
    var web =  new shadWeb();
});


// let search a word on my website o__O
/* lets make work better later !! */
document.onkeypress = function(e){
    var isCtrl = false;
    
    if(window.event){
        key = window.event.keyCode; //IE
        if(window.event.ctrlKey)
            isCtrl = true;
        else
            isCtrl = false;
    } else {
        key = e.which;              //firefox
        if(e.ctrlKey)
            isCtrl = true;
        else
            isCtrl = false;
    }
    
    var e = window.event || e;
    // TODO : nothing seem happen out of firefox check it later!!
    if (isCtrl && (e.charCode == 102)) {

        var myFx = new Fx.Scroll(window,{
            offset: {'x': 0, 'y': -($(document).getHeight() / 2)}
        }).toElement('hs_search');
        $('hs_search').focus();
        $('hs_search').select();
        
        return false;   
    }
    
    return true;
};

