$("document").ready(function() {
    
    
    site = $("#domain").val();
    icon = site+"/assets/icons";
    settings_shout_info = $("#setShoutInfo").val();
    current_page = $("#page").val();
    imageError = "<img src='"+site+"/assets/images/icons/error.png' alt='' />";
        
    $("#submit_search").click(function() {
        $("#search_form").submit();
    });
    
    
    $("#middleBox").draggable({
    containment: "body",
    handle: "div.sideboxhead"
    });
    
    $("#middleClose").mouseup(function() {
	dialog("hide");
    });
    
    
    $("#submit_search2").click(function() {
        $("#search_form2").submit();
    });
    
    
    // Load new shout
    $("a.newShout,a.fetchShout").mouseup(function() {
		var shoutID = $(this).attr("rel");
	fetchShout(shoutID);
	
    });
    
    $("#loadOlderMessages").mouseup(function() {
	getMessages("old");
    })
    
    $("img.nextShout").mouseup(function() {
	fetchShout();
    });
    
    
    $("#panel_reset").click(function() {
	
	if ($(this).val() == "Reset") {
	
	    var confirmFirst = confirm("Are you sure you want to reset panels to their default settings?");
	
	    if (confirmFirst == true) {
		panelReset();
	    }
	    
	} else {
	    // use the button as a refresh button
	    window.location = document.location;
	}
    });
    

    $("#header_shout").hover(function() {
	if (settings_shout_info != 1) $("#shout_rating").show();
    }, function() {
	if (settings_shout_info != 1) $("#shout_rating").hide();
    });
    
    
    // Panels
    $("#panel_add2").sortable({
        items: "div.panel_toggle",
        container: "#panel_add2",
        opacity: 0.8,
        axis: "y"
    });
    
    $("#panel_save").click(function() {
	panelOrder();
    });
    

    if ($('#chat_disabled:visible').length == 0 && $("div#panel_chat_content:visible").length == 1) {
        getMessages("new"); 
        getChatMessages = setInterval("getMessages()", 15000);
    }
    
    $("#chatEnable").mouseup(function() {
	
	enableChat();

    });
    
    $("#chatOff").mouseup(function() {
	disableChat();
	
	$.ajax({
	    type: "GET",
	    url: site+"/assets/functions/ajax.php?function=chatStatus&status=0",
	    cache: false
	});
	
    });
    
    
    //Disabled feature, hide left panels
    /*$("#container-left").animate({width: ['toggle', 'swing']}, 1000);
    $("#container-right").animate({"width": "97%"}, 1000);*/
    

});

function dialog(command, title, middle, width) {
    
    if (command == "hide") {
	
	$("#middleTitle").html("");
	$("#middleContent").html("");
	$("#middleDialog").removeClass("shown").fadeOut("fast");
	return false;
    
    } else if (command == "show") {
	
	$("#middleDialog").addClass("shown").fadeIn("normal", function() {
	    
	    $("#middleTitle").html(title);
	    $("#middleContent").html(middle);
	    $("#middleBox").animate({"width": width}, 500);
	    
	});
	return false;
    
    } else if (command != undefined) {
	
	$("#middleDialog").addClass("shown").fadeIn("normal");
	return false;
    
    } else {
	
	return false;
    
    }
    
}


function reportContentBox(type,id) {
    $('#reportContentBox').dialog('open');
    
    var data = "<p>Why are you reporting this "+type+"?</p>"+
    "<p><textarea id='reportReason' cols='40' rows='5' style='width: 90%; height: 80px'></textarea></p>"+
    "<p><input id='reportButton' type='button' onclick=\"reportContent('"+type+"','"+id+"')\" class='fancy' value='Report' /> <input type='button' class='fancy' onclick=\"dialog('hide')\" value='Cancel' /></p>";
    
    dialog("show", "<img src='"+site+"/assets/images/icons/flag.png' alt='' width='16' height='16' /> Report "+ucfirst(type), data, "300px");
    window.location='#top';
}

// Report Content
function reportContent(type, id) {

    var reportReason = escape($("#reportReason").val());
    reportReason = reportReason.replace(/\+/g,"%2B"); // Parse + to %2B
    
    $.ajax({
        type: "GET",
        url: site+"/assets/functions/ajax.php?function=reportContent&type="+type+"&id="+id+"&reason="+reportReason,
        cache: false,
	beforeSend: function() {
	    $("#reportButton").attr({"disabled": true}).val("Reporting...");
	},
        success: function(output) {
            if (output.substr(0,5) != "ERROR") {
                
                $("#reportArticleStatus").text("Reported");
                
                if (type == "comment") {
		    window.location = "#"+id;
                    $("#c"+id+"_buried").find("span.buried_report").html("<strong>This comment has been reported!</strong>");
                }
                
                if (type == "article") {
                    $("#reportArticleStatus").text("Reported");
                }
		
		if (type == "shout") {
		    fetchShout();
		}
		
		dialog("hide");
                
            } else {
                alert(output);
            }
        }
    });
}



function closeNews() {
    
    $.ajax({
        type: "POST",
        url: "./assets/functions/ajax.php?function=closeNews",
        data: "code=create",
        cache: false,
        beforeSend: function() {
            $("#latest_news_close").html("<img src='./assets/images/icons/loader.gif' alt='' />");
        },
        success: function(output) {
            if (output.substr(0,5) != "ERROR") {
                $("#news_ticker").slideUp("normal");
            } else {
                alert(output);
            }
            
        }
    });
    
}


function disableChat() {
    clearInterval(getChatMessages);
    $("#chatInput").hide();
    $("#chatDisabled").show();
    $("#panel_chat_content").slideUp("normal");
}


function enableChat() {
    getChatMessages = setInterval("getMessages()", 15000);
    $("#panel_chat_content").slideDown("normal");
    $("#chatInput").show();
    $("#chatDisabled").hide();
    getMessages();

    $.ajax({
        type: "GET",
        url: site+"/assets/functions/ajax.php?function=updateActivity&loginChat=1",
        cache: false
    });
}

function panelReset() {
    
    
    
    $.ajax({
        type: "GET",
        url: site+"/assets/functions/ajax.php?function=panelReset",
        cache: false,
        beforeSend: function() {
            $("input.panel_checkbox").attr({disabled: true});
        },
        success: function(output) {
            if (output.substr(0,5) != "ERROR") {
		
                $("#panel_reset").attr({value: "Refresh page!"});
		$("#panel_save").hide();
		$("#panel_toggle_container").slideUp("normal",function() {
		    $("#panel_reset_complete").slideDown("normal",function() {
			$("#panel_reset_complete").effect("highlight", {}, 5000)
		    });
		});
                
            } else {
                alert(output);
            }
        }
    });
}

function shout_thumbs(option,id) {

    $.ajax({
        type: "POST",
        url: site+"/assets/functions/ajax.php?function=thumb",
        data: "contenttype=shouts&commentid="+id+"&thumb="+option,
        cache: false,
        beforeSend: function() {
            $("#shout_"+id+"_thumb_up").html("<img src='"+site+"/assets/images/icons/loader.gif' alt='' />");
            $("#shout_"+id+"_thumb_down").empty();
        },
        success: function(output) {
            if (output.substr(0,5) != "ERROR") {
		fetchShout();
            } else {
                alert(output);
            }
        }
    });
}

function fetchShout(id) {

    if (id == undefined) {
	id = "";
    }

    $.ajax({
        type: "GET",
        url: site+"/assets/functions/ajax_noauth.php?function=fetchShout&id="+id,
        cache: false,
        beforeSend: function() {
            $("#header_shout").html("<img src='"+site+"/assets/images/icons/loader.gif' alt='' />");
        },
        success: function(output) {
            if (output.substr(0,5) != "ERROR") {
		
                $("#header_shout").html(output);
		
		if (id != "") {
		    $("#header_shout").effect("highlight", {}, 10000);
		}
                
            } else {
                alert(output);
            }
        }
    });
}


function sendChatMessage() {

    var message = escape($("input#send_message").val());

    $.ajax({
        type: "POST",
        url: site+"/assets/functions/ajax.php?function=sendMessage",
        data: "message="+message,
        cache: false,
        beforeSend: function() {
            $("#send_button").attr({disabled: true});
        },
        success: function(output) {
            if (output.substr(0,5) != "ERROR") {
                $("#send_message").attr({disabled: false}).val("").focus();
                $("#send_button").attr({disabled: false, value: "Send"});
            
                getMessages(output);
            } else {
                alert(output);
            }
        }
    });

}

function getMessages(single) {

    if (single == "old") {
	
	var last = "old"
	single = "";
	
	$("#moreChatLoading").show();
	$("#olderMessages").attr({src: site+"/assets/images/icons/replies_open.png"});

	// Get total amount of chats current on page
	//var total = $("div.chat_box:visible").length;
	
    } else if (single == "new") {
	var last = "new";
	single = "";
	var new_message = "";
    } else if (single != undefined) {
        var last = "message_0";
        var new_message = "new_message";
    } else {
        var last = $("div.chat_box:first").attr("id").split("message_")[1];
        single = "";
        var new_message = "";
    }
    
    $.getJSON(
	site+"/assets/functions/ajax.php?token="+Math.floor(Math.random()*99999)+"&function=getMessages&last="+last+"&single="+single+"&page="+current_page,
	function(data){
            var messages = "";
	    $.each(data.userdata, function(i,user){
		
		if(user.id == "TIMEOUT") {
		    disableChat();
		    
		    return false;
		}
		
		if (user.me == 1) {
		    var me1 = "<em>*";
		    var me2 = "</em>";
		} else {
		    var me1 = "";
		    var me2 = "";
		}
		
		messages = messages+
                    "<div id='message_"+user.id+"' lang='"+user.id+"' class='chat_box "+new_message+"' style='color: #"+user.timeColor+"'>";
                    if (current_page == "chat") {
                        messages = messages+"["+user.timestamp+"] ";
                    }
                messages = messages+me1+"<a href='"+site+"/user/"+user.author+"' class='chat_author' title='"+user.timestamp+"'>"+user.author+"&nbsp;</a> "+user.message+me2+""
                    +"</div>";

	    });
            
	    if (last != "old") {
		$("#messages_box").prepend(messages);
		if (current_page != "chat") {
		    $("div.chat_box:visible:gt(9)").hide("fast");
		}
	    } else {
		$("#old_messages_box").append(messages);
		$("#loadOlderMessages").remove();
		$("#moreChatLoading").hide();
	    }
	    $("div.chat_box:odd").addClass("chat_box_odd");
	    $("div.chat_box:even").removeClass("chat_box_odd");
            $("div.new_message:visible").effect("highlight",{},3000).removeClass("new_message");
	}
	
    );
}






function logEffect(option) {
    $("#login_form").hide();
    $("#logging").html("<p style='margin: 10px'>Logging "+option+"...</p>");
}


function toggleDivs(div1,div2,speed) {
    $(div1).slideUp(speed,function() {
        $(div2).slideDown(speed); 
    });
}


function panelOrder(order) {
    
    var panels = "";
    
    $("div.panel_toggle").each(function(output) {
        var panel_name = $(this).attr("id").split("toggle_panel_")[1];
        var panel_enabled = ($("#panel_"+panel_name+"_enable").prop("checked") == true) ? 1 : 0;
        
        if (panel_enabled == 1) {
            panels = panels+"&panel[]="+panel_name;
        }
        
    });
        
    $.ajax({
        type: "GET",
        url: site+"/assets/functions/ajax.php?function=panelOrder"+panels,
        cache: false,
	beforeSend: function() {
	  $("#panel_save:visible").val("Saving...");
	},
	success: function(output) {
	    $("#panel_save:visible").val("Saved!").effect("highlight", {}, 5000, function() {
                $("#panel_save:visible").attr({disabled: false}).val("Save");
            });
	}
    });

}


function increment(option,id,type) {
    
    if (type == "text") {
        var current = $(id).text();
        if (option == "+") {
            current++;
        } else {
            current--;
        }
        $(id).text(current);
    }
    
    if (type == "html") {
        var current = $(id).html();
        if (option == "+") {
            current++;
        } else {
            current--;
        }
        $(id).text(current);
    }
    
    if (type == "val") {
        var current = $(id).val();
        if (option == "+") {
            current++;
        } else {
            current--;
        }
        $(id).text(current);
    }
    
}

function ucfirst(string) {
    return string.substr(0,1).toUpperCase() + string.substr(1,string.length);
}


function textCounter(field, countfield, maxlimit) {
    var fieldvalue = $(field).val();
    var countvalue = $(countfield).val();
    
    if (fieldvalue.length > maxlimit) { // trim if too long
        $(field).val(fieldvalue.substring(0, maxlimit));
        var chars_left = 0;
    } else { 
        var chars_left = maxlimit - fieldvalue.length;
    }
    
    if (chars_left <= 20) {
        $(countfield).text(chars_left).addClass("red");
    } else {
        $(countfield).text(chars_left).removeClass("red");
    }
}
