$(document).ready(function(){

    //var isPath = window.location.pathname;
    //var isHash = window.location.hash;
    
    var cookieName = 'mikebogFont';

    //prevent double click on all submit types
    $('form').submit(function(){
        $("*[type='submit']", this).click(function() {
            return false;
        }).hide('fast');
    });


    $(window).load(function(){
        if(!window.location.hash && window.location.pathname.length === 1){
            $('div#portfolio > div.section-title h3').trigger('click');
            $('div#futured > div.section-title h3').trigger('click');
            $('div#contacts > div.section-title h3').trigger('click');
        } else {
            switch(window.location.hash)
            {
                case '#portfolio':
                    $('div#futured > div.section-title h3').trigger('click');
                    $('div#servicies > div.section-title h3').trigger('click');
                    $('div#contacts > div.section-title h3').trigger('click');
                    break;
                case '#futured':
                    $('div#portfolio > div.section-title h3').trigger('click');
                    $('div#servicies > div.section-title h3').trigger('click');
                    $('div#contacts > div.section-title h3').trigger('click');
                    break;
                case '#servicies':
                    $('div#portfolio > div.section-title h3').trigger('click');
                    $('div#futured > div.section-title h3').trigger('click');
                    $('div#contacts > div.section-title h3').trigger('click');
                    break;
                case '#aboutme':
                    $('div#portfolio > div.section-title h3').trigger('click');
                    $('div#futured > div.section-title h3').trigger('click');
                    $('div#contacts > div.section-title h3').trigger('click');
                    break;
                case '#contacts':
                    $('div#portfolio > div.section-title h3').trigger('click');
                    $('div#futured > div.section-title h3').trigger('click');
                    $('div#servicies > div.section-title h3').trigger('click');
                    break;
            };
        }
    });


    $('#header-separator')
        .after('<p id="fontlist" class="top append-bottom small"><strong>Font Selector:</strong> <a rel="georgia" href="#">Georgia</a> | <a rel="monospace" href="#">Monospace</a> | <a rel="verdana" href="#">Verdana</a> | <a rel="garamond" href="#">Garamond</a> | <a rel="times" href="#">Times</a> | <a rel="original" href="#">Default</a></p>');

    $('p#fontlist > a').live('click', function(ev){
        ev.preventDefault();
        fontStack = $(this).attr('rel');
        switch (fontStack) {
            case 'georgia':
                $('body').css({'font-family':'Constantia,"Lucida Bright",LucidaBright,"DejaVu Serif","Bitstream Vera Serif","Liberation Serif",Georgia,serif'});
                createCookie(cookieName, fontStack, 7);
                break;
            case 'monospace':
                $('body').css({'font-family':'Consolas,"Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace'});
                createCookie(cookieName, fontStack, 7);
                break;
            case 'verdana':
                $('body').css({'font-family':'Verdana,Geneva,Tahoma,sans-serif'});
                createCookie(cookieName, fontStack, 7);
                break;
            case 'garamond':
                $('body').css({'font-family':'"Palatino Linotype",Palatino,"URW Palladio L","Book Antiqua",Baskerville,"Bookman Old Style","Bitstream Charter","Nimbus Roman No9 L",Garamond,"New Century Schoolbook","Century Schoolbook","Century Schoolbook L",Georgia,serif'});
                createCookie(cookieName, fontStack, 7);
                break;
            case 'times':
                $('body').css({'font-family':'Times,"Times New Roman",Georgia,serif'});
                createCookie(cookieName, fontStack, 7);
                break;
            case 'original':
                $('body').css({'font-family':'"Helvetica Neue",Arial,Helvetica,sans-serif'});
                createCookie(cookieName, fontStack, 7);
                break;
            default:
                break;
        };
        $('div.serv-sec1').height('auto');
    });

    $('h1#logo > a').click(
        function(e){
            e.preventDefault();
            if((!window.location.hash && window.location.pathname.length === 1) && window.location.href.indexOf('idoqa.com') ==-1)
            {
                void(0);
            } else if(window.location.href.indexOf('admin')>0) {
                window.location.href = '//mikebog.com/admin';
            } else if(window.location.href.indexOf('blog')>0) {
                window.location.href = '//mikebog.com/blog';
            } else {
                window.location.href = '//mikebog.com';
            }
        }
    );

    //тут равняем нужные нам колонки
    equalHeight($('#header > div'));
    equalHeight($('div.serv-sec1'));

    $('div.section-title > h3') //тут сворачиваем секции по нажатию на title
        .css({'cursor' : 'pointer'})
        .attr('title','Свернуть / Раскрыть блок')
        .append(' ↓↑')
        .toggle(
            function(){
                $($(this).parent().next('.last')).hide(300);
                $($(this).nextAll()).hide();
                $($(this).parent()).attr('class','span-24 last section-title');
                $(this).css({'color':'#FFF', 'background':'#111', 'margin-bottom':'0', 'padding':'.5em 0 .5em .5em'});
            },
            function(){
                $($(this).parent().next('.last')).show(300);
                $($(this).nextAll()).show();
                if(window.location.href.indexOf('idoqa') > 0){
                    $(this).css({'background':'#7CBA0F', 'color':'#FFF'});
                    $($(this).parent()).attr('class','span-6 colborder section-title');
                } else {
                    $(this).css({'background':'#7CBA0F', 'color':'#FFF', 'margin-bottom':'1em'});
                    $($(this).parent()).attr('class','span-3 colborder section-title');
                }
            }
        );



    $('p.gotop > a').live('click', function(ev){ //эта штука скрулит вверх
        ev.preventDefault();
        $.scrollTo($('#header'), 500, {easing:'jswing', onAfter:
            function(){
                window.location.hash = '#header';
            }
        });
    });

    $('ol#idoqa-index li > a').live('click', function(ev){ //эта штука скрулит по странице idoqa
        ev.preventDefault();
        var target = $(this).attr('href');
        $.scrollTo($(target), 500, {easing:'jswing', onAfter:
            function(){
                window.location.hash = target;
            }
        });
    });


    $('ul#menu-list li > a, a.gotocontacts').live('click', function(ev){ //эта штука скрулит по секциям меню
        var target = $(this).attr('href');
        local = target.indexOf('#');
        if(local === -1 || window.location.href.indexOf('idoqa.com') !== -1 || window.location.pathname.length > 1) {
            return true;
        } else {
            ev.preventDefault();
            $.scrollTo(target, 500, {easing:'jswing', onAfter:
                function(){
                    window.location.hash = target;
                    if($(target + ' > div.last').is(':hidden')){
                        $(target + ' > div.section-title h3').click();
                    }
                }
            });
        }
    });

    $('ul#serv-menu > li a')
        .live('click',function(ev){ //эту штука скрулит и мигает
            ev.preventDefault();
            $(this)
                .addClass('selected')
                .parent().siblings().children().removeClass('selected');
            var target = $(this).attr('href');
            $('div#serv-sections').scrollTo($('li div'+target), 800);
        });

    

	//Caption Sliding 
	$('.boxgrid.caption').hover(function(){
		$(".cover", this).stop().animate({top:'0'},{queue:false,duration:1000, easing:'easeOutElastic'});
	}, function() {
		$(".cover", this).stop().animate({top:'160px'},{queue:false,duration:300, easing:'easeInOutElastic'});
	});

    //эта секция для админки только
    if(window.location.pathname.indexOf('admin'))
    {

    }


    if(window.location.pathname.indexOf('submit'))
    {
        if($('form#commentform > p.error').length){
            window.location.hash = '#commentform';
        }
    }


    if(window.location.pathname.indexOf('blog'))
    {

        $('p.video')
            .css({
                'width':'500px',
                'display':'block',
                'margin':'0 auto 3em'
            })
            .each(function(){
                var video = $(this).attr('link');
                var blockId = $(this).attr('id');
                addVideoPlayer(video, blockId);
            })


        $('div.post_content > h3 a')
            .parent()
            .append('&nbsp;&nbsp;<a title="Спрятать/Показать текст публикации" class="post-toggle-title" href="#">↓↑</a>');
            
        $('a.post-toggle-title').live('click', function(){
            $(this).parent().nextAll().toggle('fast');
            $(this).parents('.post_content').prev('.post_meta').children('ul').toggle('fast');
            return false;
        });

        $('label#ishumanlabel').hover(
            function(){
                $(this).next('span#humapexpl').toggle();
            },
            function(){
                $(this).next('span#humapexpl').toggle();
            }
        );

        $('input#ishuman')
            .attr('checked', false)
            .after('<input type="hidden" name="nobotsallowed" id="nobotsallowed" value="iamdumbot">')
            .live('click', function(){
                if($('input#nobotsallowed[value=\'iamdumbot\']').length)
                {
                    $('input#nobotsallowed').attr('value', 'iamhuman');
                } else {
                    $('input#nobotsallowed').attr('value', 'iamdumbot');
                }
            });


        $('form#commentform').submit(function(){
            var name = $('input#name', this).val();
            var email = $('input#email', this).val();
            createCookie('mb_commentform', name+'|||'+email, 30);
        });


        var commentInitial = readCookie('mb_commentform');
        if(commentInitial != null)
        {
            var commentFormUser = commentInitial.split('|||');
            var inputName = commentFormUser[0];
            var inputEmail = commentFormUser[1];
            //console.log(inputName+'+'+inputEmail);
            if(window.location.pathname.indexOf('blog/post'))
            {
                $('form#commentform input#name').val(inputName);
                $('form#commentform input#email').val(inputEmail);
            }
        }

    }

    var pageFont = readCookie(cookieName);
    if(pageFont !== null)
    {
        $("p#fontlist > a[rel='"+pageFont+"']").click();
        equalHeight($('div.serv-sec1'));
    }

});


function equalHeight(group) { //эта функция подгоняет колонки под одну высоту
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function addVideoPlayer(video, blockId)
{
    var loadPlayer = new SWFObject('/flash/player/player.swf','player','500','300','9','#000');
    loadPlayer.addParam('allowfullscreen','true');
    loadPlayer.addParam('allowscriptaccess','always');
    loadPlayer.addParam('allownetworking','all');
    loadPlayer.addParam('wmode','opaque');

    loadPlayer.addVariable('plugins', 'viral-2');
    loadPlayer.addVariable('viral.callout', 'mouse');
    loadPlayer.addVariable('viral.onpause', true);
    loadPlayer.addVariable('viral.oncomplete', true);
    loadPlayer.addVariable('viral.functions', 'embed');
    
    loadPlayer.addVariable('file', video);
    loadPlayer.addVariable('skin', '/flash/player/bekle.swf');
    loadPlayer.addVariable('frontcolor', '#FFFFFF');
    loadPlayer.addVariable('controlbar', 'over');
    loadPlayer.write(blockId);
}