//  *** TRIGGERS
$(document).ready(function() {
	// Recents
	$(".sidebar-recents-nav ul li.remotelist").click(function() { updateRemoteList(this); return false; } );
	$(".sidebar-recents-t .recents-refresh").click(function() { refreshRemoteList(this); return false; } );

	// Goto forum inbox when clicking new message link
	$("#nav-ucp var").click(function() {window.location = "/forum/index.php?act=Msg&CODE=01"; return false;} );
		
	// Comments reply / quote
	$(".comment-reply").click(function() { c_reply(this); } );
	$("#submit-reply").click(function() { c_save(this); } );
	$(".comment-quote").click(function() { c_quote(this); } );
	
	// preview & submit form
	$("#news_preview_button").click(function() { news_preview(this); } );
	$("#news_submit_button").click(function() { news_submit(this); } );
	
	// Search
	$("#search").focus(function() { if (this.value == 'Search Neowin') this.value = ''; } );
	$("#search").blur(function() { if (this.value == '') this.value = 'Search Neowin'; } );
	$("#header-search-box").click(function() { $("#search").focus(); } );
	
	// Target _blank
	$('A[rel="external"]').click( function() { window.open( $(this).attr('href') ); return false; });
	
	// Announcement toggle
	$("#content-main-latest-toggle").click(function() { announcementToggle(); return false; } );
	
	// Width toggle
	$("#nav-toggle").click(function() { toggleWidthType(this); } );    
 	
 	// Profile business cards
 	$('.dropdown-profile').click(function(){showMiniProfile(this)});
 	
 	// Digg Box
	//getDiggStories();
});

//  *** FUNCTIONS

// Mini profiles

var dontloadprofile = false;

function showMiniProfile(elm) {
	if (!dontloadprofile) {
		closeMiniProfile();
		$(".dropdown-profile-clicked").each(function(i){
			$(this).removeClass();
			$(this).addClass('dropdown-profile');
			$(this).find('.dropdown-profile-content').remove();
			$(this).click(function(){showMiniProfile(this)});
		});
		
		$(elm).unbind();
		
		$(elm).removeClass('dropdown-profile');
		$(elm).addClass('dropdown-profile-clicked');
		$(elm).attr('href', '#');
		$(elm).attr('id', 'miniprofile-open');
		$(elm).append('<div class="dropdown-profile-content dropdown-profile-loading"></div>');
		$.ajax({type:"GET", url:'/index.php?act=ajax_get_miniprofile&username=' + $(elm).attr('rel'), cache:false, timeout:10000,
			success: function(content) {
				$(elm).find('.dropdown-profile-loading').removeClass('dropdown-profile-loading');
				$(elm).find('.dropdown-profile-content').html(content);
				$('body').click(function(){closeMiniProfile()});
				$('#miniprofile-open').click(function(event) {
				  event.stopPropagation();
				});
			}
		});
	}
}

function closeMiniProfile(elm) {
	$('#miniprofile-open').each(function(i){
		$(this).removeClass();
		$(this).addClass('dropdown-profile');
		$(this).find('.dropdown-profile-content').remove();
		dontloadprofile = true;
		setTimeout(function(){dontloadprofile = false;}, 100);
		$(this).unbind();
		$(this).click(function(){showMiniProfile(this)});
	});
	$('#miniprofile-open').attr('id','');
	$('body').unbind();
}

// Digg feed
function getDiggStories() {
	spinner = $('#sidebar-recents-news-content').parent().parent().find(".recents-refresh");
	spinner.addClass("loading");
	morelink = $('#sidebar-recents-news-content').parent().parent().find(".sidebar-recents-b-l");
	morelink.empty();
	
	$.ajax({type:"GET", url:'/index.php?act=ajax_digg_widget', cache:false, timeout:10000,
			success: function(content) {
				$('#sidebar-recents-news-content').html(content);
				spinner.removeClass("loading");
			},
			complete: function() {},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#sidebar-recents-news-content').html('<div style="padding-top:35px;text-align:center;">We are unable to get Digg stories at this time.</div>');
				spinner.removeClass("loading");
			}
		}); 
}

// Width toggle
function toggleWidthType(elm) {
  $(elm).toggleClass("active");
  $("#container").toggleClass("full");
  toggleCookieExistence("normalwidth");	
}

// Poll
function submitPoll(elm) {
	pollid = $(elm).attr("poll");
	pollchoice = $("input[@name='choice']:checked").val();
	target = $(elm).parent().parent();
    $(target).html("<div style=\"text-align:center;margin:20px;\"><img src=\"/themes/theme_images/neowin5/ajax_wait.gif\" /></div>");
	$.get(
    		"index.php?act=ajax_poll_vote",
    	{
        	choice: pollchoice,
        	id: pollid
    	},
    	function(content) {
        	$(target).html(content);
    	}
	);
}

// Announcements toggle
function announcementToggle() {
	$("#content-main-latest-toggle").toggleClass("show");
	$("#content-main-top-content").slideToggle(250);
	toggleCookieExistence("announcement");	
}

function announcementCheck() {
	if ($.cookie("announcement")=="false") { 
		$("#content-main-top-content").hide();
		$("#content-main-latest-toggle").addClass("show");
	}
}

// Cookies
function toggleCookieExistence(name) {
    if ($.cookie(name)=="false") { $.cookie(name, null) } else { $.cookie(name, "false", { expires: 30 } )}
}

// Recents
function updateRemoteList(elm) {
	section = $(elm).find("a").attr("rel");
    $(elm).parent().find("li.active").removeClass("active");
    $(elm).addClass("active");  
    spinner = $(elm).parent().parent().parent().find(".recents-refresh");
    morelink = $(elm).parent().parent().parent().parent().parent().parent().find(".sidebar-recents-b-l");
    spinner.addClass("loading");
    if (section == 'digg')
    {
    	getDiggStories(elm);
    }
    else
    {
		$.ajax({type:"GET", url:"index.php?act=ajax_recent_content&sect=" + section, cache:false, timeout:10000,
			success: function(xml) {
				containerList = $(elm).parent().parent().parent().parent().parent().parent().find(".sidebar-recents-content ul");
				$(containerList).empty();
				$(xml).find("error").each(function() {
					$(containerList).append("<li>" + $(this).text() + "</li>");
				});
				if (section == "poll" || section == "podcast") {
					$(containerList).append(xml);
					return;
				}
				$(xml).find("items item").each(function() {
					$(containerList).append("<li><a href=\""+$(this).find("href").text()+"\" title=\""+$(this).find("title").text()+"\">"+$(this).find("text").text()+"</a></li>");
				});
			},
			complete: function() { 
				if(section=="gamers" || section=="software") {
					morelink.html("<img src='/themes/theme_images/neowin5/comment_reply_link.png' alt=''> <span><a href='/index.php?cat=" + section +"'>View more like this</a></span>");
				} else if(section=="forum") {
					morelink.html("<img src='/themes/theme_images/neowin5/comment_reply_link.png' alt=''> <span><a href='/forum/index.php?act=Search&CODE=getnew'>View more like this</a></span>");
				} else if(section=="blog") {
					morelink.html("<img src='/themes/theme_images/neowin5/comment_reply_link.png' alt=''> <span><a href='/forum/index.php?automodule=blog'>View more like this</a></span>");
				} else if(section=="submissions") {
					morelink.html("<img src='/themes/theme_images/neowin5/comment_reply_link.png' alt=''> <span><a href='/index.php?pid=submissions'>View more like this</a></span>");
				} else if(section=="podcast") {
					morelink.html("<img src='/themes/theme_images/neowin5/comment_reply_link.png' alt=''> <span><a href='/index.php?subcat=podcast'>View more like this</a></span>");
				} else {
					morelink.empty();
				}
				spinner.removeClass("loading");
			}     
		}); 
	}
}

function refreshRemoteList(elm) {
    updateRemoteList($(elm).parent().find(".sidebar-recents-nav ul li.active"));
}


// News poll on comments page
function sndReq(vote,id_num) {
    $.get(
        '/index.php?act=ajax_news_vote',
        {
            rating: vote,
            id: id_num
        },
        function(content) {
            $("#content-story-rating").html(content);
        }
    );
}


// Comments
function c_reply(elm) {
	var itm = document.getElementById("comments-replyform");
	if (itm.style.display == "none") {
		$("#submit-reply").attr("cid", $(elm).attr('cid'));
		$("#submit-reply").attr("nid", $(elm).attr('nid'));
		$("#submit-reply").attr("pid", $(elm).attr('pid'));
		$("#submit-reply").attr("loc", $(elm).attr('cid'));
		$(elm).parent().append($("#comments-replyform"));
		$("#comments-replyform").slideDown('fast');
	} else {
		$("#comments-replyform").slideUp('fast');
		$("#postcontentreply").val('');
	}
}

function c_quote(elm) {
	var itm = document.getElementById("comments-replyform");
	var cid = $(elm).attr('cid');
	var pid = $(elm).attr('pid');
    $.get(
        '/index.php?act=ajax_comment_quote',
        {
            id: cid
        },
        function(comment_bbcode) {
        	var data=comment_bbcode.split('|')
			if (itm.style.display == "none") {
				var rows = parseInt(data[1]);
				rows = rows + 3;
				$("#submit-reply").attr("cid", $(elm).attr('cid'));
				$("#submit-reply").attr("pid", $(elm).attr('pid'));
				$("#submit-reply").attr("loc", $(elm).attr('pid'));
				$("#postcontentreply").val(data[0]);
				$("#postcontentreply").attr("rows",rows);
				$("#comment" + cid + " .comment-content:first").append($("#comments-replyform"));
				$("#comments-replyform").slideDown('fast');
			} else {
				$("#comments-replyform").slideUp('fast');
				$("#postcontentreply").val('');
			}
        }
    );
}

function c_edit(comment) {
	var original_html = $("#comment" + comment).html();
    $.get(
        '/index.php?act=ajax_comment',
        {
            id: comment
        },
        function(comment_html) {

            $("#comment" + comment + " .comment-content:first").html(comment_html);
			$('#saveButton').click(function(){saveChanges($("#comment" + comment),$("#postcontent").get(0).value,comment, false);});
			$('#cancelButton').click(function(){saveChanges($("#comment" + comment),'',comment, original_html);});
        }
    );
}

function c_delete(comment,newsid) {
	var comment_id = comment;
	var answer = confirm("Delete this comment?")
	if (answer){
	$("#comment" + comment).parent().remove();
    $.get(
        '/index.php?act=ajax_comment_delete',
        {
            id: comment,
            news_id: newsid
        },
        function() {
            $("#comment" + comment).parent().remove();
        }
    );
	}
} 

function c_save(elm) {
	var cid = $(elm).attr('cid');
	var nid = $(elm).attr('nid');
	var pid = $(elm).attr('pid');
	var loc = $(elm).attr('loc');
	var content = $("#postcontentreply").get(0).value;
	if (!content) {
		return false;
	}
	$.post("/index.php?act=ajax_comment_save",{
  		content: content,
  		id: cid,
  		nid: nid
	},
	function(comment_html){
		$("#comments-replyform").hide();
		$("#postcontentreply").val('');
		$("#comment-reply" + loc).before(comment_html);
	});

}

function saveChanges(obj,content, comment, cancel) {
	if(!cancel) {
		var t = content;
		$.post("/index.php?act=ajax_comment_save",{
	  		content: t,
	  		id: comment
		},
		function(comment_html){
			$(obj).html(comment_html);
		});
	} else {
		var t = cancel;
		$(obj).html(t);
	}
	$(".comment-buttons").show();
}


function report(newsid, commentid) {
	var reason=prompt("Enter your reason for reporting this comment");
	if(reason.length >0) {
		$.ajax({type: "POST",url: "/index.php",data: "act=c_report&newsid="+newsid+"&commentid="+commentid+"&reason="+escape(reason),success: function(msg){alert("Thank you for your report. It will be reviewed by a moderator.");}})
	}
}

function typo(newsid) {
	var problem=prompt("Paste the problematic block of text here (hit 'cancel' and copy it if you haven't already). After completing this step, you will be given the opportunity to say what the problem is.");
	var reason=prompt("What is wrong with this text?")
	if(reason.length >0) {
		$.ajax({type: "POST",url: "/index.php",data: "act=n_typo&newsid="+newsid+"&error="+escape(problem)+"&correction="+escape(reason),success: function(msg){alert(msg);}})
	}
}

function news_preview() {
	var content = $("#postcontent").get(0).value;
	var title = $("#posttitle").get(0).value;
	$.post("/index.php?act=ajax_news_preview",{
  		content: content
	},
	function(data){
	    var data=data.split('|')
		$("#news_preview").html(data[0]);
		$(".postername").html(data[1]);
		$(".preview-t-l h3").html("Preview: " + title);
		scroll(0,0);
	});
}

function news_submit() {
	var content = $("#postcontent").get(0).value;
	var title = $("#posttitle").get(0).value;
	var category = $("#category").get(0).value;
	var subcategory = $("#subcategory").get(0).value;
	if (!title) {
		$("#posttitle").css("background-color","#ffcccc");
		return false;
	}	
	if (!content) {
		$("#postcontent").css("background-color","#ffcccc");
		return false;
	}
	$.post("/index.php?act=ajax_news_submit",{
  		content: content,
  		title: title,
  		category: category,
  		subcategory: subcategory
	},
	function(){
		$("#posttitle").val('');
		$("#postcontent").val('');
		$(".alert-bar").show();
	});	
}

function tag_beta()
{
    var FoundErrors = '';
    var enterTITLE = prompt(text_enter_beta_name, "This is BETA software!, please use caution when installing it on your system");
    
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/warnicon.gif[/img]"+enterTITLE });
}

function tag_source()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_source, "http://");
    var enterTITLE = prompt(text_enter_source_name, "Source");

    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/souricon.gif[/img] News source: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}

function tag_view()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_view, "http://");
    var enterTITLE = prompt(text_enter_view_name, "View");
    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/viewicon.gif[/img] View: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}

function tag_music()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_music, "http://");
    var enterTITLE = prompt(text_enter_music_name, "Music");

    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/musiicon.gif[/img] Music: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}

function tag_link()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_link, "http://");
    var enterTITLE = prompt(text_enter_link_name, "Link");

    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/linkicon.gif[/img] Link: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}


function tag_download()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_download, "http://");
    var enterTITLE = prompt(text_enter_download_name, "Download");

    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/softicon.gif[/img] Download: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}

function tag_screen()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_screen, "http://");
    var enterTITLE = prompt(text_enter_screen_name, ">> Click here <<");

    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/picticon.gif[/img] Screenshot: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}

function tag_video()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_video, "http://");
    var enterTITLE = prompt(text_enter_video_name, ">> Click here <<");

    if (!enterURL)
    {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE)
    {
        FoundErrors += " " + error_no_title;
    }
    if (FoundErrors)
    {
        alert("Error!"+FoundErrors);
        return;
    }
    $.markItUp({ placeHolder:"[img]http://www.neowin.net/images/icons/vidicon.gif[/img] Video: [url="+enterURL+"]"+enterTITLE+"[/url]" });
}

function neoModalView(ajaxPage)
{
	if (ajaxPage == 'close')
	{
		tb_remove();
	}
	
	else
	{
		$.get(ajaxPage, {}, function(returnValue) 
		{
			neoModalViewWithContent(returnValue, 0);
		})
	}	
}

function neoModalViewWithContent(content, block)
{
	if (!block)
	{
		tb_remove();
	}
	
	$('#TB_ajaxContent').html(content);
}

function submitContactForm()
{
	var username = $("#username").val();
	var userid = $("#userid").val();
	var email = $("#email").val();
	var title = $("#title").val();
	var message = $("#message").val();
	
	if (!username) {
		$("#username").css("background-color","#ffcccc");
		return false;
	} else if (!email) {
		$("#email").css("background-color","#ffcccc");
		return false;
	} else if (!message) {
		$("#message").css("background-color","#ffcccc");
		return false;
	} else if (!title) {
		$("#title").css("background-color","#ffcccc");
		return false;
	}
	
	$.get("/index.php?act=ajax_contact_send",
		{
			username: username,
			userid: userid,
			email: email,
			message: message,
			title: title
		},
		function(content) {
			neoModalViewWithContent(content, 1);
			
			setTimeout('neoModalView("close")', 5000);
		}
	);
}

function submitEmailForm(nid)
{
	var username = $("#username").get(0).value;
	var t_username = $("#t_username").get(0).value;
	var userid = $("#userid").get(0).value;
	var email = $("#email").get(0).value;
	var t_email = $("#t_email").get(0).value;
	var message = $("#message").get(0).value;
	
	if (!username) {
		$("#username").css("background-color","#ffcccc");
		return false;
	} else if (!email) {
		$("#email").css("background-color","#ffcccc");
		return false;
	} else if (!t_email) {
		$("#t_email").css("background-color","#ffcccc");
		return false;
	}
	
	$.get("/index.php?act=ajax_email_send",
		{
			username: username,
			userid: userid,
			email: email,
			message: message,
			t_email: t_email,
			t_username: t_username,
			nid: nid
		},
		function(content) {
			neoModalViewWithContent(content, 1);
			
			setTimeout('neoModalView("close")', 5000);
		}
	);
}

function article_page_select() {
    var page  =  $("select#pages").val();
    top.location.href = page;
    return true;
}

function writePodcast(file){document.write('<object type="application/x-shockwave-flash" data="http://staff.neowin.net/rob/player.swf" id="audioplayer1" height="24" width="290"><param name="movie" value="http://staff.neowin.net/rob/player.swf"><param name="FlashVars" value="playerID=1&amp;bg=0xdce7f1&amp;leftbg=0xb2c9e0&amp;lefticon=0xffffff&amp;rightbg=0x8caed0&amp;rightbghover=0xb2c9e0&amp;righticon=0xffffff&amp;righticonhover=0xffffff&amp;text=0xb2c9e0&amp;slider=0x8caed0&amp;track=0xFFFFFF&amp;border=0x6699cc&amp;loader=0xb2c9e0&amp;soundFile='+file+'"><param name="quality" value="high"><param name="menu" value="false"><param name="wmode" value="transparent"></object>');}
function writePodcastButton(file){document.write('<object type="application/x-shockwave-flash" data="http://staff.neowin.net/rob/buttonplayer.swf?&song_url='+file+'" width="17" height="17"><param name="movie" value="http://staff.neowin.net/rob/buttonplayer.swf?&song_url='+file+'" /></object>');}
function doAddFacebook(title, file){u="http://www.neowin.net/podcast.php?file="+file+"&title="+title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u),'sharer','toolbar=0,status=0,width=626,height=436');return false;}


//  *** PLUGINS

// jQuery-Cookie
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
