(function($){
    $.fn.navigation= function(options) {

        var defaults = {
            step: 290,
            efDuration: 1000,
            position: 0
        }
        
        var selector = $(this);
        var opts     = $.extend(defaults, options);

        return this.each(function() {

            var mainObj  = selector;
            var boxObj   = mainObj.find('div:first');
            var mainObjH = mainObj.height();
            var boxObjH  = boxObj.height();
            var eqBlocks = Math.ceil( boxObjH / mainObjH )-1;

            var upNav    = $('.nav-small-top');
            var downNav  = $('.nav-small-bottom');

            mainObj.css('position','relative');
            boxObj.css('position','relative');

            function actualizeNavigation(){

                if ( opts.position == 0 ){
                    upNav.hide();
                } else upNav.show();

                if ( opts.position < eqBlocks ){
                    downNav.show();
                } else downNav.hide();
            }
 
            function scrollDown(){
                ++opts.position;
                actualizeNavigation();
                boxObj.animate({
                    top: '-=' + opts.step
                }, opts.efDuration);
            }
        
            function scrollUp(){
                if ( opts.position > 0 ){
                    --opts.position;
                    actualizeNavigation();
                    boxObj.animate({
                        top: '+=' + opts.step
                    }, opts.efDuration);
                }
            }

            actualizeNavigation();

            if (mainObjH < boxObjH){
                downNav.live('click',function(event){
                    scrollDown();
                });
        
                upNav.live('click',function(event){
                    scrollUp();
                });
            }
        });
    };
})(jQuery);

function showSocialsF(){
    var socf ="<div id='socialf'><div id='twitter'><a href='http://twitter.com/janakirschner'></a></div><div id='facebook'><a href='http://facebook.com/janakirschner'></a></div><div id='myspace'><a href='http://myspace.com/janakirschner'></a></div></div>"

    $( socf ).insertAfter( $('#menu') );
    $('#socialf').show();
}

function cycleGallery(){
    $('#pic-gallery').cycle({
        fx:     'fade',
        speed:   300,
        timeout: 0,
        next:   '#next-pic, #g-right',
        prev:   '#prev-pic, #g-left'
    })

    $('#next-pic, #prev-pic, #g-right, #g-left').css('cursor', 'pointer');
    $('#next-pic, #g-right').bind({
        mouseenter: function(){
            $('#g-right').show();
        },
        mouseleave: function(){
            $('#g-right').hide();
        }
    })
    $('#prev-pic, #g-left').bind({
        mouseenter: function(){
            $('#g-left').show();
        },
        mouseleave: function(){
            $('#g-left').hide();
        }
    })

}

function clickbox(obj, activeClassName, forced){
    var active_class_name = (activeClassName) ? activeClassName : "active";
    $(obj).each(function (count, el){
        if ( $(this).find("a").size() > 0 || forced == true){
            $(el)
            .bind("mouseenter mouseleave", function (){
                $(this).toggleClass(active_class_name).css('cursor','pointer');
            })
            .bind("click", function(){
                $(location).attr('href', $(this).find('a:first').attr('href') );
            });
        }
    });
}

function is_iphone(){
    var agent=navigator.userAgent.toLowerCase();
    var iphone = (agent.indexOf('iphone')!=-1);
    if (iphone) {
      return true;
    } else {return false;}
}

function generateVideoPlayer(){
    var videoPath = $('#video-url').text();

    var so = new SWFObject("swf/video_player.swf", "player_lite", "600", "400", "9", "#000000");
    so.addParam("scale", "noscale");
    so.addParam("allowFullscreen", "true");
    so.addParam("allowScriptAccess", "sameDomain");
    so.addParam("wmode", "transparent");


    so.addVariable("myVideoPath", videoPath);
    so.addVariable("autoStart", "true");
    so.addVariable("autoLoop", "false");
    so.addVariable("soundOff", "false");
    so.addVariable("player_width", "600");
    so.addVariable("player_height", "400");


    so.addVariable("player_bg_color", "0xf7f8f2"); // player background
    so.addVariable("panel_bg_color", "0x4c433c"); // panel background
    so.addVariable("bt_play_color", "0x574e49"); // symbol play
    so.addVariable("bt_pause_color", "0x574e49"); // symbol pause
    so.addVariable("progress_bar_cursor_color", "0xf8f8f8"); // progress cursor
    so.addVariable("progress_bar_fluid_color", "0xd75defb"); // progress fluid
    so.addVariable("progress_bar_buffer_color", "0xc9c5bc"); // progress buffer
    so.addVariable("progress_bar_bg_color", "0xf7f8f2"); // progress background
    so.addVariable("bt_volume_on_color", "0xc9c5bc"); // speaker in state on
    so.addVariable("bt_volume_wave_color", "0xc9c5bc"); // the 3 vertical lines when the speaker is in state on
    so.addVariable("bt_volume_off_color", "0xc9c5bc"); // speaker in state off
    so.addVariable("bt_volume_cross_color", "0xff0000"); // the cross when the speaker is in state off

    so.write("objectMedia");
}

// // try {
//        xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
//        xhr.send( (type !== "GET" && s.data) || null );
//
//    } catch( sendError ) {
//        jQuery.ajax.handleError( s, xhr, null, e );
//
//    }

function parseJSON( data ) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }

    data = jQuery.trim( data );

    if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
        .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {

        // Try to use the native JSON parser first
        return window.JSON && window.JSON.parse ?
        window.JSON.parse( data ) :
        (new Function("return " + data))();

    } else {
        jQuery.error( "Invalid JSON: " + data );
    }
}

function generateHomepageFlashButoon(){
    $('#hp-player').flash({
        src: 'swf/homepage_player.swf',
        wmode: 'transparent',
        width: 35,
        height: 35,
        flashvars: {
            filename: $('#hiddenSource').text(),
            id      : 1,
            service : 'kirschner',
            maxID   : 1
        }
    });
}

function emailIt(){
    $('.email input').val('@');
}

function hoveredArrows(){

    var efDuration = 200;

    var rightArrows = ['nav-right-v-1','nav-right-v-2','nav-right-v-3','nav-right-v-4'];
    $(rightArrows).each(function (cnt, el){

        var newElement = $('#' + el).clone().addClass('rightArrow').insertAfter('#' + el);

        $('#' + el + '.rightArrow').live('mouseenter', function (){
            $(newElement).find('img').animate({
                left: '+=5'
            }, efDuration, function() {

            });
        })

        $('#' + el + '.rightArrow').live('mouseleave', function (){
            $(newElement).find('img').animate({
                left: '-=5'
            }, efDuration, function() {

            });
        })
    })



    var leftArrows = ['nav-left-v-1','nav-left-v-2','nav-left-v-3','nav-left-v-4'];
    $(leftArrows).each(function (cnt, el){

        var newElement = $('#' + el).clone().addClass('leftArrow').insertAfter('#' + el);

        $('#' + el + '.leftArrow').live('mouseenter', function (){
            $(newElement).find('img').animate({
                left: '-=5'
            }, efDuration, function() {

                }
                );
        })

        $('#' + el + '.leftArrow').live('mouseleave', function (){
            $(newElement).find('img').animate({
                left: '+=5'
            }, efDuration, function() {

                }
                );
        })
    })
}


function submenuArrowEvents(){

    var rObj = $('.right');
    var rOriginalPath = rObj.find('img').attr('src');
    var lObj = $('.left');
    var lOriginalPath = lObj.find('img').attr('src');

    $(rObj).bind({
        mouseenter: function (){
            $(this).find('img').attr('src','images/arrow-right-submenu-active.png');
        },

        mouseleave: function(){
            $(this).find('img').attr('src',rOriginalPath);
        }

    })

    $(lObj).bind({
        mouseenter: function (){
            $(this).find('img').attr('src','images/arrow-left-submenu-active.png');
        },

        mouseleave: function(){
            $(this).find('img').attr('src',lOriginalPath);
        }

    })

}


        function clickEvent(){
            $(this).parent().find('.active').removeClass('active');
            $(this).addClass('active');

            $(this).find('a:first').animate({
                top: '0'
            }, 200);

            var $this = $(this).find('a');
            $('#detail-infos').load($this.attr('href') + ' #detail-infos > div', function(){
                Cufon.refresh();
            })
        }

        function mouseenterEvent(){
            if ( $(this).hasClass('active') != true ){
                $(this).css('cursor','pointer');
                $(this).find('a:first').css({'position':'relative'}).animate({
                    top: '-2'
                }, 200);
            }
        }

        function mouseleaveEvent(){
            if ( $(this).hasClass('active') != true ){
                $(this).find('a:first').animate({
                    top: '0'
                }, 200);
            }
        }

        function discTimeLine(){
            $('#bio3-content #years .item, #dis1-content #years .item').bind({
                click:      clickEvent,
                mouseenter: mouseenterEvent,
                mouseleave: mouseleaveEvent
            });
        }




$(document).ready(function(){
    if (is_iphone()) $('body').attr('class','');
})

$(window).bind('load', function(){

    /******************************** HOVER EFFECT FOR ARROWS *****************/
    hoveredArrows();

    /******************************* CLICK BOXES ******************************/
    clickbox($('#news-list .item-wrapper'));
    clickbox($('#media-list-wrapper .item-wrapper'));
    
    

    /******************************** HIDE BIO SUB MENU ***********************/
    if ( $('#menu .main.active').text().toLowerCase() != "biography" ){
        //$('#menu .main').eq(1).parent().find('.sub').hide();
    }

    /******************************** CUFON ********************************/
    Cufon.replace('#header-text, #header-text-bio1 > div, #homepage-news .title, #news-body h1, #album-production h2, #bandsman-detail #instruments, #contact-content #sub-head, #contact-content  h2, #contact-content label, #year-items > div', {
        hover: true,
        fontFamily: 'utopia'
    });

    Cufon.replace('#album-name h1, #media-type, #bandsman-detail h1, #detail-infos #year', {
        hover: true,
        fontFamily: 'solomon'
    });
    /**************************************************************************/

    $.ajaxSetup({
        cache: false,
        data : null
    });


    /******************************  MENU EVENTS  *****************************/
    $('#menu .main a, #menu #media a').bind({
        dthis: $(this),
        click: function (event){
            var $this = $(this);
            var itemName = $this.text().toLowerCase();
            event.preventDefault();

            $('#menu .main').removeClass('active');
            //$(this).parents('.main').addClass('active');
            $(this).parents('.m-item').find('.main').addClass('active');

            $('.preloader').remove();

            var itemClicked  = (itemName == 'foto' || itemName == 'video') ? 'media' : itemName;

            $("<div class='preloader " + itemClicked + "' style='display: none;'></div>").insertBefore('#document');
            $('.preloader').fadeIn('normal');

            $('#content').load($this.attr('href') + ' #content > div', function(){
                // success events
                if (!is_iphone())
                    $('body').attr('class', itemClicked);
                $('.preloader').fadeOut('slow');

                /** google analytics */
                var pageTracker = _ga._getTracker('UA-17604426-4', '.janakirschner.com');
                pageTracker._trackPageview();

                if (itemName == "home"){
                    generateHomepageFlashButoon();
                    showSocialsF();
                } else { 
                    $('#socialf').remove();
                }

                if (itemName == "biography"){
                    $('#menu > div').eq(1).find('.sub').remove();
                    var fitem = $('#bio-first-sub').html();
                    $(fitem).appendTo($('#menu > div').eq(1))
                    submenuArrowEvents();
                } else {
                    $('#menu > div').eq(1).find('.sub').remove();
                }
                
                if (itemName == "discography"){
                    discTimeLine();
                    clickbox('.album');
                }

                if (itemName == "foto" || itemName == "video"){
                    if (itemName == "video") generateVideoPlayer();

                    $('#media-list-wrapper').navigation();
                    clickbox($('#media-list-wrapper .item-wrapper'));

                    cycleGallery();
                }

                if (itemName == "band"){
                    $('#band-list-wrapper').navigation({
                        step: 297
                    });
                    $('#band-list-wrapper .item').eq(0).addClass('active');
                    clickbox($('#band-list-wrapper .item-wrapper'));
                }

                if (itemName == "live"){
                    $('#live-list-wrapper').navigation({
                        step: 297
                    });
                    clickbox($('#live-list-wrapper .item-wrapper'));
                }

                if (itemName == "contact"){
                    emailIt();
                }

                $('#menu > div').eq(2).find('.sub').hide();

                hoveredArrows();
                Cufon.refresh();
            });
            
        }
    });

    $('#menu #media').parent().bind({
        mouseover: function(){
            //alert( $.trim($(this).find('.main').text().toLowerCase()) );
            if ( $.trim($(this).find('.main').text().toLowerCase()) == "media"){
                $(this).find('.sub').show();
            }
        },

        mouseleave: function (){
            if ( $.trim($(this).find('.main').text().toLowerCase()) == "media"){
                $(this).find('.sub').hide();
            }
        }
    });
    /******************************** END MENU EVENTS *************************/
    /*(****************************** SUB MENU ********************************/
    submenuArrowEvents();
    /**************************************************************************/

    /********************  DISCOGRAPHY            *****************************/
/* TODO */
    discTimeLine();
    clickbox('.album');
    
    $('#dis1-content #years .item .link').live('click', function (event){
        $('#years .item').find('.albums').hide();
        $(this).parents('.item').find('.albums').fadeIn('slow');

        event.preventDefault();
    });

    $('#dis1-content #years .item .album a').live('click', function(){
        $(location).attr('href', $(this).attr('href'));
    })

    /**************************** IMAGE CACHE *********************************/
    var images = [ 'images/homepage.jpg', 'images/biography.jpg', 'images/discography.jpg', 'images/media.jpg', 'images/live.jpg', 'images/contact.jpg'];

    jQuery.each(images, function(i) {
        images[i] = new Image();
        images[i].src = this;
    });

})

