/*
	Script: Main
	Project: Sonic-B.A.N.G.
	Author: Primal Consultancy
	Last Update: 22 February 2012
	
	Table of Contents:
						Inactive anchors
						Tabs
						Dropdowns
						Notification bar
						Searchbox
						Contest nominations
						Music lists - transitions
						Empty inputs
						Tiny MCE settings
						Help tooltips
						Charts positions
						Profile functionality
						Scouts registration toggle
						Styling file inputs
						Scrolling player, search
*/

jQuery(document).ready(function($) {
	
	/* INACTIVE ANCHORS
	--------------------------------------------------------------------------------------- */
	$('a[href=#]').click(function(e){
		e.preventDefault();
	});
	
	/* TABS
	--------------------------------------------------------------------------------------- */
	$(".tabs-content>div").hide();
	$(".tabs-nav a:first").addClass("active"); // Add "active" to first tab
	$(".tabs-content>div:first").show(); 

	// Rotate
	var rotation;
	var rotateSpeed = 4000;
	function startRotation() {
		rotation = setInterval(function(){
			var activeTab = $(".tabs-nav a.active");
			var nextTab = activeTab.parent("li").next().children("a");
			if (nextTab.length == 0) {
				nextTab = $(".tabs-nav a:first");
			}
			$(".tabs-content>div").hide();
			var nextDiv = $(nextTab).attr("href"); //Find the href attribute value to identify the active tab
			$(nextDiv).fadeIn(); // Fade in the active ID content
			$(".tabs-nav a").removeClass("active");
			$(nextTab).addClass("active"); // Add "active" class to selected tab
		}, rotateSpeed);
	}
	
	$(".tabs-nav a").click(function() {
		if ( ! $(this).hasClass("active") ) { // Don't do anything if user clicks on opened tab
			$(".tabs-content>div").hide();
			var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab
			$(activeTab).fadeIn(); // Fade in the active ID content
			$(".tabs-nav a").removeClass("active");
			$(this).addClass("active"); // Add "active" class to selected tab
		}
		return false;
	});
	
	startRotation();
	$(".tabs-nav, .tabs-content").hover(
		function() {
			clearInterval(rotation);
		}, function() {
			startRotation();
		}
	);
	
	
	/* DROPDOWNS
	--------------------------------------------------------------------------------------- */
	$('.dropdown strong').parent().addClass('drop-current');
	
	
	/* NOTIFICATION BAR
	--------------------------------------------------------------------------------------- */
	/*
	var infobar  = $("#infobar");
	var infobarClose = $("#infobar-close");
	infobar.hide();
	if ( infobar.length > 0 ) {
		infobar.hide().slideDown(1000);
		$("body").animate({paddingTop: 60}, 1500);
		infobarClose.bind("click", function(e){
			e.preventDefault();
			infobar.slideUp(1000, function(){
				$(this).remove();
			});
			$("body").animate({paddingTop: 0}, 1000);
		});
	}
	*/
	
	
	/* SEARCHBOX
	--------------------------------------------------------------------------------------- */
	var searchAll = $("form.search #all");
	var searchBoxes = $("form.search .extended input");
	searchBoxes.bind("click", function(){
		// When clicking on "All", deselect others
		if ( $(this).attr("id") == "all" && $(this).is(":checked") ) {
			searchBoxes.not("#all").attr("checked", false);
		}
		// When clicking on a section, deselect "All"
		if ( $(this).attr("id") != "all" && searchAll.is(":checked") ) {
			searchAll.attr("checked", false);
		}
	});
	
	
	/* CONTEST NOMINATIONS
	--------------------------------------------------------------------------------------- */
	$('ul.nom input[type=radio]').click(function(){
		var current = $(this).attr('value'); // get current value
		$(this).parents('ul.nom').find('input[value=' + current + ']').attr('checked', ''); // uncheck all buttons with that value
		$(this).attr('checked', 'checked');
	});
	
	
	/* MUSIC LISTS - TRANSITIONS
	--------------------------------------------------------------------------------------- */
	$('ul.catal li, ul.catal-tracks li').hover(
		function(){
			$(this).children('ul.item-prop').css({opacity: 0.0}).animate({ opacity: 1.0 }, 200);
		}, function() {
			// Don't animate mouseout for IE7
			if (! $.browser.msie || ($.browser.msie && $.browser.version > 8)) {
				$(this).children('ul.item-prop').css({visibility: 'visible'}).animate({opacity: 0}, 100);
			} else {
				$(this).children('ul.item-prop').animate({opacity: 0}, 100);
			}
		}
	);
	
	
	/* EMPTY INPUTS
	--------------------------------------------------------------------------------------- */
	var searchLabel = $('form.search input#keywords').val();
	$('form.search input#keywords').focus(function(){
		if ( $(this).val() == searchLabel ) {
			$(this).val('');
		}
	}).blur(function(){
		if ( $(this).val() == '' ) {
			$(this).val(searchLabel);
		}
	});
    
    $('form input[name="data[Member][username]"]').focus(function(){
        if ( $(this).val() == 'Автор' ) {
            $(this).val('');
        }
    }).blur(function(){
        if ( $(this).val() == '' ) {
            $(this).val('Автор');
        }
    });
    $('form input[name="data[Scout][username]"]').focus(function(){
        if ( $(this).val() == 'Рецензент' ) {
            $(this).val('');
        }
    }).blur(function(){
        if ( $(this).val() == '' ) {
            $(this).val('Рецензент');
        }
    });
    $('form input[name="data[Member][password]"]').focus(function(){
        if ( $(this).val() == '******' ) {
            $(this).val('');
        }
    }).blur(function(){
        if ( $(this).val() == '' ) {
            $(this).val('******');
        }
    });
    $('form input[name="data[Scout][password]"]').focus(function(){
        if ( $(this).val() == '******' ) {
            $(this).val('');
        }
    }).blur(function(){
        if ( $(this).val() == '' ) {
            $(this).val('******');
        }
    });
	
    
	// HEADER LOGIN FORM -> WORKAROUND TO NOT SHOW VALIDATION ERRORS
    $('form.login-head .error-message').hide();
	
	// NOMINATIONS FORM -> WORKAROUND TO NOT SHOW VALIDATION ERRORS
    $('ul.fill-rates .error-message').hide();
	
    
	/* TINY MCE
	--------------------------------------------------------------------------------------- */
    $('textarea.mce').each(function(){ 
        tinyMCE.init({
            mode : "specific_textareas",
            editor_selector : "mce",
            theme : "advanced",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            plugins : "paste",
            theme_advanced_buttons1: "bold, italic, underline, link, unlink, |, bullist, numlist, blockquote, |, outdent, indent, |, undo, redo,",
            theme_advanced_buttons2: "pastetext, pasteword, selectall",
            paste_auto_cleanup_on_paste : true,
			convert_urls : false
        });
    });
	
	
	/* HELP TOOLTIPS
	--------------------------------------------------------------------------------------- */
	$('form.form div').hover().children('p').css({ 'display' : 'none'});
	
	$('a.help').hover(
		function(){
			$(this).siblings('p.help').slideDown();
		}, 
		function(){
			$(this).siblings('p.help').slideUp();
		}	
	);
	
	/*
    $('button.accept-terms').mouseup(function(){
		window.location.href = 'signup_fill.html';
	});
    */
	
	
	/* CHARTS POSITIONS
	--------------------------------------------------------------------------------------- */
	$('table.chart-track td.pos').each(function(){
		var pos = $(this).html();
		var shift = $(this).siblings('td.shift').html();
		if (parseInt(pos) < parseInt(shift)) {
			$(this).siblings('td.shift').append(' <span class="sprite-misc up">&nbsp;</span>');
		}
		if (parseInt(pos) > parseInt(shift)) {
			$(this).siblings('td.shift').append(' <span class="sprite-misc down">&nbsp;</span>');
		}
		if (parseInt(pos) === parseInt(shift)) {
			$(this).siblings('td.shift').append(' <span class="idle">-</span>');
		}
	});
	
	$('table.part-hide td.genre, table.part-show td.genre').hover(function(){
		var genre = $(this).text();
		var gena = "Pop, Rock, Jazz, Easy Listening";
		var genb = "Electronica, Rap & Hip Hop, RnB & Soul";
		var genc = "Classical, Film Music/Soundtrack, New Age, World/Folk";
		if ( genre === "A" ) { $(this).attr('title', gena); }
		if ( genre === "B" ) { $(this).attr('title', genb); }
		if ( genre === "C" ) { $(this).attr('title', genc); }
	});
	
	/*
    $('ul.nom input').change(
		function(){
			$(this).siblings('span').css({'font-weight' : 'bold', 'color' : '#000'});
		}	
	);
    */
	
    
	/* PROFILE FUNCTIONALITY
	--------------------------------------------------------------------------------------- */
	$('div.show-second').slideUp(); // Hide all track info
	$('div.show-first').click(function(){ // Upon track title click
		if ( !$(this).hasClass('opened') ) { // If an already opened track is clicked
			$('div.show-first').removeClass('opened');
			$(this).addClass('opened'); // Tell that the clicked track is opened
			$('div.show-first').each(function() {
				if ( ! $(this).hasClass('opened') ) { // Don't hide info, if clicked on already opened track
					$(this).siblings('div.show-second').slideUp();
				}
			});
			$('.opened').siblings('div.show-second').slideDown(); // Show the clicked track info
		} else {
			$(this).removeClass('opened').siblings('div.show-second').slideUp();
		}
	});
	
	$('table.adm-tracks').slideUp('fast');
	
	// Admin stats
	$('a.toggle-stats, a.toggle-votes').click().toggle(
		function(){
			$(this).parent().next().slideDown();
			$(this).html('Скрий');
		},
		function(){
			$(this).parent().next().slideUp();
			$(this).html('Покажи');
		}
	);
	
    
    /* SCOUTS REGISTRATION TOGGLE
    --------------------------------------------------------------------------------------- */
    $('blockquote#scouts_diary').slideUp('fast');
    $('a.toggle-diary').click().toggle(
        function(){
            $(this).parent().next().slideDown();
            $(this).html('Скрий');
        },
        function(){
            $(this).parent().next().slideUp();
            $(this).html('Покажи');
        }
    );
	
	
    
	/* STYLING FILE INPUTS - http://www.quirksmode.org/dom/inputfile.html
	--------------------------------------------------------------------------------------- */
	var W3CDOM = (document.createElement && document.getElementsByTagName);
	function initFileUploads() {
		if (!W3CDOM) return;
		var fakeFileUpload = document.createElement('div');
		fakeFileUpload.className = 'fakefile';
		fakeFileUpload.appendChild(document.createElement('input'));
		var image = document.createElement('img');
		image.src='/app/webroot/images/fancy-file.gif';
		fakeFileUpload.appendChild(image);
		var x = document.getElementsByTagName('input');
		for (var i=0;i<x.length;i++) {
			if (x[i].type != 'file') continue;
			if (x[i].parentNode.className != 'fileinputs' && x[i].parentNode.className != 'fileinputs required' && x[i].parentNode.className != 'fileinputs required error') continue;
			x[i].className = 'file hidden';
			var clone = fakeFileUpload.cloneNode(true);
			x[i].parentNode.appendChild(clone);
			x[i].relatedElement = clone.getElementsByTagName('input')[0];
			x[i].onchange = x[i].onmouseout = function () {
				this.relatedElement.value = this.value;
			}
		}
	}
	
	initFileUploads();
	
	
	/* SCROLLING PLAYER, SEARCH
	--------------------------------------------------------------------------------------- */
	
	// All variables are global, to be used out of document.ready()
	topWrap = $("#top-wrap");
	headerFill = $("#header-fill");
	headerNewHeight = 0;
	playerMargin = 0;
	
	// Check if there is a message bar and increase margin
	var infobar = $(".infobar");
	if ( infobar.length > 0 ) {
		playerMargin = infobar.css("height"); 		// get the height of the message
		topWrap.animate({top: playerMargin});			// move the player down
		headerNewHeight = parseInt(playerMargin) + parseInt(headerFill.css("height"));
		headerFill.animate({height: headerNewHeight}); 	// move the website down
	}	
	
	$(window).scroll(function(){
		if ( $(this).scrollTop() > 10 ) {
			topWrap.addClass("scrolling-top");
			if ( $.browser.msie && $.browser.version <= 8) {
				$("#audio-player, form.search, form.search .extended").css({borderBottom: "1px solid #999"});
			}
		} else {
			topWrap.removeClass("scrolling-top");
			if ( $.browser.msie && $.browser.version <= 8) {
				$("#audio-player, form.search, form.search .extended").css({borderBottom: "none"});
			}
		}
	});
});

// Move everything up when closing the message bar
function closing_infobar() {
	var slideSpeed = 300;
	jQuery(".infobar.message").slideUp(slideSpeed);
	headerNewHeight = headerNewHeight - parseInt(playerMargin);
	headerFill.animate({height: headerNewHeight}, slideSpeed); // 400 = the duration the message bar slides up for
	topWrap.animate({top: 0}, slideSpeed);
	jQuery(this).remove();
}
