var portfolioTimeout;
var blogInt;

function reloadScripts(){
    tpl = jQuery('#content-var').attr('template');
    tpl = (tpl == undefined) ? 'home' : tpl;
    jQuery('ul, ol').children(':last-child').addClass('last-child');
    jQuery('ul, ol').children(':first-child').addClass('first-child');
    jQuery('body').attr('class',tpl + ' site-' + currentLanguage);
    if(the_anchor() == '/services/apps-smartphone-facebook/'){
        jQuery('#content-reel').css('backgroundImage','url('+templateDirectory+'/images/background/'+tpl+'-2.png)');
    } else {
        jQuery('#content-reel').css('backgroundImage','url('+templateDirectory+'/images/background/'+tpl+'.png)');
    }
    jQuery('#menu-main li').removeClass('current_page_item').removeClass('current_page_parent');
    jQuery('#menu-main li a[slug='+the_anchor()+']').parent().addClass('current_page_item');
    jQuery('#menu-main li a[slug='+the_anchor()+']').parents('li:gt(0)').addClass('current_page_parent').children('ul').show();
    eval('if(window.'+tpl+'Action){'+tpl+'Action();}');
}

function changeTitle(title){
    if(title == undefined || title == ''){
        document.title = sitename;
    } else {
        title = title.replace(/<([a-z][a-z0-9]*)\b[^>]*>.+<\/([a-z][a-z0-9]*)\b[^>]*>/,'');
        document.title = sitename + ' :: ' + title;
    }
}

function ajaxLoad(url, callback){
    jQuery('#content-right').load(url,function(){
        changeTitle(jQuery('#title').html());
        if(url != baseUrl){
            window.location.hash = '#!'+url.replace(completeUrl,'');
        }
        reloadScripts();        
        if(callback != null){
            callback();
        }
    });
}

function navScroll(me){
    speed = 0.6;
    screenWidth = jQuery(window).width();
    reelWidth = jQuery('#content-reel').width();
    jQuery('#line').animate({
        marginLeft: 240 - jQuery(window).width()
    }, speed * (reelWidth + screenWidth)/2);
    jQuery('#content-reel').animate({
        marginLeft:-(reelWidth + screenWidth/2)
    },{
        duration: speed * (reelWidth + screenWidth)/2,
        easing: 'easeInBack',
        complete: function(){
            ajaxLoad(me.attr('href'), function(){
                jQuery('#content-reel').css('marginLeft',(reelWidth + screenWidth)/2);
                jQuery('#content-reel').animate({
                    marginLeft:-reelWidth/2
                }, speed * (reelWidth + screenWidth/2), 'easeOutBack');
                jQuery('#line').animate({
                    marginLeft:0
                }, speed * (reelWidth + screenWidth/2), 'linear')
            })
        }
    });
}

function navFade(me){
    jQuery('#content-right').fadeOut();
    ajaxLoad(me.attr('href'), function(){
        jQuery('#content-right').fadeIn();
    });
}

function offsetLine(){
    setInterval(function(){
        if(jQuery('#menu-main > li.current_page_parent, #menu-main > li.current_page_item').length > 0){            
            jQuery('#line').css({
                top: jQuery('#menu-main > li.current_page_parent, #menu-main > li.current_page_item').offset().top - 25
            });
        }
    }, 10);
}

/* ACTIONS */

function homeAction(){
    jQuery('#line').css('width',jQuery(window).width()/2 - 260).css('marginLeft',240 - jQuery(window).width());
    jQuery('.wpcf7-form label').each(function(){
        label = jQuery(this).text();
        jQuery(this).parent().find('input, textarea').val(label).attr('rel',label);
    });
}

function archiveAction(){
    jQuery('.post-list').jScrollPane();
    jQuery('#line').animate({
        marginLeft:-jQuery('#line').width()
    }, 0.6 * jQuery('#line').width(), 'linear')
}

function blogAction(){
    jQuery('.post-list > div:gt(4)').hide();
    interval = 1000;
    setTimeout(function(){
        blogItemAutoSlide(interval);
    }, 6 * interval);
}

function blogItemStopSlide(){
    
}

function blogItemAutoSlide(interval){
    blogItemSlide('up', interval, false, function(){
        blogInt = setTimeout(function(){
            blogItemAutoSlide(interval);
        }, 6 * interval)
    });
}

function blogItemSlide(control, interval, stop, callback){
    e = jQuery('.post-list > div:visible:first');
    if(stop){
        jQuery('.post-list > div:visible:first').stop(true, true);
        clearTimeout(blogInt);
    }
    switch(control){
        case 'up':
            if(jQuery('.post-list > div:nth-child('+(e.index()+6)+')').length == 0){
                return false;
            }            
            e.animate({
                marginTop:'-96px'
            }, 2 * interval,function(){
                e.css({
                    marginTop:0
                }).hide();
                jQuery('.post-list > div:nth-child('+(e.index()+6)+')').fadeIn(interval);
                if(callback != null){
                    callback();
                }
            });
            break;
        case 'down':
            if(e.prev('div').length == 0){
                return false;
            }
            e.animate({
                marginTop:'96px'
            }, 2 * interval,function(){
                e.css('marginTop','0px').prev('div').fadeIn();
                if(callback != null){
                    callback();
                }
            });
            break;        
    }
}

function pageAction(){    

}

function singleAction(){
    slug = jQuery('a.page-for-posts').attr('slug');
    jQuery('#menu-main li a[slug='+slug+']').parent().addClass('current_page_parent');
    jQuery('#line').animate({
        marginLeft:0
    }, 0.6 * jQuery('#line').width(), 'linear');
}

function portfolioAction(){
    w = 0;
    jQuery('#gallery-pager-reel a').each(function(idx){
        w += 70;
        if(idx+1 == jQuery('#gallery-pager-reel a').length){
            jQuery('#gallery-pager-reel').css('width', Math.max(w, 630));
        }
    });
    portfolioInit(jQuery('#content-var .work:first'));
}

function portfolioInit(e){
    clearTimeout(portfolioTimeout);
    if(e == null || e.length == 0){
        return false;
    }
    to = 8000;
    jQuery('#content-var .work.activeSlide').children('.gallery').cycle('destroy');
    jQuery('#content-var .work.activeSlide').hide();
    jQuery('#gallery-pager a').removeClass('activeSlide');
    jQuery('#gallery-pager a#pager-'+e.attr('id').replace('work-','')).addClass('activeSlide');
    if(jQuery('#gallery-pager a.activeSlide').index() > 8){
        jQuery('#gallery-pager-reel').animate({
            marginLeft:(643 - 70 * (jQuery('#gallery-pager a.activeSlide').index()+1))
        });
    }
    e.addClass('activeSlide');
    if(e.find('.gallery-item').length > 1){
        e.children('.gallery').cycle({
            autostop:1,
            timeout:to,
            pager:'#gallery-pager-'+e.attr('id').replace('work-',''),
            delay:2000,
            end: function(){
                e.fadeOut('normal',function(){
                    if(e.next('.work').length > 0){
                        portfolioInit(e.next('.work'));
                    } else {
                        portfolioInit(e.parent().children('.work:first'));
                    }
                });
            }
        });
        e.fadeIn(1000);
    } else {
        e.fadeIn(1000);
        portfolioTimeout = setTimeout(function(){
            e.fadeOut('normal',function(){
                if(e.next('.work').length > 0){
                    portfolioInit(e.next('.work'));
                } else {
                    portfolioInit(e.parent().children('.work:first'));
                }
            })
        },(to+2000));
    }
}

jQuery(document).ready(function(){

    jQuery('#gallery-pager a').live('click',function(){
        id = jQuery(this).attr('id').replace('pager-','');
        portfolioInit(jQuery('#work-'+id));
        return false;
    });

    jQuery('.gallery-pager-control')
    .live('mouseover',function(){
        animFactor = 8;
        w = jQuery('#gallery-pager-reel').width();
        ml = parseInt(jQuery('#gallery-pager-reel').css('marginLeft').replace('px',''));
        switch(jQuery(this).attr('id').replace('gallery-pager-control-','')){
            case 'next':
                nml = (-w+643);
                jQuery('#gallery-pager-reel').animate({
                    marginLeft:nml+'px'
                },(ml+w-643) * animFactor);
                break;

            case 'prev':
                jQuery('#gallery-pager-reel').animate({
                    marginLeft:'13px'
                },(25-ml) * animFactor);
                break;
        }
    })
    .live('mouseout',function(){
        jQuery('#gallery-pager-reel').stop();
    });

    jQuery('#content-right a').live('click',function(){
        e = jQuery(this);
        if((e.attr('href') + '').indexOf(completeUrl) !== -1){
            navFade(e);
            return false;
        }
    });

    jQuery('#top-menu > li > a').click(function(){
        ul = jQuery(this).parent().children('ul');
        if(ul.is(':visible')){
            ul.slideUp();
        } else {
            jQuery('#top-menu > li > ul').hide();
            ul.slideDown();
        }
        return false;
    });

    jQuery('#top-menu > li > ul')
    .live('mouseenter',function(){
        clearTimeout(jQuery(this).stop(true, true).data('timer'));
    })
    .live('mouseleave', function(){
        elem = jQuery(this);
        jQuery.data(this, 'timer', setTimeout(function() {
            elem.slideUp();
        }, 2000));
    });

    jQuery('#qtranslate-chooser > li > a').live('click',function(){
        window.location.href = jQuery(this).attr('href') + '#!'+the_anchor();
        return false;
    })

    jQuery("#home-news").live('mouseover',function(){
        jQuery("#home-news").draggable({
            containment: 'document'
        });
    });

    jQuery("#menu-main li a").each(function(){        
        slug = jQuery(this).attr('href').replace(completeUrl,'');
        jQuery(this).attr('slug',slug);
    });

    jQuery("#menu-main li a").live('click',function(){
        var me = jQuery(this);
        if(me.parent().children('ul').length == 1){
            if(me.parent().children('ul').is(':visible')){
                me.parent('li').find('ul').slideUp();
            }
            else{
                jQuery('#menu-main li ul').slideUp();
                me.parent('li').find('ul').slideDown();
            }
        }
        else{
            if(!me.parent().hasClass('current_page_item')){
                jQuery('#top-menu li ul').slideUp();
                if(!me.parents('ul:first').is(':visible')){
                    me.parents('ul:first').slideDown();
                }
                if(me.parents('li:last').hasClass('current_page_parent')){
                    navFade(me);
                }
                else{
                    navScroll(me);
                }
            }
        }
        return false;
    });

    jQuery('.post-list-scroll').live('click',function(){
        switch(jQuery(this).attr('id')){
            case 'post-list-scroll-up':
                blogItemSlide('up',1000, true);
                break;
            case 'post-list-scroll-down':
                blogItemSlide('down',1000, true);
                break;
        }
    });

    // TEAM

    jQuery('body.team .member').live('mouseover',function(){
        jQuery('#tooltip').removeClass('top').removeClass('bottom');
        var member = jQuery(this);
        var content = jQuery.parseJSON(member.find('span').text());
        jQuery('#tooltip').html('<img src="'+baseUrl+'/wp-content/team/min/'+content.avatar+'"><div><h1>'+content.name + ((content.age) ? ' ('+content.age+')' : '')+'</h1><h2>'+content.position+'</h2><p>'+content.description+'</p></div>');
        var left;
        var top;

        if(parseInt(member.css('top').replace('px','')) > 30){
            left = parseFloat(member.css('left').replace('px',''))+parseFloat(member.css('width').replace('px',''))/2-5;
            top = parseFloat(member.css('top').replace('px',''))+parseFloat(member.css('height').replace('px',''));
            jQuery('#tooltip').css('left',Math.min(left,570) + 'px');
            jQuery('#tooltip').css('top',Math.min(top,410) + 'px');
        }
        else{
            left = parseFloat(member.css('left').replace('px',''))+40;
            top = parseFloat(member.css('top').replace('px',''))-parseFloat(member.css('height').replace('px',''))+20;
            jQuery('#tooltip').addClass('top').css('left',left + 'px').css('top',top + 'px');
        }

        if(parseInt(member.css('left').replace('px','')) >= 500){
            left = parseFloat(member.css('left').replace('px',''))-140;
            jQuery('#tooltip').css('left',left + 'px').addClass('bottom');
        }

        jQuery('#tooltip').fadeIn();
    }).live('mouseout',function(){
        jQuery('#tooltip').hide();
    });

    /*jQuery('.news-list .post').live('click',function(){
        jQuery(this).find('.view-more a').click();
    });*/

    jQuery('.wpcf7-form input[type=text], .wpcf7-form textarea').live('focus',function(){
        jQuery(this).attr('alt',jQuery(this).val());
        jQuery(this).val('');
    }).live('blur',function(){
        if(jQuery(this).val() == ''){
            jQuery(this).val(jQuery(this).attr('alt'));
        }
    });

    reloadScripts();

    if(the_anchor() == ''){
        jQuery('#preloader').fadeOut('slow');        
        offsetLine();
    } else {
        ajaxLoad(completeUrl + the_anchor(), function(){            
            jQuery('#line').css('marginLeft','0');
            offsetLine();
            jQuery('#preloader').fadeOut('slow');            
        });
    }
});
