/******************************************************************************************************************/
// TABS HANDLE
/******************************************************************************************************************/

function handleTabs(){
	$('.tabs .tab').hide();

	$('.tabs .labels .sel').each(function(){
		initid = $(this).attr('href');
		$(initid).show();
	});

    // Carico all'inizio
    init_tab    = $('.tabs .labels a:first');
    mylink = init_tab.attr('href');
    myblock = init_tab.parents('.tabs');

    myblock.find('.tab').hide();
    myblock.find('.t-ajax').html('<div class="loading">loading...</div>').show();

    jQuery.ajax({
        url: mylink,
        success: function(html){
            myblock.find('.t-ajax').html(html);

            handleMeta();
        }
    });

    //caricamento dopo il clik
    $('.tabs .labels a').click(function(){
		// rimuove la class sel per il filter type e la riassegna ad all
        $('.box .filters .right a').removeClass('sel');
        $('.box .filters .right a:first').addClass('sel');
        
        $('.tabs .labels a').removeClass('sel');
		$(this).addClass('sel');
			
		if ($(this).hasClass('ajax')) {
			// load ajax tab
			mylink = $(this).attr('href');
			myblock = $(this).parents('.tabs');
			
			myblock.find('.tab').hide();
			myblock.find('.t-ajax').html('<div class="loading">loading...</div>').show();
								
			jQuery.ajax({
				url: mylink,
				success: function(html){			
					myblock.find('.t-ajax').html(html);						
					
					handleMeta();
				}
			});
		}
		else {
			// show tab new release per il filtro all
//			myid = $(this).attr('href');
//			$('.tabs .tab').hide();
//			$(myid).show();
//			handleMeta();
            // load ajax tab
			mylink = $(this).attr('href');
			myblock = $(this).parents('.tabs');

			myblock.find('.tab').hide();
			myblock.find('.t-ajax').html('<div class="loading">loading...</div>').show();

			jQuery.ajax({
				url: mylink,
				success: function(html){
					myblock.find('.t-ajax').html(html);

					handleMeta();
				}
			});
		}
		
		return false;
	});
}

function handleTabsFilterType(){
    $('.box .filters .right a').click(function(){
		var query;
        $('.tabs .labels .sel').each(function(){
            initid = $(this).attr('href');
            if( initid.match('most-popular') )
                query = '&order_item=most-popular';//most popular
            else
                query = '&order_item=new-releases';//new releases
        });

        $('.box .filters .right a').removeClass('sel');
		$(this).addClass('sel');

		if ($(this).hasClass('ajax')) {
			// load ajax tab
			mylink = $(this).attr('href');
			myblock = $(this).parents('.tabs');

			myblock.find('.tab').hide();
			myblock.find('.t-ajax').html('<div class="loading">loading...</div>').show();

			jQuery.ajax({
				url: mylink+query,
				success: function(html){
					myblock.find('.t-ajax').html(html);

					handleMeta();
				}
			});
		}
		else {
			// show static tab
			myid = $(this).attr('href');
			$('.tabs .tab').hide();
			$(myid).show();
			handleMeta();
		}

		return false;
	});

    //per la pagina dei profili
    $('.tabs .labels a').click(function(){
        mylink = $(this).attr('href');
        //profile
        if ($(this).hasClass('bee_profile')) {
//        console.log(mylink);
            $('.box .filters .right a').each(function(){
                initid = $(this).attr('href');
//            console.log(initid);
                if( initid.match('music-connections') )
                    newlink = mylink+'&type=music-connections';//music-connections
                else if( initid.match('movies-connections') )
                    newlink = mylink+'&type=movies-connections';//movies-connections
                else
                    newlink = mylink+'&type=all';//all
//            console.log(newlink);
                $(this).attr('href',newlink);
            });
        }
    });
}

/******************************************************************************************************************/
// SEARCH HANDLE
/******************************************************************************************************************/

function handleSearch(){
	$('.search .frm-text').attr('autocomplete','off');
	
	$('.search .frm-text').focus(function(){
		$(this).parents('.search').css({ backgroundPosition: '8px -17px' });
		$(this).css({ color: '#000000' });
		if ($(this).hasClass('link')) {
            if( this.value == 'Paste URL here...' )
                this.value = '';
            else
                this.value = this.value;//this.value = "Paste URL here...";
        }else{
            if( this.value == 'Search...' )
                this.value = '';
            else
                this.value = this.value;//this.value = "Paste URL here...";
        }
//        else this.value = "";

	});
	
	$('.search .frm-text').blur(function(){ 
		$(this).parents('.search').css({ backgroundPosition: '8px 8px' });
		$(this).css({ color: '#7f7f7f' });
		if (this.value == "") {
			if ($(this).hasClass('link')) this.value = this.value;//this.value = "Paste URL here...";
			else this.value = "Search...";
		}
	});
}

/********************************************/
// META INFO HANDLE
/********************************************/

function handleMeta(){
	$('.item').each(function(){ $(this).find('.meta').height($(this).height()); }); 
	
	// comments
	$('.comm').each(function(){ 
		m = $(this).parents('li').find('.meta');
		ch = $(this).height();
		mh = m.height(); 
		
		if (ch > mh) m.height(ch);
	}); 
	
	// votes
	$('.votes').each(function(){ $('#meta-box').find('.meta').height($(this).height()); });
}

function handleComm(){
	// open from url
	myquery = location.search;
	myshow = myquery.substr(6);
	
	if (myshow == 'comm') {			
		myanchor = location.hash;	
		myid = myanchor.substr(2);
				
		$('.vote a').removeClass('opened');
		$('.comment a').removeClass('opened');
		$(myanchor).find('.comment a').addClass('opened');	

		$(myanchor).after('<div id="meta-box"><div class="loading">loading...</div><!-- ajax comments here --></div>');
		$('#meta-box').show();

		mylink = '../wp-content/themes/filtersage/_inc/ajax/ajax-comments.php?id=' + myid;
		jQuery.ajax({
			url: mylink,
			success: function(html){
				$('#meta-box').html(html);
				
				handleMeta();
				
				$('#frm-comment .frm-text').attr('autocomplete','off');

				$('#frm-comment .frm-text').focus(function(){ 
					$(this).css({ color: '#000000' });
					this.value = "";
				});
				
				$('#frm-comment .frm-text').blur(function(){ 						
					$(this).css({ color: '#7f7f7f' });
					if (this.value == "") this.value = "Leave a comment here...";
				});
			}
		});
	}
	
	// on click
	$('#connections .comment a').click(function(){
		
		$('#meta-box').remove();
			
		if (!$(this).hasClass('opened')){
			$('.vote a').removeClass('opened');
			$('.comment a').removeClass('opened');
			$(this).addClass('opened');	

			$(this).parents('.item').after('<div id="meta-box"><div class="loading">loading...</div><!-- ajax comments here --></div>');
			$('#meta-box').show();
			
			myanchor = $(this).attr('href');
			myid = myanchor.substr(2);

            mylink = '../wp-content/themes/filtersage/_inc/ajax/ajax-comments.php?id=' + myid;
			jQuery.ajax({
				url: mylink,
				success: function(html){
					$('#meta-box').html(html);
					
					handleMeta();
					
					$('#frm-comment .frm-text').attr('autocomplete','off');
	
					$('#frm-comment .frm-text').focus(function(){ 
						$(this).css({ color: '#000000' });
						this.value = "";
					});
					
					$('#frm-comment .frm-text').blur(function(){ 						
						$(this).css({ color: '#7f7f7f' });
						if (this.value == "") this.value = "Leave a comment here...";
					});
				}
			});				
		}
		else {
			$(this).removeClass('opened');
			$('#meta-box').remove();
		}
		
		return false;
	});
}

function handleVotes(){
	// open from url
	myquery = location.search;
//    console.log(myquery);
	myshow = myquery.substr(6);
	
	if (myshow == 'vote') {			
		myanchor = location.hash;
//        console.log(myanchor);
		myid = myanchor.substr(2);

		$('.vote a').removeClass('opened');
		$('.comment a').removeClass('opened');
		
		$(myanchor).find('.vote a').addClass('opened');				

		$(myanchor).after('<div id="meta-box"><div class="loading">loading...</div><!-- ajax votes here --></div>');
		$('#meta-box').show();
		
		mylink = '../wp-content/themes/filtersage/_inc/ajax/ajax-votes.php?id=' + myid;
		jQuery.ajax({
			url: mylink,
			success: function(html){
				$('#meta-box').html(html);
				
				handleMeta();
			}
		});		
	}

	// on click
	$('#connections .vote a').click(function(){
		
		$('#meta-box').remove();
			
		if (!$(this).hasClass('opened')){
			$('.vote a').removeClass('opened');
			$('.comment a').removeClass('opened');
			
			$(this).parents('ul').find('.vote a').addClass('opened');				

			$(this).parents('.item').after('<div id="meta-box"><div class="loading">loading...</div><!-- ajax votes here --></div>');
			$('#meta-box').show();
			
			myanchor = $(this).attr('href');
			myid = myanchor.substr(2);
			
			mylink = '../wp-content/themes/filtersage/_inc/ajax/ajax-votes.php?id=' + myid;
			jQuery.ajax({
				url: mylink,
				success: function(html){
					$('#meta-box').html(html);
					
					handleMeta();
				}
			});				
		}
		else {
			$(this).parents('ul').find('.vote a').removeClass('opened');
			$('#meta-box').remove();
		}
		
		return false;
	});
 
}



/******************************************************************************************************************/
// CONNECT HANDLE
/******************************************************************************************************************/

function handlePreview(){
	// click from search results
	$('#frm-connect-results li').click(function(){
		$('#frm-connect-results, #connect-link').hide();
		$('#connect').after('<div id="connect-preview"><div class="loading">loading...</div><!-- ajax preview here --></div>');
		
		myid = $(this).attr('id');
		mylink = '../wp-content/themes/filtersage/_inc/ajax/ajax-preview.php?id=' + myid;
		
		jQuery.ajax({
			url: mylink,
			success: function(html){
				$('#connect-preview').html(html);			
				
				handleMeta();
				
				// types
				$('#type').fadeIn(300);
				
				$('#type .symbol').click(function(){
					$('#type .symbol').removeClass('sel');
					
					myclass = $(this).attr('class');
					mytext = $(this).text();
					
					$(this).addClass('sel');										
					
					$('#connect-preview .thumb .symbol').attr('class', myclass);	
					$('#connect-preview .thumb .symbol').text(mytext);
					$('#ctype').attr('value', myclass.substr(7));
					$('#btn-publish').removeAttr('disabled');

					$('#type').hide();
				});
				
				$('#connect-preview .thumb .symbol').click(function(){ $('#type').fadeIn(300); });
				
				// comment
				$('#connect-preview .frm-text').attr('autocomplete','off');
	
				$('#connect-preview .frm-text').focus(function(){ 
					$(this).css({ color: '#000000' });
					this.value = "";
				});
				
				$('#connect-preview .frm-text').blur(function(){ 						
					$(this).css({ color: '#7f7f7f' });
					if (this.value == "") this.value = "Leave a comment here...";
				});

				// back to results
				$('#connect-preview .back').click(function(){
					$('#connect-preview').remove();
					$('#frm-connect-results, #connect-link').show();
					
					return false;
				});
			}
		});		
	});
}

function handleConnect(){
	onconnect = false;
	
	// open search
	$('#connect .btn').click(function(){
        if( $(this).attr('href').match('#') ){
            $('#frm-connect-search').show();
            $(this).hide();

            onconnect = true;

            return false;
        }
	});
	
	// close search
	$('#frm-connect-search .btn-close').click(function(){
		$('#connect .btn').show();
		$('#frm-connect-search').hide();
		$('#frm-connect-results, #connect-preview').remove();
//        $('.search .frm-text').val('Paste URL here...');

		onconnect = false;
		
		return false;
	});
	
	// results
	$('#frm-connect-search').submit(function(){
		$('#frm-connect-results, #connect-preview').remove();
		$('#connect-link, #connect-link .msg, #connect-link .btn').show();
		
		$('#connect').after('<div id="frm-connect-results"><div class="loading">loading...</div><!-- ajax results here --></div>');
		
		mylink  = $(this).attr('action');
		key     = $('#search_connection_key').val();
		genre   = $('#search_connection_genre').val();
		post_not_in   = $('#search_connection_post_not_in').val();

		jQuery.ajax({
			url: mylink,
            type: "POST",
            data: "key="+key+"&genre="+genre+"&post_not_in="+post_not_in,
			success: function(html){
				$('#frm-connect-results').html(html);			
				
				// items click
				handlePreview();			
			}
		});			
		
		return false;
	});
}

function handleConnectURL(){
	onlink = false;
	
	// open input box
	$('#connect-link .btn').click(function(){
		$('#frm-connect-results').remove();
		$('#connect, #connect-link .msg').hide();
		$('#frm-connect-link').show();
		$(this).hide();
		
		onlink = true;
		
		return false;
	});
	
	// close input box
	$('#frm-connect-link .btn-close').click(function(){		
		$('#connect, #connect .btn').show();
		$('#connect-link, #frm-connect-search, #frm-connect-link').hide();
		$('#connect-preview').remove();
//        $('.search .frm-text').val('Paste URL here...');
		
		onlink = false;
		
		return false;
	});
	
	// parse url
	$('#frm-connect-link').submit(function(){
	
		$('#connect-preview').remove();
		
		$('#connect-link').after('<div id="connect-preview"><div class="loading">loading...</div><!-- ajax preview here --></div>');
		
		var mylink  = $(this).attr('action');
//        var url     = $('#url').val();
//        var id      = $('#id_right').val();
//		var genre   = $('#add_item_connection_genre').val();
		
		jQuery.ajax({
			url: mylink,
            type: "POST",
//            data: "url="+url+"&genre="+genre+"&id="+id,
            data: ({url : $('#url').val(), genre : $('#add_item_connection_genre').val(), id : $('#id_right').val()}),
			success: function(html){
				$('#connect-preview').html(html);			
				
				handleMeta();
				
				// types
				$('#type').fadeIn(300);
				
				$('#type .symbol').click(function(){
					$('#type .symbol').removeClass('sel');
					
					myclass = $(this).attr('class');
					mytext = $(this).text();
					
					$(this).addClass('sel');										
					
					$('#connect-preview .thumb .symbol').attr('class', myclass);	
					$('#connect-preview .thumb .symbol').text(mytext);
					$('#ctype').attr('value', myclass.substr(7));
				
					$('#type').hide();
				});
				
				$('#connect-preview .thumb .symbol').click(function(){ $('#type').fadeIn(300); });
				
				// comment
				$('#connect-preview .frm-text').attr('autocomplete','off');
	
				$('#connect-preview .frm-text').focus(function(){ 
					$(this).css({ color: '#000000' });
					this.value = "";
				});
				
				$('#connect-preview .frm-text').blur(function(){
					$(this).css({ color: '#7f7f7f' });
					if (this.value == "") this.value = "Leave a comment here...";
				});				
			}
		});	
		
		return false;
	});
}

/******************************************************************************************************************/
// CREATE HANDLE
/******************************************************************************************************************/

function handleCreate(){
	// fancybox
	$('#new .btn').fancybox({
		'type': 'iframe',
		'overlayOpacity': 0.6,
		'overlayColor': '#000',
		'width': 550,
		'height': 450		
	});
	
	$('.what').fancybox({
		'type': 'iframe',
		'overlayOpacity': 0.6,
		'overlayColor': '#000',
		'width': 800,
		'height': 550		
	});
	
	// parse url
	$('#frm-create-link').submit(function(){
	
		$('#connect-preview').remove();
		
		$(this).after('<div id="connect-preview"><div class="loading">loading...</div><!-- ajax preview here --></div>');
		
		mylink  = $(this).attr('action');
//		url     = $('#new_item_url').val();
        
		jQuery.ajax({
			url: mylink,
            type: "POST",
//            data: "url="+url,
            data: ({url : $('#new_item_url').val()}),
			success: function(html){
				$('#connect-preview').html(html);	
				
				$('#frm-publish').submit(function(){
					mylink = $(this).attr('action');

					parent.window.location = mylink;
					
					return false;
				});
			}
		});	
		
		return false;
	});
}

/******************************************************************************************************************/
// PROFILE HANDLE
/******************************************************************************************************************/

function handleProfile(){
	$('.showmore').live('click', function() {
		mylink = $(this).attr('href');
		
		$(this).before('<div class="loading">loading...</div>');
		
		jQuery.ajax({
			url: mylink,
			success: function(html){				
				$('.loading').remove();
				$('.showmore').before(html).remove();
			}
		});	
		
		return false;
	});
}

/******************************************************************************************************************/
// FX HANDLE
/******************************************************************************************************************/

function handleFx(){
	// cover glow
	$('#single .item .cover').prepend('<div class="glow"><!-- glow fx --></div>');
	
	// ajust genres width (puņ essere miglirata)
	$('.genres').each(function(){
		maxnum = 0;
		$(this).find('li').each(function(){
			mynum = parseInt($(this).find('small').text());
			if (mynum > maxnum) maxnum = mynum;
		});
		
		$(this).find('li').each(function(){
			mynum = parseInt($(this).find('small').text());
			w = Math.round((mynum * 165) / maxnum);
			if (w >= 55) $(this).find('a').width(w);
			else $(this).find('a').width(w+70);
		});
	});
	
	$('.genres li').hover(function(){
		tmpw = $(this).find('a').width();
		$(this).find('a').width(165);
		$(this).find('small').show();
	}, function(){
		$(this).find('a').width(tmpw);
		$(this).find('small').hide();
	});
}

/** ON DOCUMENT LOAD... **/

$(function(){
	// tabs
	handleTabs();
    handleTabsFilterType();
	
	// search
	handleSearch();
	
	// meta
	handleMeta();	
	
	// fx
	handleFx();
	
	// connect
	handleConnect();
	handleConnectURL();
	
	// create item
	handleCreate();
	
	// comments & votes
	handleComm();
    handleVotes();

	// profile
	handleProfile();
	
	// btn back
	$('.back').click(function(){ window.history.back(); return false; });

    // validate frm-signin form on keyup and submit
    $("#frm-signin").validate({
        rules: {
            username: {
                required: true,
                minlength: 3
            },
            password: {
                required: true,
                minlength: 6
            },
            confirm_password: {
                required: true,
                minlength: 6,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            username: {
                required: "Please enter a username",
                minlength: "Your username must consist of at least 3 characters"
            },
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 6 characters long"
            },
            confirm_password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 6 characters long",
                equalTo: "Please enter the same password as above"
            },
            email: "Please enter a valid email address"
        }
    });
    
    // validate frm-signin form on keyup and submit
    $("#frm-account").validate({
        rules: {
            user_pass: {
                required: true,
                minlength: 6
            }
        },
        messages: {
            user_pass: {
                required: "Please provide a password",
                minlength: "Your password must be at least 6 characters long"
            }
        }
    });
    
});
