$(document).ready(function(){

    // TODO - Meg kellene valahogy csinalni, hogy a zend form ne a label ala tegye a checkbox-ot
    $("form[id='login']").find("label[for='password']").livequery(function(){
        $dd = $(this).parent().next();
        $(this).after(' &nbsp; ' + $dd.html());
        $dd.html( $('<a href="/user/forgotten">forgotten password</a>').css("color","orange") );
    });

	/* compositionBox ORDER */
    $(".box.composition .nav>a").livequery("click",function(){
        
        $(".box.composition .nav").removeClass("active");
        $(this).parent().addClass("active");

        w_compositionBox_order = $(this).attr("rel");
        var url = '/compositionbox/categories/order/' + $(this).attr("rel");

        showLoader();
        $.get(url,false,function(result) {
            hideLoader();
            $(".box.composition .content > .categories").html(result);
        });
        compositionBox_updateItems(1);
        
    });

    /* compositionList ORDER */
    $(".box.sidebox .nav>a").livequery("click",function(){

        $(".box.sidebox .nav").removeClass("active");
        $(this).parent().addClass("active");
        
        w_composition_order = $(this).attr("rel");
        compositionList_updateItems(1);

    });
    /* compositionList OWNER */
    $(".box.sidebox .own>a").livequery("click",function(){

        $(".box.sidebox .own").removeClass("active");
        $(this).parent().addClass("active");
        
        if ( $(this).attr("rel") ) {
        	w_composition_userId = $(this).attr("rel");
        } else {
        	w_composition_userId = 0;
        }
        
        compositionList_updateItems(1);

    });

    /* compositionBox/compositionList category filter */
    $(".categories .category > a").livequery("click",function(){
        
        var compositionCategoryId = $(this).parent().attr("id");

        $(".category.active").removeClass("active");
        $("div[class='category'][id='" + compositionCategoryId + "']").addClass("active");

        if ( typeof( w_compositionBox_compositionCategoryId ) != 'undefined' ) {
            
            w_compositionBox_compositionCategoryId = compositionCategoryId;
            compositionBox_updateItems(1);

        } else if ( typeof(w_composition_compositionCategoryId) != 'undefined' ) {

            w_composition_compositionCategoryId = compositionCategoryId;
            compositionList_updateItems(1);

        }
        
    });

    /* compositionBox detailsFor */
    $(".box.composition .items").find("a[name='detailsFor']").livequery("click",function(){

        w_compositionBox_detailsFor($(this).attr("rel"));

    });


    /* compositionBox pagination */
    $(".box.composition .pagination a").livequery("click",function(){

        compositionBox_updateItems($(this).attr("rel"));

    });

	$('a, div, span, p').tooltip({
		 delay: 0,
		 track: true,
		 showURL: false,
		 showBody: "; "
	 });


    /* Shoutbox box */
    $("form[id='shout']").submit(function(){

        $form = $(this);
        
        showLoader();

        $.post('/shoutbox/add',$form.serialize(),function(result){

            hideLoader();

            if ( !result ) {

                getShoutList($form.parent().find(".shouts"));

                $form.find("input[name='s']").val('');
                $form.find("input[name='s']").removeClass("input_text_error");
                
            } else {
                $form.find("input[name='s']").addClass("input_text_error");
            }

        });

    });
    /* Shoutbox auto refresh */
    shoutboxAutoRefresh();

    /* fav */
    $("#fav").livequery("click",function(){

        var url = '/composition/fav/compositionId/' + $(this).attr("rel");

        showLoader();
        $.get(url,false,function(result) {
            hideLoader();
        	$("#fav").hide('slow');
        });

    });


    /* binderpoints hidden */
    $("div[class^='box'][id='binderpoints']").livequery(function(){

       $h1 = $(this).find("h1");

       if($h1.html().length > 4) {
           $(this).find("img").css({marginRight:'0',marginLeft:'0'});
           $h1.css('margin-left','0');
       }

    });
    /* my links */
    $("#my_favs").livequery("click",function(){
    	showLoader();
    	location.href = "/my/favs";
    });
    $("#my_comments").livequery("click",function(){
    	showLoader();
    	location.href = "/my/comments";
    });
    
    /* my close message */
    $(".close_msg").livequery("click",function(){
    	var messageId = $(this).attr("rel");
        var url = '/my/seen/messageId/' + $(this).attr("rel");
        showLoader();
        $.get(url,false,function(result) {
            hideLoader();
            $('#message_'+messageId).hide('slow');
        });

    });


    /* forgotten password */
    $("form[name='forgotten_password']").submit(function(){

        showLoader();

        $status = $("div.status");
        $status.html('Please wait...').css('color','white');

        $.ajax({
            type: "POST",
            url: '/user/forgotten',
            data: $(this).serialize(),
            dataType: 'json',
            cache: false,
            success: function(data){

                if ( data.error ) {

                    $status.html(data.error).css('color','red');

                } else {
                    $status.html(data.msg).css('color','green');
                }

                hideLoader();

            },
            error: function(result) {
                hideLoader();
                alert(result.responseText);
                $status.html('&nbsp;');
                alert('Database error!');
            }
        });

    });

    $("a[rel^='video_']").livequery("click",function(){

        var num = $(this).attr("rel").replace('video_','') - 1;
        $("ul.videos").find("li").hide();
        $("ul.videos").find("li").eq(num).show();
        $("ul.video_nav a[rel^='video_']").css( {fontWeight:"normal",color:"white"} );
        $("ul.video_nav a[rel='video_" + (num+1) + "']").css( {fontWeight:"bold",color:"orange"} );

    });

    /* INVITE users */
    $("form#adduser #invite_users").livequery("click",function(){
        $status = $('<div class="status">Please Wait...</div>');
        $(this).after($status);

        var data = $("input[type='checkbox'][name='invite_users[]']").serialize();
        
        $.post('/user/inviteUsers',data,function(result){
           try { eval('data = ' + result); } catch(err) { return alert(result); }

           if ( typeof(data.alreadyInvited) != 'undefined' ) {
               alert(data.alreadyInvited + 'ALREADY INVITED')
           }
           alert(data.msg);
           $status.remove();
           document.location.reload(true);
        });

    });

});


/* UPDATE ITEMS*/

function compositionBox_updateItems(page) {
    
    w_compositionBox_page = page;
    
    var url = '/compositionbox/items/page/' + page + '/compositionCategoryId/'
    + w_compositionBox_compositionCategoryId + '/order/'
    + w_compositionBox_order+'/userId/'+w_compositionBox_userId;
        
    showLoader();

    $.get(url,function(result){
        hideLoader();
        $("div[class='items']").html(result);
        w_compositionBox_detailsFor($(result).find("a[name='detailsFor']").eq(0).attr("rel"));
    });
    
}

function compositionList_getURL(page,type) {
	w_composition_page = page;

    var url = '/composition/'+type+'/page/' + page + '/compositionCategoryId/'
    + w_composition_compositionCategoryId + '/order/'
    + w_composition_order+'/userId/'+w_composition_userId
	+ '/browser/' + w_composition_browser;
	return url;
}

function compositionList_updateItems(page) {

    w_composition_page = page;

    var url = compositionList_getURL(page,'list');

    showLoader();

    $.get(url,false,function(result){
        hideLoader();
        $("div[class='items']").html(result);
    });

    document.getElementById('currentPage').innerHTML = 'Current page: '+page;
}

/* ------------------------------------- */

function w_compositionBox_detailsFor(compositionId) {
    
    var url = '/compositionbox/detail/compositionId/' + compositionId +'/userId/'+w_compositionBox_userId;

    showLoader();
    $.get(url,false,function(result) {
        hideLoader();
        $(".box.composition .compositionDetails").html(result);
        $('a, div, span, p').tooltip({
            delay: 0,
            track: true,
            showURL: false,
            showBody: "; ",
            fade: 250
        });
    });

}

var loaderTime;

function showLoader() {
    $("#ajaxLoad #oops").hide("slow");
    $("#ajaxLoad, #ajaxLoad #loading").show();

    loaderTime = setTimeout(function(){

                     showOops();

                 }, 1000*10);
}

function hideLoader() {
    $("#ajaxLoad,#ajaxLoad > div").hide();
    clearTimeout(loaderTime);

}

function showOops() {

    $("#ajaxLoad #oops").show();
    $("#ajaxLoad #loading").hide();
    setTimeout(function(){
        $("#ajaxLoad #oops").hide("slow");
    },30000);

}

function getShoutList($tag) {

    if ( typeof($tag) != 'object' ) {
        $tag = $("#shouts_list");
    }

    $.get('/shoutbox/shouts',false,function(shoutList){
        $tag.html(shoutList);
    });
}

function shoutboxAutoRefresh() {
    setTimeout("getShoutList(true);shoutboxAutoRefresh();",(60*1000));
}

function sbWindowOpen( compositionId ) {
        var win = window.open( '/binder/index/compositionId/'+compositionId, 'sourcebinder'+Math.random(),
                               'fullscreen=1,directories=0,location=0,menubar=0,resizeable=1,scrollbars=0,status=0,titlebar=0,toolbar=0' );
        win.focus();
}

/*
function showLoader() {
	$('ajaxLoad').style.display = 'block';
}
function hideLoader() {
	$('ajaxLoad').style.display = 'none';
}
function favComposition( compositionId, elem ) {
	var url = '/composition/fav/compositionId/' + compositionId;
	showLoader();
	new Ajax.Request(url, {
		method :'post',
		onComplete : function(transport) {
		hideLoader();
			$(elem).innerHTML = 'Fav\'d!';
		}
	});
} */