
var playlist = [];
var current_track = 0;
var playNext;
var ie_version = getInternetExplorerVersion();
var show_effects = (ie_version >= 8 || ie_version < 0);

function getInternetExplorerVersion(){
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer'){
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
    }
    return rv;
}

function getPageSize() {

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) {	// all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }

    return [pageWidth,pageHeight];
}

function stylizeText(){

    //self explanitory i think
    Cufon.replace('h1',{
        fontFamily: 'Big Top'
    });
    Cufon.replace('p',{
        fontFamily: 'OldStyle 1'
    });
    Cufon.replace('.bubble',{
        fontFamily: 'Bellamy'
    });
}


function showAlt(element){
    
    
    var text_id = element.id+'_text';

    //check if box has already been created
    if(!$(text_id)){
        
        //create text box
        var textbox = document.createElement('div');

        textbox.className = 'alt_text';
        textbox.setAttribute('id',text_id);


        document.body.appendChild(textbox);


        $(text_id).absolutize();
        $(text_id).update(element.alt);
        $(text_id).hide();

        $(text_id).setStyle({
            height: '20px',
            width: 'auto'
        })

    }

    //clone position to text and center

    dif_width = element.getWidth()-$(text_id).getWidth(); //difference
    offset = Math.round(dif_width/2);

    if(show_effects){
        offset_top = -50;
    }else{
        offset_top = -25;
    }

    Element.clonePosition($(text_id),element,{
        setHeight:false,
        setWidth:false,
        offsetLeft:offset,
        offsetTop:offset_top
    });

    if(show_effects){
        $(text_id).appear({
            duration: 0.3,
            from: 0,
            to: 0.7,
            onComplete: setTimeout(function(){
                $(text_id).fade({
                    duration: 0.3
                });
            },1000*1.5)
        });
    }else{
        $(text_id).show();
        setTimeout(function(){
            $(text_id).hide()
        },1000*1.5)
    }
//set timeout to fade

}


function initHover(){
    
    $$('.nav_image').each(startHover);
    
}

function startHover(element){
    if(show_effects){
        element.offset = element.cumulativeScrollOffset();
        element.dimensions = element.getDimensions();

        element.hovering = false;
        hoverdistance = 10;
        hduration = 0.5;
        hzoom = 1.1;

        Event.observe(element, 'mouseover', function(event) {
            //element.lower.cancel();
            if(!element.hovering){
                element.hovering = true;
                element.raise = new Effect.Move(element, {
                    x: element.offset.left,
                    y: element.offset.top-hoverdistance,
                    mode: 'absolute',
                    duration:hduration,
                    transition: Effect.Transitions.spring,
                    onComplete: showAlt(element)

                });

            }


        });

        Event.observe(element, 'mouseout', function(event) {
            if(element.raise != null){
                element.raise.cancel();
            }
            $(element.id+'_text').fade({
                duration: 0.3
            });
            if(element.hovering){
                element.hovering = false;
                element.lower = new Effect.Move(element, {
                    x: element.offset.left,
                    y: element.offset.top,
                    mode: 'absolute',
                    duration:hduration,
                    transition: Effect.Transitions.spring
                });

            }

        });
    }else{
        Event.observe(element, 'mouseover', function(event) {
            showAlt(element)
        });
        Event.observe(element, 'mouseout', function(event) {
            $(element.id+'_text').hide()
        });
    }
}

function initHash(){

    //load hash when clicked
    addHashLoader = function(element){ 
        Event.observe(element, 'click', function() {
            loadHash(element);
        })
    }

    //find all links with a hash and add the hashloader click event
    $$('a[href^=#]').each(addHashLoader);

    //load the hash from the location.hash if possible
    loadHash(false);
}

function loadHash(user_hash){

    var hash;

    //if hash is explicitly set, pull it from the href of link...otherwise use the location.hash
    if(user_hash){
        hash=user_hash.readAttribute('href');
    }else{
        hash=location.hash;
    }

    //if we have a hash load it...otherwise go to the home section
    if (hash){
        if(hash.length > 1){
            category = hash.substr(1);
            loadContent(category+'.php','');
            Sound.play('sounds/effect_'+category+'.mp3');
        }else{
    //do nothing
    }
    }else{
        loadContent('home.php');
    }

    return false;
}

function loadContent(url,post_vars){

    //older browsers (specifically IE) don't like some of the effects so the goal is to avoid some.
    if(show_effects){
        
        var fade_time = 1;

        //hide the aside/sidepanel
        new Effect.Move('aside',{
            x:-250,
            y:0,
            mode:'absolute',
            duration:1,
            transition: Effect.Transitions.sinoidal
        });

        //fade out the content
        new Effect.Opacity('content',{
            to:0,
            duration:fade_time
        });

        //show a waiting cursor
        document.body.setStyle({
            cursor:'wait'
        });

        //NOTE: this could possibly go into an afterFinish callback in the fading of the content
        setTimeout(function(){
            new Ajax.Updater('content',url,{
                parameters:post_vars,
                evalScripts: true,
                onComplete: function(){

                    //show the aside (if hidden) and then place it.
                    $('aside').show();
                    new Effect.Move('aside',{
                        x:0,
                        y:0,
                        mode:'absolute',
                        duration:1,
                        transition: Effect.Transitions.sinoidal
                    });

                    //refresh all cufon fonts
                    Cufon.refresh();

                    //fade in the content
                    new Effect.Opacity('content',{
                        to:1,
                        duration:fade_time
                    });

                    //reset the cursor
                    document.body.setStyle({
                        cursor:'default'
                    });
                }
            });
        },1000*fade_time);

    }else{
        //hide the contents
        $('aside').hide();
        $('content').hide();

        //show contents after loaded
        new Ajax.Updater('content',url,{
            parameters:post_vars,
            evalScripts: true,
            onComplete: function(){
                $('aside').show();
                $('content').show();

                //refresh fonts
                Cufon.refresh();
            }
        });
    }
}


function initPlaylist(){

    //load playlist
    new Ajax.Request('sounds/playlist.php', {
        onComplete: function(response){

            //decode JSON formatted playlist
            playlist = response.responseText.evalJSON();

            // get random song from playlist
            current_track = Math.floor(Math.random()*(playlist.length-1));

            // set a 20 minute timeout to avoid bandwidth limits
            setTimeout(stopAudio,1000*60*20);
        }
    });
}

function previousAudio(){

    //stop whatever is playing
    stopAudio();

    //increment pointer
    current_track -= 1;

    //move pointer to end if at the beginning of playlist
    if(current_track < 0){
        current_track = (playlist.length)-1;
    }

    //play audio at new pointer
    playAudio();
}

function nextAudio(){
    //stop whatever is playing
    stopAudio();

    //increment pointer
    current_track += 1;

    //move pointer to beginning if at the end of playlist
    if(current_track >= playlist.length){
        current_track = 0;
    }

    //play audio at new pointer
    playAudio();
}

function playAudio(){

    //toggle icons
    $('sound_play').hide();
    $('sound_stop').show();
    $('now_playing').show();

    //enable the sound
    Sound.enable();

    //get current song in playlist
    var filename = playlist[current_track].song_filename;
    var length = playlist[current_track].song_length;

    //start playing song
    sound_path = 'http://www.lux666.com/sounds/playlist/'+filename;
    Sound.play(sound_path , {
        replace:true
    });

    //update the artist-title display
    $('song_artist').update(playlist[current_track].song_artist);
    $('song_title').update(playlist[current_track].song_title);

    //add cufon font for the artist-title display (also updates all other p tags)
    Cufon.refresh('p');

    //play the next song when the current song is over
    playNext = setTimeout(function(){
        nextAudio();
    },Math.ceil(1000*length));
}

function stopAudio(){

    //toggle icons
    $('sound_stop').hide();
    $('sound_play').show();
    $('now_playing').hide();

    //avoid playing the next song
    clearTimeout(playNext);

    //replace audio with...nothing
    Sound.enable();
    Sound.play('http://www.lux666.com/sounds/record_scratch.mp3',{
        replace:true
    });
}

function addOverlay(behind_element){

    behind_element.setStyle({
        zIndex: 9999,
        position:'absolute',
        display:'none',
        position:'absolute',
        left:'0px',
        top:'0px',
        width:'80%'
    });

    document.body.appendChild(behind_element);

    //initialize overlay element
    var overlay = new Element('div',{
        id:'user_overlay'
    });

    //get page size
    page_size = getPageSize();

    //make cover entire page
    overlay.setStyle({
        position:'absolute',
        backgroundColor:'#000000',
        width: page_size[0]+'px',
        height: page_size[1]+'px',
        left: '0px',
        top: '0px'
    });

    //make sure it gets placed properly behind element specified
    behind_element.insert({
        'before': overlay
    });

    //set opacity of overlay
    overlay.setOpacity(0.9);

    var special_left = Math.round(((document.viewport.getScrollOffsets().left+document.viewport.getDimensions().width)-behind_element.getWidth())/2);
    var special_top = Math.round(((document.viewport.getScrollOffsets().top+document.viewport.getDimensions().height)-behind_element.getHeight())/2);
    
    //allow padding if content is huge
    var padding = 20;
    if(special_top < padding){
        special_top = padding;
    }

    //position the content
    behind_element.setStyle({
        left:special_left+'px',
        top:special_top+'px'
    });
    behind_element.appear();

    //add close button
    var close_button = new Element('img',{
        id:'user_overlay_close',
        src:'images/close.png',
        alt:'close'
        
    });

    behind_element.insert({
        'before': close_button
    });


    $('user_overlay_close').setOpacity(0);
    close_button.style.cursor = 'pointer'; //TODO: setstyle not working for cursor?
    
    

    positionCloseButton = function(){
        //position close button
        $('user_overlay_close').setStyle({
           position:'absolute',
           top:(document.viewport.getScrollOffsets().top+15)+'px',
           left:(document.viewport.getDimensions().width-60)+'px'
        });
    }

    setTimeout(function(){
        positionCloseButton();
        $('user_overlay_close').appear();

    },1000);

    close_button.observe('click',function(){
        removeOverlay(behind_element);
    });

    Event.observe(window, 'scroll', function(){
       positionCloseButton();
    });

    //close when clicked
    overlay.observe('click',function(event){
        event.stop();
        removeOverlay(behind_element);
    });

    //close when escape is pressed
    document.observe('keydown', function(event) {
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();

        if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
            removeOverlay(behind_element);
        }
    });
    Cufon.refresh();
}

function removeOverlay(element){

    //if exists, fade out and remove
    if($('user_overlay') != null){
        $('user_overlay_close').fade({
            duration:0.5,
            afterFinish:function(){
                 $('user_overlay_close').remove();
            }
        });
        $('user_overlay').fade({
            afterFinish:function(){
                if($('user_overlay') != null){
                    $('user_overlay').remove();
                    
                }
            }
        })
        element.fade({
            duration:0.3
        });
    }
}
    

