///////////////////////////////////////////////////////////////////////////
// Some fixes
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

/////////////////////////////////////////////////////////////////////////
// Forms
$(document).ready(function(){
    $(".formInfoBox").mouseenter(function(){
        var strMessage = eval("msg" + $(this).attr("id"));

        if (strMessage) {
            var boxInfo = '<div id="boxInfo" class="formInfoBox">' + strMessage + '</div>';
            $(this).before(boxInfo);
        }
        
    });

    $(".formInfoBox").blur(function() {$("#boxInfo").remove()});
    $(".formInfoBox").mouseout(function() {$("#boxInfo").remove()});
});

/////////////////////////////////////////////////////////////////////////
// Change language
$(document).ready(function(){
    $("#linkLanguages").click(function(event){
        $("body").append(htmlBlankScreen);
        document.body.style.cursor = 'wait';

        // Load informations into the profile box
		$.post("/partials/changeLanguage", function(language) {
            openWindow(msgChangeLanguage, language, "changeLanguage", 250, true);
		});

		event.preventDefault();
    });
});

/////////////////////////////////////////////////////////////////////////
// jQuery functions
$(document).ready(function(){
	
	/////////////////////////////////////////////////////////////////////////
	// Show user profile's popup
	$(".showProfile-left, .showProfile-right, .showProfile").click(function(event) {
		var href = $(this).attr("href");
		var username = href.substr(href.lastIndexOf("/") + 1, href.length);
        $("body").append(htmlBlankScreen);
        document.body.style.cursor = 'wait';

		// Load informations into the profile box
		$.post("/partials/showProfileBox", { username: username }, function(profileBox) {
            openWindow(msgShowProfile + " " + username, profileBox, "showProfile", 450, true);
		});
		
		event.preventDefault();
	});
	
	$("#feedbackTabAction").click(function(event) {
        $("body").append(htmlBlankScreen);
        document.body.style.cursor = 'wait';

		// Load informations into the profile box
        $.get("/partials/feedbackForm", function(wndFeedback) {
            openWindow(msgSendUsFeedback, wndFeedback, "feedbackForm", 400, true);

            // Print a "send feedback" option on the page
            $("#sendFeedback").ready(function() {
                $(this).submit(function(e){

                    if($(this).attr('id') != 'undefined')
                    {
                        var message = $("#feedbackMessage").val();

                        if(message.length < 5)
                        {
                            alert(msgEnterLeast5Chars);
                        }
                        else
                        {
                            $.post("/feedbacks/SendFeedback", { message: message, page: window.location.href });
                            alert(msgFeedbackReveived);
                            closeWindow("feedbackForm");
                        }
                    }

                    e.preventDefault();
                });
            });
        });

		event.preventDefault();
	});

	/////////////////////////////////////////////////////////////////////////
	// Add play button to video thumbs
	$(".video_thumb").each(function() {
		var image_name = $(this).attr('src');
		image_name = image_name.substring(image_name.lastIndexOf("/") + 1, image_name.lastIndexOf("."));
		
		var current_thumb = $(this);

		$.get("/video/thumbPlayOptions/slug/" + image_name, function(thumbPlayOptions) {
			current_thumb.after(thumbPlayOptions);
			
			$('#tp_' + image_name).click(function(){
				$.get("/video/videoPlayer/slug/" + image_name, function(videoPlayer) {
					current_thumb.replaceWith(videoPlayer);
				}, 'videoPlayer');
				$(this).remove();
			});
		}, 'thumbPlayOptions');
		
	});
	
	/////////////////////////////////////////////////////////////////////////
	// Vote for a specific page
	$(".star-rating li a").each(function() {
		$(this).click(function(event) {
			var url = $(this).parent().parent().attr('url');
			var rating = $(this).attr('value');
			var ratingClass = null;
			var item = $(this);

			$(".current-rating").css("width", rating * 30 + "px");

			$.post("/partials/rate", { value: rating, slug: url }, function(rate) {
				var message = null;
				
				switch(rate) {
					case 'success': item.parent().parent().toggleClass('global-' + ratingClass); break;
					case 'exist': alert(msgVoteExist); break;
					case 'notConnected': msgNotConnected(); break;
					default: alert(msgError);
				}
			});
				
			event.preventDefault();
		});
	});
	
	/////////////////////////////////////////////////////////////////////////
	// Add a page to favourites
	$(".link_add_favourite, .link_remove_favourite").each(function() {
		$(this).click(function(event) {
			var url = $(this).attr('url');
			var item = $(this);
			
			$.post("/partials/toggleFavourite", { slug: url }, function(favourite) {
				switch(favourite) {
					case '0': item.toggleClass('link_remove_favourite'); item.html(lblFavouriteAdd); break;
					case '1': item.toggleClass('link_add_favourite'); item.html(lblFavouriteRemove); break;
					case 'notConnected': msgNotConnected(); break;
					default: alert(msgError);
				}
			});
			
			event.preventDefault();
		});
	});
	
	/////////////////////////////////////////////////////////////////////////
	// Report spamming
	$(".report_spam").each(function() {
		$(this).click(function(event) {
			var toUser = $(this).attr('user');
			var type = $(this).attr('type');
			var value = $(this).attr('value');
			var item = $(this);
			
			$.post("/partials/spamReports", { to: toUser, type: type, value: value, url: window.location.href }, function(spam) {
				switch(spam) {
					case 'success': item.removeClass('report_spam'); item.html('<s>' + lblReportSpamMarked + '</s>'); break;
					case 'exist': alert(msgReportSpamExist); item.html('<s>' + lblReportSpamMarked + '</s>'); break;
					case 'notConnected': msgNotConnected(); break;
					default: alert(msgError);
				}
			});
			
			event.preventDefault();
		});
	});
	
	/////////////////////////////////////////////////////////////////////////
	// Rate comment
	$(".rate-comment-good, .rate-comment-bad").each(function() {
		$(this).click(function() {
			var id = $(this).attr("id");
			var table = $(this).attr("table");
            var rating;
            var type;

			if($(this).hasClass("rate-comment-good")){rating = "1"; type = "good";}
			if($(this).hasClass("rate-comment-bad")){rating = "0"; type = "bad";}

			$.post("/partials/rateComment", { id: id, rating: rating, table: table }, function(rate) {
				switch(rate) {
                   
					case 'success': 
						var objRate = $("#rate-" + type + "-" + table + "-" + id);
						var number = parseInt(objRate.html()) + 1;
						objRate.html(number);
						alert(msgRateCommentSuccess); 
						break;
                    case 'notHimself': alert(msgCannotRateHimself); break;
					case 'exist': alert(msgRateCommentExist); break;
					case 'notConnected': msgNotConnected(); break;
					default: alert(msgError);
				}
			});
		});
	});

    /////////////////////////////////////////////////////////////////////////
	// Forum send message
    $("#forum-send-button").click(function(event) {
        var comment = $("#forums_messages_content").val();
        if(comment.length < 5) {alert(msgCommentMoreLong); event.preventDefault(); return;}

        var fileId = $("#user-forum > :file").attr("id");
        var threadId = $("#forums_messages_thread_id").val();

        $("#forumNewPost").append('<input type="text" name="forums_messages[thread_id]" id="post_thread_id" value="' + threadId + '" />');
        $("#post_thread_id").css("display", "none");

        if(!isUploaded && isUploadTouch)
        {
            uploadFile(fileId);
            setTimeout(function(){sendForumMessageIfUploadFinished("forumNewPost", fileId)}, 500);
            event.preventDefault();
        }
        else
        {
            $(".btnAddFile").remove();
            $("#" + fileId).remove();
            $("#forumNewPost").submit();
        }
    });

    function sendForumMessageIfUploadFinished(strForumId, strFileId)
    {
        if(isUploaded)
        {
            $("#" + strFileId).remove();
            $(".btnAddFile").remove();
            $("#" + strForumId).submit();
        }
        else
        {
            setTimeout(function(){sendForumMessageIfUploadFinished(strForumId, strFileId)}, 500);
        }
    }
	
	/////////////////////////////////////////////////////////////////////////
	// Rate comment
	$("#comment-send-button").click(function(event) {

        var comment = $("#comments_comment").val();
        if(comment.length < 5) {alert(msgCommentMoreLong); event.preventDefault(); return;}

		$.post("/partials/sendComment", { comment: comment, url: currentPageShort}, function(comment) {
			switch(comment) {
				case 'success': $("#user-comment").text($("#comments_comment").val()); alert(msgSendCommentSuccess); break;
				case 'pleaseWait': alert(msgPleaseWait); break;
				case 'notConnected': msgNotConnected(); break;
				default: alert(msgError);
			}
		});
		event.preventDefault();
	});
	
	/////////////////////////////////////////////////////////////////////////
	// Show login box
	$("#linkSignIn").click(function(event) {
        $("body").append(htmlBlankScreen);
        document.body.style.cursor = 'wait';

        $.get("/partials/showLoginBox" , function(boxLoginForm) {
            openWindow(msgMemberLogin, boxLoginForm, "loginForm", 250, true);
        });

		event.preventDefault();
	});

	/////////////////////////////////////////////////////////////////////////
	// Resize the iframes
	$('#content > iframe').each(function() {
		this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
		this.style.width = '100%';
	});

    /////////////////////////////////////////////////////////////////////////
	// TABS - Get artists
    $('.glossary ul li').click(function(event) {

        $('.glossary ul li').each(function(){
            $(this).removeClass("selected");
        });

        $(this).addClass("selected");
        $("#tabsBandResults").html(htmAjaxLittleLoading);

        var strLetter = $(this).text();
       $.get("/tabs/ajaxGlossary/letter/" + strLetter , function(results) {
			$("#tabsBandResults").html(results);
		});

        event.preventDefault();
    });
});

function tabsGetSongs(strId)
{
    var strUrl = $("#" + strId + " a").attr("href");
    strUrl = strUrl.replace("/glossary/", "/ajaxArtist/");

    $('#tabsBand #tabsSongResults ul li').each(function(){
        $(this).removeClass("selected");
    });

    $("#" + strId).addClass("selected");
    $("#tabsSongResults").html(htmAjaxLittleLoading);

    $.get(strUrl, function(results) {
			$("#tabsSongResults").html(results);
	});
}

function tabsGetDetails(strId)
{
    
    var strUrl = $("#" + strId + " a").attr("href");
    strUrl = strUrl.replace("/glossary/", "/ajaxSong/");

    $('#tabsDetailResults ul li').each(function(){
        $(this).removeClass("selected");
    });

    $("#" + strId).addClass("selected");
    $("#tabsDetailResults").html(htmAjaxLittleLoading);

    $.get(strUrl, function(results) {
			$("#tabsDetailResults").html(results);
	});
}

/////////////////////////////////////////////////////////////////////////
// Image preloading
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}