$(function(){
    //only put stuff in here if you want it to run on every page!!
    $('.hide').hide();   
    
    $('body').addClass('js-enabled'); 
 
    youtubeAccess(function() {
        $('param').each(function(){
            if($(this).attr('value').indexOf('youtube.com') > -1){                
                $('<div id="no-youtube">no youtube access</div>').insertAfter($(this).parent());
                $(this).parent().remove();
            }
        });
        $('object').each(function(){
            if($(this).attr('data').indexOf('youtube.com') > -1){
                $('<div id="no-youtube">no youtube access</div>').insertAfter($(this));
                $(this).remove();            
            }
        });    
    });
    /*   
    if(!youtubeAccess()) {
        $('param').each(function(){
            if($(this).attr('value').indexOf('youtube.com') > -1){                
                $('<div id="no-youtube">no youtube access</div>').insertAfter($(this).parent());
                $(this).parent().remove();
            }
        });
        $('object').each(function(){
            if($(this).attr('data').indexOf('youtube.com') > -1){
                $('<div id="no-youtube">no youtube access</div>').insertAfter($(this));
                $(this).remove();            
            }
        });
    }*/


    //onchange, submit
    $('.onchange').change(function(){
        var baseurl = $(this).closest("form").attr('action');
        var segment = $(this).attr('name');
        var value = $(this).attr('value');

        window.location.href = baseurl + '/' + segment + '/' + value;
        return false;
    });
    
    $('#no-js-submit-button').css('display','none');
    $('#tag-filters select').change(function(){
        $form = $(this).closest("form");
        var baseurl = $form.attr('action');
        var tags = $(this).attr('value');
                
        $('.tag').not($(this)).each(function(){
            if($(this).attr('value')!=''){
                if(tags!=''){
                    tags+=',';
                }
                tags +=$(this).attr('value');    
            }
        });

        window.location.href = baseurl + '/tags/' + tags;
        return false;
    });
    
    $('#sb-search-form').submit(function(){
        var baseurl = $(this).attr('action');
        var search = $('#searchsb').attr('value');
        search = search.replace(/[^a-zA-Z 0-9]+/g,'');
        window.location.href = baseurl + '/search/' + search;
        return false;
    });

    //scrollables
	$('.scroll-box, .scrollable').jScrollPane({
	   scrollbarWidth: 21,
	   showArrows: true
	});
	
	$('#playlist-wrapper').equalHeights();

	
	
	//read more 
    $('.read-more').condense({
        moreText : 'Read more',
        ellipsis : '',
        moreSpeed : 'fast',
        delim : '</p>'
    });
	
	//slide down
	$('.more-link').css('display','inline');
	var displayed_list = $('.more-link').parent().siblings('.lists:first');
    $('.more').css('display','none'); 
	$('.slide-down').click(function(){
	   if(!$(this).hasClass('dont-hide')){
	       $(this).hide();
	   }else{
	       $(this).css('cursor', 'default');
	   }
	   if($(this).parent().siblings('.more').slideDown().length < 1){
    	   $(this).parent().parent().siblings('.more').slideDown();
	   }
	   return false;
	});
	
	
	//whiteboard popup
    $('.popup').popupWindow({ 
        height:500,
        width:800,
        centerScreen:1
    });
    
    
    //magazine issue nav

    $('#issues-nav li ul:not(#issues-nav li.current-year ul)').hide();

    $('#issues-nav li').click(function(){
        
        $('#issues-nav li ul').hide();
        
        $('#issues-nav li.current-year').removeClass('current-year');
        
        $(this).addClass('current-year');
        
        //$(this).parent().addClass('current-issue');
        
        $(this).children().next().show();
    });

    
    //registration info/help bubbles
    $(".help").click(function(){
        /*
        BR: BG to look at this on friday
        var $temp = $(this);
        */
        
        $(this).next().show();
        
        /*
        $(document + ":not(.help)").click(function(){
            console.log('test');
            

            //if($temp.next().not(":visible") {
                console.log("visable");
                $temp.next().hide();
            //}

        });

        $(".su-reg-help-box-wrapper").click(function(){return false;});
        */

        $(this).next().css({
            "margin-left" : 370,
            "margin-top" : -27
        });
        
    });
    
    $(".su-reg-help-box-close").click(function(){
        $(this).parent().parent().hide();
        return false;
    });
    
    
    //my sing up pull down
    $('#mysingup').click(function(){
        if(!$(this).hasClass('locked')){
            pulldown('open','My Sing Up', '/do/mysingup/index/index/', '#my-singup-wrapper','#mysingup', 'Close');
        }else{
            pulldown('close','My Sing Up','','#my-singup-wrapper','#mysingup');
        }
        return false;
    });
    
    //remove favourited items within my sing up
    $('.mysingup-remove-from-favourites').click(function() {
    	var url = $(this).attr('href');
    	var el = $(this);
        
    	$.ajax({
    		type: "POST",
    		url: url,
    		success: function(response) {
    			if(parseInt(response)) {
    				el.parent().slideUp('slow');
                }
    		}
    	});
    	return false;
    });
    
    //login pull down
    $('#login').click(function(){
        if(!$(this).hasClass('locked')){
            pageTracker._trackPageview('/login/pagetop');
            pulldown('open', 'Login', '/do/mysingup/index/login/', '#my-singup-wrapper', '#login', 'Close');
        }else{
            pulldown('close','Login','','#my-singup-wrapper','#login');
        }
        return false;
    });        
    
    //lyrics changer
    $('#lyrics h3 a').click(function(){
        langId = $(this).attr('rel');
        $('#lyrics a.active').removeClass('active');
        $(this).addClass('active');
        $('.language').hide();
        $('#'+langId).show();
        return false;
    });
    
    
    //nag overlay
    $('.nag').colorbox({
        href : "/do/mysingup/index/modallogin/",
        width : "340px",
        initialWidth : "0",
        initialHeight : "0",
     // height : "230px",
     // initialHeight : "230px",
        scrolling : false,
        transition : 'none',
        close : ""
    }, function(el){    //for the nag on training course booking for that takes user to registration lite
        if($(this).attr('href') == "/registration/lite-registration/stage-1/") {
            var regLiteLink = $(this).attr("href");
            $('#modal-register').attr('href', regLiteLink);
        }
    });
    
    // new singup limited downloads
    
    $('.do-download').colorbox({
        href : function() {
            // This feels dirty. Is there a better way?
            var rel = encodeURI($(this).attr('rel'));
            var redir = encodeURI($(this).attr('href'));
            var ret = "/do/songbank/download/usecredit/?l=" + redir + '&rel=' + rel;
            return ret;
        },
        initialWidth : "0",
        initialHeight : "0",
        scrolling : false,
        transition : 'none',
        close : ""
    }, function(el){
        
    });
    
    // Change Class of Button that leads to Modal Popup if "Download" in Modal is clicked 
    
    $('#dl-modal a.action').live('click', function(){
    	song_id = $(this).attr('rel');
    	//Remove the do-download class from the track and close colorbox
    	if(window.location.href.indexOf('song-bank/song-detail') == -1){
	    	$('.dl-button[rel="' + song_id +'"]').addClass('in-library').removeClass('do-download, cboxElement');
    	}else{ //If we're on a song-detail page we'll change the classes of all the download links, as its' all one song...
	    	$('.dl-button').addClass('in-library').removeClass('do-download, cboxElement');    		
    	}
    	$.colorbox.close();
    });
            
    //---------
    
    
    //no stream message
    $('.no-stream').colorbox({
        href : "/do/default/index/nostream/",
        width : "340px",
        initialWidth : "0",
        initialHeight : "0",
     // height : "230px",
     // initialHeight : "230px",
        scrolling : false,
        transition : 'none',
        close : ""        
    });
    
    //
    
    
    //comments
    $('#comment-form form button').click(function(){
        $('#comment-form').slideUp(function(){
            $(this).html('<h2>Thank you! Your comment has been added!</h2>').slideDown();
        });
        $.ajax({
            url : $('#comment-form form').attr('action'),
            type : 'POST',
            data : $('#comment-form form').serialize(),
            success : function(data){
                $('#comment-empty').remove();
                $('#comment-list').append(data);
            }
        });        
        return false;
    });   
    
    //fullscreen
    $('.openFullscreen').click(function(){
        var fullscreen = window.open($(this).attr('href'), 'suFull', 'fullscreen=yes,location=no,menubar=no,toolbar=no,width=' + window.screen.width + ',height=' + window.screen.height);
        fullscreen.moveTo(0,0);
        return false;
    });
    
    //my sing up form
    $('#mysingup-form input, #mysingup-form textarea').attr('readonly', 'readonly').addClass('not-form');
    if($.browser.msie){
        $('#mysingup-form button').width(0);
    }else{
         $('#mysingup-form button').hide();
    }
    
    $('#edit-mysingup').click(function(){
        $('#mysingup-form input, #mysingup-form textarea').attr('readonly', '').removeClass('not-form');
        if($.browser.msie){
            $('#mysingup-form button').width('120px');
        }else{
             $('#mysingup-form button').show();
        }
        return false;
    });
    
    $('#mysingup-form button').click(function(){
        $(this).attr('readonly', 'readonly').text('Sending...');
        $.ajax({
            url : $('#mysingup-form').attr('action'),
            type : 'POST',
            data : $('#mysingup-form').serialize(),
            success : function(data){
                $('<p>'+data+'</p>').appendTo('#mysingup-form');
                $('#mysingup-form input, #mysingup-form textarea').attr('readonly', 'readonly').addClass('not-form');
                $('#mysingup-form button').hide();                
            }
        });
        return false;
    });
    
    // comment hiding
    $('.comment-hide').click(function(e) {
        var answer = confirm("Sure you want to delete that?")
    	if (answer){
    		$.get(e.currentTarget.href);
            $(e.currentTarget).parent().parent().parent().parent().remove();
    	}
        return false;
    });
    
    // comment typo3
    $('.comment-typo3').click(function() {
        var fullscreen = window.open($(this).attr('href'), 'suFull', ',location=no,menubar=no,toolbar=no,width=600,height=600');
        return false;
    });
    
    // comment hiding
    $('.comment-flag:not(.nag)').click(function(e) {
        $.get(e.currentTarget.href);
        $(this).replaceWith('<span>Comment flagged</span>');
        return false;
    });
});


function pulldown(action, label, url, wrapper, button, altLabel){
    if(action=='open'){
        $(button).addClass('locked').text('Loading...');
        $.get(url,function(data){
            $(wrapper).html(data);
            if(altLabel != ''){
                $(button).text(altLabel);
            }else{
                $(button).text(label);
            }
            $('#page-wrapper').animate({'margin-top':'0px'});
        });    
    }else{
        $(button).removeClass('locked');
        $(button).text(label);
        $('#page-wrapper').animate({'margin-top':'-208px'},500,function(){
            $(wrapper).empty();
        });
    }
}

function youtubeAccess(noAccessCallback)
{
    var access = true;

    var image = new Image();
//    image.src = "http://youtube.com/favicon.ico";
    image.onload = function(){
        // The user can access youtube
        access = true;
    };
    image.onerror = function(){
        // The user can't access youtube
        access = false;
        noAccessCallback();
    };
    image.src = "http://youtube.com/favicon.ico";
    return access;
}

