$(document).ready(function()
{
    $("a[rel]").overlay({ 
        expose: 'gray', 
        onBeforeLoad: function() { 
            var wrap = this.getContent().find(".contentWrap"); 
            wrap.load(this.getTrigger().attr("href")); 
        }  
    });
    // dChatJS.initialize();

	$("#friendSearch").bind("keydown keyup keypress", function(event) {
		if(event.type == "keypress" && event.keyCode == 13)
			runSearch();
	});
	//$('#ad160space').load('/ads.html');	
});

function runSearch(){
	var tstr = escape($("#friendSearch").val());
	if(tstr == '' || tstr == escape('Member Search'))
		dDialog.show('Enter your friend\'s name.', 'Type your friend\'s name in and we\'ll help you find them!', [dDialog.okButton], forCallback);
	else
		location.href='/search/'+escape($("#friendSearch").val());
}

function findFriend(){
	var tstr = escape($("#findFriend").val());
	if(tstr == '')
		dDialog.show('Where is your text?', 'Please type something in and we\'ll help you find your friend!', [dDialog.okButton], forCallback);
	else
		location.href='/search/'+escape($("#searchFriend").val());
}

function loadTabList(sind, eind, lind, itemsperpage, feedpage, filter){
	var tfilter = '';
	if(filter == null) filter = '';
	if(filter != '') tfilter = '/' + escape(filter);
	$("ul.iconview-links").removeData("tabs");
	var thtml = '';
	if(sind > 1){
		var tsind = 1;
		if((sind-itemsperpage) > 1) tsind = (sind-itemsperpage);
		thtml += '<li><span class="iconview-ltab" onclick="loadTabList(' + tsind + ',' + (tsind+itemsperpage-1) + ',' + lind + ',' + itemsperpage + ', \'' + feedpage + '\', \'' + filter + '\');"><<</span></li>';
	}
	for(i = 0; i < (eind-sind+1); i++){
		if((sind+i) > lind)
			break;
		thtml += '<li><a href="/' + feedpage + '/' + (sind+i) + tfilter + '">' + (sind+i) +  '</a></li>';
	}
	if(lind > eind){
		var teind = lind;
		if((eind+itemsperpage) < lind) teind = (eind+itemsperpage);
		thtml += '<li><span class="iconview-ltab" onclick="loadTabList(' + (eind+1) + ',' + teind + ',' + lind + ',' + itemsperpage + ', \'' + feedpage + '\', \'' + filter + '\');">>></span></li>';
	}
	$("ul.iconview-links").html(thtml);
	$("ul.iconview-links").tabs("div.iconview-paging > div", {effect: 'ajax'});
	
	if(lind == 1)
	    $("ul.iconview-links").css("visibility", "hidden");
	else
	    $("ul.iconview-links").css("visibility", "visible");
}

var userData = {
    loadListFeed: function(pagename, divid){
	    tpage++;
	    $.ajax({
	      url: "/" + pagename + "/" + tpage,
	      cache: false,
	      success: function(html){
		    if(html == '') $('#getMoreControl').hide(500);
		    $("#" + divid).append(html);
	      }
	    });
    },

    axFriend: function(id, to, hideafter) {
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=axfriend&id=" + escape(id) + "&to="+to,
		    dataType: "json",
		    success: function(data){
			    if(hideafter)
				    $("#friendId_" + data["id"]).hide(500);
				dDialog.show('Updated', 'Friend info updated!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    addFriend: function(id) {
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=addfriend&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        $("#friendId_" + data["id"]).hide(500);
		        dDialog.show('Request Submitted', 'Friend request has been submitted!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    addNetwork: function(id) {
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=addnetwork&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        $("#friendId_" + data["id"]).hide(500);
		        dDialog.show('Done!', 'Network added!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    approveFriend: function(id) {
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=approvefriend&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        $("#friendId_" + data["id"]).hide(500);
		        dDialog.show('Approved!', 'You\'ve got a new friend!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    dismissFriend: function(id){
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=dismissfriend&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        $("#friendId_" + data["id"]).hide(500);
		        dDialog.show('Dismissed!', 'Contact request dismissed.', [dDialog.okButton], forCallback);
		    }
	    });
    },
    dismissRecommended: function(id){
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=dismissrecommended&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        $("#friendId_" + data["id"]).hide(500);
		        dDialog.show('Dismissed!', 'Recommendation dismissed.', [dDialog.okButton], forCallback);
		    }
	    });
    }
}

var convJS = {
    submitPost: function(conversationid, replytoid, itemid, typeid){
        var comments = '';
        var whisper = false;
        comments = $('#cp_' + replytoid).val();
        //whisper  = $('#cpw_' + replytoid).is(':checked');
        mtype = $('#cpw_' + replytoid).val();
        if(comments != ''){
            $('#cp_' + replytoid).attr('disabled', 'disabled');
            $('#cpb_' + replytoid).attr('disabled', 'disabled');
            $('#cp_' + replytoid).val('');
            if(mtype == undefined) mtype = 0;
	        $.ajax({
		        url: "/conversation/ax",
		        type: "POST",
		        data: "action=post&mtype=" + mtype + "&item=" + itemid + "&type=" + typeid + "&id=" + conversationid + "&reply="+replytoid+"&com="+escape(comments),
		        dataType: "json",
		        success: function(data){
                    $('#cp_' + replytoid).closest("li").before(data["html"]);
                    $('#cp_' + replytoid).attr('disabled', null);
                    $('#cpb_' + replytoid).attr('disabled', null);
                    //if(whisper == false)
					//    dChatJS.postNotification(data["notify"]);
		        }
	        });
	    } else {
	        dDialog.show('Where is the text?', 'Please type something in before pushing buttons!', [dDialog.okButton], forCallback);
	    }
    },
    leaveConversation: function(conversationid){
        $.ajax({
	        url: "/conversation/ax",
	        type: "POST",
	        data: "action=leave&id=" + conversationid,
	        dataType: "json",
	        success: function(data){
                $('#c_' + data["id"]).hide(300);
                dDialog.show('You left this Conversation.', 'You\'re no longer a part of this conversation!', [dDialog.okButton], forCallback);
	        }
        });
    },
    showReply: function(commentid, elem){
        $('#rl_' + commentid).show(0);
        $('#rlb_' + commentid).hide(400);
    }
}

var userPost = {
    activeConversation: 0,
    submit: function(userid){
	    var tpost = $("#feedPostText").val();
	    var twhis = $("#whisper").is(':checked');
	    if(tpost.length <= 5000 && tpost.length > 0) {
	        $("#feedPostText").val('');
		    $.ajax({
			    url: "/members/ax",
			    type: "POST",
			    data: "action=postuserfeed&touserid=" + escape(userid) + "&posttext=" + escape(tpost) + "&whisper=" + escape(twhis),
			    dataType: "json",
			    success: function(data){
	    		    $('#feedPostArea').closest("li").after(data["html"]);
					//dChatJS.postNotification('Post to ' + userid + '\'s profile:' + tpost);
			    }
		    });
	    } else {
	        dDialog.show('No Text Entered.', 'If you want to give your friends the silent treatment just don\'t click at all!', [dDialog.okButton], forCallback);
	    }
    },
    loadDashConversation: function(conversationid, itemid, typeid, listitem){
        $('#fc_' + listitem).hide(0);
	    $.ajax({
		    url: "/dashboard/ax",
		    type: "POST",
		    data: "action=openconversation&conversationid=" + escape(conversationid) + "&itemid=" + escape(itemid) + "&typeid=" + escape(typeid) + "&listitem=" + escape(listitem),
		    dataType: "json",
		    success: function(data){
    		    $('#uf_' + data["listitem"]).closest("li").after('<li id="activeConversation" class="conversation">' + data["html"] + '</li>');
		    }
	    });
    },
    openConversation: function(feedid){
        $('#cb_' + feedid).hide();
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=openconversation&feedid=" + escape(feedid),
		    dataType: "json",
		    success: function(data){
		        if(userPost.activeConversation != 0){
		            $('#activeConversation').remove();
		             $('#cb_' + userPost.activeConversation).show();
		        }
    		    $('#uf_' + data["userfeedid"]).closest("li").after('<li id="activeConversation" class="conversation">' + data["html"] + '</li>');
    		    userPost.activeConversation = feedid;
		    }
	    });
    },
    postBlog: function(blogid){
        var title = "";
        var content = "";
        content = escape(tinyMCE.activeEditor.getContent());
        title = escape($("#title").val());
	    if(title.length > 0 && content.length > 0) {
		    $.ajax({
			    url: "/blogs/ax",
			    type: "POST",
			    data: "action=postblog&id=" + blogid + "&title=" + title + "&content=" + content,
			    dataType: "json",
			    success: function(data){
			        $("#title").val('');
			        tinyMCE.activeEditor.setContent('');
			        if(data["edit"] == true)
			            dDialog.show('Blog Updated', 'Changes saved', [dDialog.okButton], forwardTo("/blogs"));
			        else
	    		        dDialog.show('Blog Posted!', 'Article submitted to TheDesperate.com', [dDialog.okButton], forwardTo("/blogs"));
			    }
		    });
	    } else {
	        dDialog.show('What in the world?', 'Put something in the box before you go mad and click away!', [dDialog.okButton], forCallback);
	    }
    },
    shoutDialog: function(itemid, itemtype){
		if(dDialog.dialog != undefined)
			dDialog.close();
        dDialog.dialog = theD.createWithClass("div", "dDialog", document.body, "shoutd_" + itemid, "<h3>SHOUT</h3><br/><p><input type=text style=\"width: 429px; opacity:0.8;filter:alpha(opacity=80)\" id=\"shoutText\"> <input type=button value=Post onclick=\"userPost.postShout(" + itemid + ", " + itemtype + ");\"></p><p style=\"margin: 4px 8px;text-align: right;\"><a href=\"#\" onclick=\"dDialog.close()\">cancel</a></p>");
        dDialog.dialog.fadeIn();
    },
    postShout: function(itemid, itemtype){
        var tpost = "";
        tpost = escape($("#shoutText").val());
	    if(tpost.length > 0 && tpost.length < 500) {
		    $.ajax({
			    url: "/shout/ax",
			    type: "POST",
			    data: "action=postshout&shouttext=" + tpost + "&itemid=" + escape(itemid) + "&itemtype=" + escape(itemtype),
			    dataType: "json",
			    success: function(data){
			        $("#shoutd_" + itemid).val('');
			        dDialog.close()
	    		    dDialog.show('You just shouted!', 'How do you feel?', [dDialog.okButton], forCallback);
	    		    // NOTIFY HERE
			    }
		    });
	    } else {
	        dDialog.show('What in the world?', 'Must have something in the box, and it cannot be a freakin book either.', [dDialog.okButton], forCallback);
	    }
    },
    statusDialog: function(){
        dDialog.show('We\'re switching things around!', 'You can update your status/post stuff on dashboard! You\'ll find the link under your pic on the left.', [dDialog.okButton], forCallback);
    },
    postStatus: function(itemid, itemtype){
        dDialog.show('Sorry, we\'re switching things around!', 'You can update your status/post stuff on dashboard! You\'ll find the link under your pic on the left.', [dDialog.okButton], forCallback);
    },
    clearStatus: function(){
	    $.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=postuserfeed&whisper=0&posttext=",
		    dataType: "json",
		    success: function(data){
    		    dDialog.show('Status Cleared!', 'Awesome stuff!', [dDialog.okButton], forCallback);
		    }
	    });
     },
    setProfilePic: function(id){
	    $.ajax({
		    url: "/dashboard/ax",
		    type: "POST",
		    data: "action=setprofilepic&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        if(data['result'])
		            dDialog.show('Profile Picture Changed!', 'It\'s official - you have a new profile picture!', [dDialog.okButton], forCallback);
		        else
		            dDialog.show('Something fialed..', 'I am trully sorrry but sompheting fwhent wrong.. Maybeh you misphelled something?', [dDialog.okButton], forCallback);
		    }
	    });
    },
    deletePicture: function(id, gallery){
	    $.ajax({
		    url: "/pics/ax",
		    type: "POST",
		    data: "action=delpic&gallery=" + escape(gallery) + "&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        if(data['result'])
		            dDialog.show('Picture wiped clean off', 'Used 44, the most powerful picture deleter in the world..', [dDialog.okButton], backToPics);
		        else
		            dDialog.show('Something fialed..', 'I am trully sorrry but sompheting fwhent wrong.. Maybeh you misphelled something?', [dDialog.okButton], forCallback);
		    }
	    });
    }
}

var dAlerts = {
    mark: function(notifytype){
        if(notifytype == 3 &&  ($('#dAlertContainer').is (':visible')) ){
	        $.ajax({
		        url: "/dashboard/ax",
		        type: "POST",
		        data: "action=mark&type=" + escape(notifytype),
		        dataType: "json",
		        success: function(data){
		            if(data["result"] == true)
    		            $('#dAlertContainer').hide();
		        }
	        });
	    }
    }
}

var dPush = {
	push: function(html) {
		if(dPush.container == undefined)
			dPush.container = theD.createWithClass("div", "dPush", document.body, "");
		
		var item = theD.createWithClass("div", "dPush_item", dPush.container, "", html);
		item.animate({
			marginBottom: "0px",
			marginTop: "10px"
		}, 800, "linear", function() { setTimeout(dPush.closeTop, 5000); });
	},
	closeTop: function()
	{	
		$($(".dPush_item")[0]).fadeOut("fast", function() { $($(".dPush_item")[0]).remove(); });
	}
};
var dDialog = {
	show: function(title, desc, buttons, callback) {
		if(dDialog.dialog != undefined)
			dDialog.close();
			
		dDialog.dialog = theD.createWithClass("div", "dDialog", document.body, "", "<div class=\"dDialogBorder\"><span class=\"dDialog_title\">" + title + "</span><br /><span class=\"dDialog_desc\">" + desc + "</span><br /></div>");
		theD.createWithClass("div", "dDialog_buttonContainer", dDialog.dialog, "");
		dDialog.dialog.fadeIn();
		
		for(var i = 0; i < buttons.length; i++)
		{
			if(typeof(buttons[i]) == "function")
			{
				buttons[i]();
			}
		}
		
		dDialog.userCallback = callback;
	},
	close: function() {
		dDialog.dialog.remove();
		
		dDialog.userCallback = undefined;
		dDialog.dialog = undefined;
	},
	callback: function(status) {
		dDialog.userCallback(status);
		dDialog.close();
	},
	createButton: function(text, value) {
		var button = theD.createWithClass("button", "dDialog_button", $(".dDialog_buttonContainer"), "", text);
		button.bind("click", function() {
			dDialog.callback(value);
		});
	},
	okButton: function() {
		dDialog.createButton("OK", true);
	},
	cancelButton: function() {
		dDialog.createButton("Cancel", false);
	},
	yesButton: function() {
		dDialog.createButton("Yes", true);
	},
	noButton: function() {
		dDialog.createButton("No", false);
	}
};
var theD = {
	createWithClass: function(eleType, cssClass, appendTo, elemId) {
		//Content optional
		var content = "";
		if(arguments[4]){ content = arguments[4]; }
		
		var temp = $(document.createElement(eleType));
		temp.addClass(cssClass);
		
		if(elemId != "")
		    temp.attr("id", elemId);
		
		if(temp.attr("value") != undefined && eleType != "button")
			temp.val(content);
		else
			temp.html(content);
		
		$(appendTo).append(temp);
		
		return temp;
	}
};

function forCallback(value)
{
	//alert(value);
}
function forwardTo(value)
{
	location.href=value;
}
function backToPics(){
    location.href='/userpictures';
}