jQuery(function(){
    jQuery("a[rel].overlaylink").overlay({
        mask: {
            color: '#000000',
            loadSpeed: 500,
            closeSpeed:0,
            opacity: 0.5
        },
        top:    'center',
        speed:  0,
        onBeforeLoad: function() { 
            var wrap = this.getOverlay().find(".contentWrap");
            wrap.html('<h3 class="overlayload">LOADING...</h3>');
            wrap.load(this.getTrigger().attr("href")); 
        }
    });
    // dChatJS.initialize();
	jQuery("#userNav img").hover(
	 function(){
	  this.src = this.src.replace("_dim","_over");
	 },
	 function(){
	  this.src = this.src.replace("_over","_dim");
	 }
	);
	jQuery("#friendSearch").bind("keydown keyup keypress", function(event) {
		if(event.type == "keypress" && event.keyCode == 13)
			runSearch();
	});
	jQuery("img[title]").tooltip({
	    position: 'bottom center',
            effect: 'slide'
        });
        if(jQuery('.addthis_toolbox').length>0){
            addthis.init();
        }
	//jQuery('#ad160space').load('/ads.html');
});

var dVideos = {
    featureVideo: function(videoid){
	    jQuery.ajax({
		    url: "/video/ax",
		    type: "POST",
		    data: "action=featurevideo&id=" + escape(videoid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('I am awesome!', 'I can feature videos!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    featureHomeVideo: function(videoid) {
	    jQuery.ajax({
		    url: "/video/ax",
		    type: "POST",
		    data: "action=homefeaturevideo&id=" + escape(videoid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('Home PAGE Awesomesness..', '.. right there! EPIC!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    removeFeatureVideo: function(videoid){
	    jQuery.ajax({
		    url: "/video/ax",
		    type: "POST",
		    data: "action=rmfeaturevideo&id=" + escape(videoid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('I am awesome!', 'I can (de)feature videos!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    saveTitle: function(videoid){
        jQuery.ajax({
                url: "/dashboard/ax",
                type: "POST",
                data: "action=videotitle&title=" + escape(jQuery('input.editorbox').val()) + "&id="+videoid,
                dataType: "json",
                success: function(){
                    jQuery(".updateTitle").text(jQuery('input.editorbox').val());
                    jQuery("a.editlink").show();
                    jQuery("a.editclink").hide();
                }
        });
    },
    renameTitle: function(){
        if (jQuery(".updateTitle").children('input').length == 0){
            jQuery("a.editlink").hide();
            jQuery("a.editclink").show();
            var inputbox = "<input type='text' class='editorbox' value=\""+jQuery(".updateTitle").text()+"\">";
            jQuery(".updateTitle").html(inputbox);
            jQuery("input.editorbox").focus();
        }
    }
}

var dBlogs = {
    deleteBlog: function(blogid){
	    jQuery.ajax({
		    url: "/blogs/ax",
		    type: "POST",
		    data: "action=deleteblog&id=" + escape(blogid),
		    dataType: "json",
		    success: function(data){
		        location.href='/blogs';
		    }
	    });
    },
    featureBlog: function(blogid){
	    jQuery.ajax({
		    url: "/blogs/ax",
		    type: "POST",
		    data: "action=featureblog&id=" + escape(blogid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('I am awesome!', 'I can feature blogs!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    featureHomeBlog: function(blogid){
	    jQuery.ajax({
		    url: "/blogs/ax",
		    type: "POST",
		    data: "action=homefeatureblog&id=" + escape(blogid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('Stuff is HOME paged!', 'I can POST STUFF ON THE HOME PAGE!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    removeFeatureBlog: function(blogid){
	    jQuery.ajax({
		    url: "/blogs/ax",
		    type: "POST",
		    data: "action=rmfeatureblog&id=" + escape(blogid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('UNDONE!', 'This blog is no longer awesome!', [dDialog.okButton], forCallback);
		    }
	    });
    }
}

var dPics = {
    deleteGallery: function(galleryid){
	    jQuery.ajax({
		    url: "/pics/ax",
		    type: "POST",
		    data: "action=deletegallery&id=" + escape(galleryid),
		    dataType: "json",
		    success: function(data){
		        location.href='/members/' + data['username'] + '/galleries';
		    }
	    });
    },
    featureHomePicture: function(pictureid){
	    jQuery.ajax({
		    url: "/pics/ax",
		    type: "POST",
		    data: "action=homefeaturepic&id=" + escape(pictureid),
		    dataType: "json",
		    success: function(data){
		        dDialog.show('Home PAGE beauty..', '.. posted!', [dDialog.okButton], forCallback);
		    }
	    });
    }
}

var Dash = {
    updateStatus: function(){
        var tpost = "";
        var tsfb = 'false';
        tpost = jQuery("#statusText").val();
        if(jQuery('#facebook_post').is(':checked'))
            tsfb = 'true';
        if(tpost.length < 260){
            if(tpost.length > 0 && jQuery("#statusText").val() != "Shout to all your friends!") {
                jQuery('#ustat button').text('....');
                jQuery('#ustat button').attr("disabled", "true");
                jQuery.ajax({
	                url: "/members/ax",
	                type: "POST",
	                data: ({ action: 'postuserfeed', whisper: '0', posttext: tpost, fb: tsfb }),
	                dataType: "json",
	                success: function(data){
                            jQuery('#ustat').slideToggle(500);
                            jQuery('.myStatus').html(jQuery('#statusText').val());
                            dChatJS.postNotification(jQuery('#statusText').val());
                            jQuery('#supdatebtn').show();
                            jQuery('#sclearbtn').show();
                            jQuery("#statusText").val('Shout to all your friends!')
                            jQuery('#ustat button').text('Shout!');
                            jQuery('#ustat button').attr("disabled", "false");
                            jQuery('#count').html(0);
                            jQuery('#bar').animate({"width": '0%'}, 1);
                            jQuery('#feed0').prepend(data["feedhtml"]);
                        }
                });
            } else {
                dDialog.show('You have to enter some text!', 'Your status just feels so empty inside.', [dDialog.okButton], forCallback);
            }
        } else {
                dDialog.show('Let your words be few!', 'Your shout can only include 250 characters - keep it loud but short!', [dDialog.okButton], forCallback);
        }
    },
    clearStatus: function(){
       jQuery.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);
                    jQuery('.myStatus').html('');
                    jQuery('#statusText').val('');
                    jQuery('#supdatebtn').show();
                    jQuery('#count').html(0);
                    jQuery('#bar').animate({"width": '0%'}, 1);
	       }
       });
    },
    showStatusArea: function(){
       jQuery('#ustat').slideToggle(500);
       jQuery('#supdatebtn').hide();
       jQuery('#sclearbtn').hide();
    },
    clearStatusDashSide: function(){
       jQuery('#supdatebtn').hide();
       jQuery('#sclearbtn').hide();
       Dash.clearStatus();
    },
    clearStatusMain: function(){
        jQuery('#sclearbtn').hide();
        userPost.clearStatus();
    },
    statusBoxFocus: function(){
	    if(jQuery('#statusText').val() == "Shout to all your friends!")
	    {
            jQuery('#statusText').val('');
	    }
    },
    statusBoxBlur: function(){
	    if(jQuery('#statusText').val() == "")
	    {
		    jQuery('#statusText').html('Shout to all your friends!');
	    }
    }
}

function runSearch(){
	var tstr = escape(jQuery("#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(jQuery("#friendSearch").val());
}

function findFriend(){
	var tstr = escape(jQuery("#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(jQuery("#searchFriend").val());
}

function loadTabList(sind, eind, lind, itemsperpage, feedpage, filter){
	var tfilter = '';
	if(filter == null) filter = '';
	if(filter != '') tfilter = '/' + escape(filter);
	jQuery("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>';
	}
	jQuery("ul.iconview-links").html(thtml);
	jQuery("ul.iconview-links").tabs("div.iconview-paging > div", {effect: 'ajax'});
	
	if(lind == 1)
	    jQuery("ul.iconview-links").css("visibility", "hidden");
	else
	    jQuery("ul.iconview-links").css("visibility", "visible");
}

var userData = {
    item: 0,
    itemtype: '',
    hideafter: false,
    confirmChange: function(confirmation){
        if(confirmation){
	        jQuery.ajax({
		        url: "/members/ax",
		        type: "POST",
		        data: "action=axfriend&id=" + escape(userData.item) + "&to="+userData.itemtype,
		        dataType: "json",
		        success: function(data){
		            if(data["result"]){
			            if(userData.hideafter)
				            jQuery("#friendId_" + data["id"]).hide(500);
				        dDialog.show('Updated', 'Friend info updated!', [dDialog.okButton], forCallback);
				        if(data["to"] == "favorite")
				            jQuery('#friendcircle').append('<li id="friendId_' + data["id"] + '"><img src="/pictures/v1/' + data["id"] + '/' + data["picturelinkinfo"]["profilepicturefilename"] + '_t2.jpg"> <a class="remove" style="" href="javascript:userData.axFriend(' + data["id"] + ', \'friend\', true);">Remove from friend circle</a></li>');
				    } else {
				        dDialog.show('No can do!', 'You can only have 5 friends in your circle!', [dDialog.okButton], forCallback);
				    }
		        }
	        });
        }
    },
    loadListFeed: function(pagename, divid){
	    tpage++;
	    jQuery.ajax({
	      url: "/" + pagename + "/" + tpage,
	      cache: false,
	      success: function(html){
		    if(html == '') jQuery('#getMoreControl').hide(500);
		    jQuery("#" + divid).append(html);
	      }
	    });
    },
    axFriend: function(id, to, hideafter) {
        userData.item = id;
        userData.itemtype = to;
        userData.hideafter = hideafter;
        dDialog.show('Confirmation', 'You totally sure about that?', [dDialog.yesButton, dDialog.noButton], userData.confirmChange);        
    },
    addFriend: function(id) {
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=addfriend&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        jQuery("#friendId_" + data["id"]).remove();
		        dDialog.show('Request Submitted', 'Friend request has been submitted!', [dDialog.okButton], forCallback);
		        if(jQuery('ul#addFriend li').size() == 0 && location.hash == '#!/dashboard')
                             dNav.loadAX('/dashboard');
		    }
	    });
    },
    addNetwork: function(id) {
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=addnetwork&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        jQuery("#friendId_" + data["id"]).remove();
		        dDialog.show('Done!', 'Network added!', [dDialog.okButton], forCallback);
		    }
	    });
    },
    approveFriend: function(id) {
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=approvefriend&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        jQuery("#friendId_" + data["id"]).remove();
		        dDialog.show('Approved!', 'You\'ve got a new friend!', [dDialog.okButton], forCallback);
		        if(jQuery('ul#addFriend li').size() == 0)
                             dNav.loadAX('/dashboard');
		    }
	    });
    },
    dismissFriend: function(id){
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=dismissfriend&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        jQuery("#friendId_" + data["id"]).remove();
		        if(jQuery('ul#addFriend li').size() == 0)
                             dNav.loadAX('/dashboard');
		    }
	    });
    },
    dismissRecommended: function(id){
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=dismissrecommended&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        jQuery("#friendId_" + data["id"]).remove();
                        if(jQuery('ul#addFriend li').size() == 0)
                            dNav.loadAX('/dashboard');
		    }
	    });
    },
    removeUserPost: function(id){
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=removeuserpost&id=" + escape(id) ,
		    dataType: "json",
		    success: function(data){
		        jQuery("#uf_" + data["id"]).hide(500);
		        dDialog.show('Removed!', 'Post removed.', [dDialog.okButton], forCallback);
		    }
	    });
    }
}

var convJS = {
    submitPost: function(conversationid, replytoid, itemid, typeid){
        var comments = '';
        var whisper = false;
        comments = jQuery('#cp_' + replytoid).val();
        //whisper  = jQuery('#cpw_' + replytoid).is(':checked');
        mtype = jQuery('#cpw_' + replytoid).val();
        if(comments != ''){
            jQuery('#cp_' + replytoid).attr('disabled', 'disabled');
            jQuery('#cpb_' + replytoid).attr('disabled', 'disabled');
            jQuery('#cp_' + replytoid).val('');
            if(mtype == undefined) mtype = 0;
	        jQuery.ajax({
		        url: "/conversation/ax",
		        type: "POST",
                        data: ({ action: 'post', mtype: mtype, item: itemid, type: typeid, id: conversationid, reply: replytoid, com: comments }),
		        dataType: "json",
		        success: function(data){
                            jQuery('#cp_' + replytoid).closest("li").before(data["html"]);
                            jQuery('#cp_' + replytoid).attr('disabled', null);
                            jQuery('#cpb_' + replytoid).attr('disabled', null);
                            if(mtype == "2")
                                dChatJS.postNotification(data["notify"]);
                        }
	        });
	    } else {
	        dDialog.show('Where is the text?', 'Please type something in before pushing buttons!', [dDialog.okButton], forCallback);
	    }
    },
    leaveConversation: function(conversationid){
        jQuery.ajax({
            url: "/conversation/ax",
            type: "POST",
            data: "action=leave&id=" + conversationid,
            dataType: "json",
            success: function(data){
                jQuery('a.leaveconv').hide(300);
                dDialog.show('You left this Conversation.', 'You\'re no longer a part of this conversation!', [dDialog.okButton], forCallback);
            }
        });
    },
    showReply: function(commentid, elem){
        jQuery('#rl_' + commentid).show(0);
        jQuery('#rlb_' + commentid).hide(0);
    },
    addFriendTag: function(userid, conversationid, itemid, typeid){
        jQuery.ajax({
	        url: "/conversation/ax",
	        type: "POST",
	        data: "action=tagfriend&userid=" + escape(userid) + "&conversationid=" + escape(conversationid) + "&itemid=" + escape(itemid) + "&typeid=" + escape(typeid),
	        dataType: "json",
	        success: function(data){
                jQuery("#friendId_" + userid).hide(500);
                if(jQuery("#taggedUserList").html() == '')
                    jQuery("#taggedUserList").append('<b class="tagged">Member tags:</b><a href="/members/' + data["username"] + '" class="tagged">' + data["name"] + '</a>');
                else
                    jQuery("#taggedUserList").append('<a href="/members/' + data["username"] + '" class="tagged">' + data["name"] + '</a>');
                dDialog.show('Friend tagged.', 'Your friend has been tagged!', [dDialog.okButton], forCallback);
	        }
        });
    },
    reportAbuse: function(){
        jQuery.ajax({
	        url: "/conversation/ax",
	        type: "POST",
	        data: "action=report&pageurl=" + escape(location.href) + "&comments=" + escape(jQuery('#reportcomments').val()),
	        dataType: "json",
	        success: function(data){
	            jQuery('#convol').hide();
	            jQuery('.reportlink').hide();
	            dDialog.show('Submitted', 'Report will be investigated!', [dDialog.okButton], forCallback);
	        }
        });
    }
}

var userPost = {
    activeConversation: 0,
    submit: function(userid, emptytxt){
	    var tpost = jQuery("#feedPostText").val();
	    var twhis = jQuery("#whisper").val();
	    if(twhis == '1') twhis = 'true';
	    if(tpost.length < 5000){
	        if(tpost.length > 0 && emptytxt != tpost) {
	            jQuery("#feedPostText").val('');
		        jQuery.ajax({
			        url: "/members/ax",
			        type: "POST",
                                data: ({ action: 'postuserfeed', whisper: twhis, posttext: tpost, touserid: userid }),
			        dataType: "json",
			        success: function(data){
	    		        jQuery('#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);
	        }
	    } else {
	        dDialog.show('Let your words be few!', 'Your shout can only include so many characters - keep it a bit shorter!', [dDialog.okButton], forCallback);	    
	    }
    },
    loadDashConversation: function(conversationid, itemid, typeid, listitem){
        jQuery('#fc_' + listitem).hide(0);
        jQuery('#uf_' + listitem).closest("li").after('<li id="activeConversation_' + listitem + '" class="conversation"><h3 style="display: block; margin: 20px;">Loading conversation...</h3></li>');
	    jQuery.ajax({
		    url: "/dashboard/ax",
		    type: "POST",
		    data: "action=openconversation&style=slim&conversationid=" + escape(conversationid) + "&itemid=" + escape(itemid) + "&typeid=" + escape(typeid) + "&listitem=" + escape(listitem),
		    dataType: "json",
		    success: function(data){
		        if(userPost.activeConversation != 0){
		            jQuery('#activeConversation_' + userPost.activeConversation).remove();
                    jQuery('#fc_' + userPost.activeConversation).show();
		        }
		        jQuery('#activeConversation_' + data["listitem"]).html(data["html"]);
		        userPost.activeConversation = listitem; 
		    }
	    });
    },
    openConversation: function(feedid, whisper){
        jQuery('#cb_' + feedid).hide();
        jQuery('#uf_' + feedid).closest("li").after('<li id="activeConversation_' + feedid + '" class="conversation"><h3 style="display: block; margin: 20px;">Loading conversation...</h3></li>');
	    jQuery.ajax({
		    url: "/members/ax",
		    type: "POST",
		    data: "action=openconversation&style=slim&feedid=" + escape(feedid) + "&whisper=" + escape(whisper),
		    dataType: "json",
		    success: function(data){
		        if(userPost.activeConversation != 0){
		            jQuery('#activeConversation_' + userPost.activeConversation).remove();
                            jQuery('#cb_' + userPost.activeConversation).show();
		        }
		        jQuery('#activeConversation_' + data["userfeedid"]).html(data["html"]);
                        //jQuery('#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(jQuery("#title").val());
	    if(title.length > 0 && content.length > 0) {
		    jQuery.ajax({
			    url: "/blogs/ax",
			    type: "POST",
			    data: "action=postblog&id=" + blogid + "&title=" + title + "&content=" + content,
			    dataType: "json",
			    success: function(data){
			        jQuery("#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(jQuery("#shoutText").val());
	    if(tpost.length > 0 && tpost.length < 500) {
		    jQuery.ajax({
			    url: "/shout/ax",
			    type: "POST",
			    data: "action=postshout&shouttext=" + tpost + "&itemid=" + escape(itemid) + "&itemtype=" + escape(itemtype),
			    dataType: "json",
			    success: function(data){
			        jQuery("#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(){
	    jQuery.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){
	    jQuery.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){
	    jQuery.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 = {
    alertCount: 0,
    mark: function(notifytype){
        if(notifytype == 3 && dAlerts.alertCount != 0){
	        jQuery.ajax({
		        url: "/dashboard/ax",
		        type: "POST",
		        data: "action=mark&type=" + escape(notifytype),
		        dataType: "json",
		        success: function(data){
		            if(data["result"] == true)
    		            jQuery('#dAlertContainer').hide();
		        }
	        });
	    }
    },
    alertMark: function(notifytype){
        jQuery.ajax({
            url: "/dashboard/ax",
            type: "POST",
            data: "action=mark&type=" + escape(notifytype),
            dataType: "json",
            success: function(data){
                // Write some stuff here
            }
        });
    }
}

var dPush = {
        dtimeout: 5000,
        shake: 0,
	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);
                if(dPush.shake == 0){
                    item.animate({
                            marginBottom: "0px",
                            marginTop: "10px"
                    }, 800, "linear", function() { setTimeout(dPush.closeTop, dPush.dtimeout); });
                } else {
                    item.animate({
                            marginBottom: "0px",
                            marginTop: "10px"
                    }, 0, "linear", function() { setTimeout(dPush.closeTop, dPush.dtimeout); });
                    jQuery('.dPush').effect("shake", {times: 3}, 50);
                }
	},
	closeTop: function()
	{
            jQuery(jQuery(".dPush_item")[0]).fadeOut("fast", function() { jQuery(jQuery(".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, "");
		theD.createWithClass("div", "dDialog_buttonContainer", ".dDialogBorder", "");
		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", jQuery(".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 = jQuery(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);
		
		jQuery(appendTo).append(temp);
		
		return temp;
	}
};

var dNav = {
    nowloaded: "",
    noaxstr: /elves/i,
    userDlg: function(dlgelem){
	if(jQuery('#userNavDlg_' + dlgelem).is(":hidden")){
		// jQuery('#ticn_' + dlgelem).attr('src', '/media/gfx/ticon_profile_over.gif?test');
		jQuery('.uDiag').hide();
		jQuery('#userNavDlg_' + dlgelem).slideDown(300);
                // AJAX LOAD COMMENT
                jQuery.ajax({
                    url: "/dashboard/ax",
                    type: "POST",
                    data: "action=axdialog&dialog=" + escape(dlgelem),
                    dataType: "json",
                    success: function(data){
                        jQuery('#userNavDlg_' + data["dlgelem"]).html(data["html"]);
                    }
        });

	} else {
		jQuery('#userNavDlg_' + dlgelem).slideUp(300);
	}
    },
    loadAX: function(clickhref){
            var runax = true;
            //var thashcur = location.href.replace('http://thedonline.com', '');
            var thashcur = location.pathname + location.hash;
            var thash = clickhref.replace('http://' + location.host, '');
            if(location.href.substring(0,5) == 'https') runax = false;
            if(runax){
                if(thashcur.search(dNav.noaxstr) != -1)
                    runax = false;
            }
            if(runax){
                if(thashcur.search(/#!/i) != -1){
                    dNav.nowloaded = thash;
                    location.hash = '!' + thash;
                    pageTracker._trackPageview(thash);
                    jQuery('#mainContentContainer').addClass('transparent_class');
                    jQuery.ajax({
                            url: clickhref,
                            type: "POST",
                            data: ({ axload:'true' }),
                            success: function(data){
                                jQuery('#mainContentContainer').html(data['htmlcontent']);
                                jQuery('#mainContentContainer').removeClass('transparent_class');
                                if(data['jscontent'] != "")
                                    eval(data['jscontent']);
                                if(data['titlecontent'] != null)
                                    document.title = data['titlecontent'] + ' - TheDesperate.com';
                                jQuery('html, body').animate({scrollTop:0}, 'slow');
                                if(data['userid'] != 0){
                                    if(data['conversations'] != '0')
                                        jQuery('#ticn_3').attr("src", jQuery('#ticn_3').attr("src").replace("_dim","_lit"));
                                    else
                                        jQuery('#ticn_3').attr("src", jQuery('#ticn_3').attr("src").replace("_lit","_dim"));

                                    if(data['alerts'] != '0')
                                        jQuery('#ticn_2').attr("src", jQuery('#ticn_2').attr("src").replace("_dim","_lit"));
                                    else
                                        jQuery('#ticn_2').attr("src", jQuery('#ticn_2').attr("src").replace("_lit","_dim"));
                                }
                            }
                    });
                } else {
                    location.href='/ax#!' + thash;
                }
                return true;
            } else {
                return false;
            }
    }
};

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

function closeOverlays(){
    jQuery("a[rel].overlaylink").each(function() {
        if (jQuery(this).overlay()) {
        jQuery(this).overlay().close();
        }
    });
}

/* D1MENU */
function showClickMenu(el1){
 elem1=document.getElementById(el1);
 if(elem1.style.display=="none"){
  loadMenuContent(el1);
  elem1.style.display="block";
 }
 else
 {
	 clearTimeout(closeTimeout[elem1.id]);
	 elem1.style.display="none";
 }
}

function hideClickMenu(el1){
 elem1=document.getElementById(el1);
 if(elem1.style.display!="none"){
  elem1.style.display="none";
 }
}

var timeToHide = 700;
var closeTimeout = new Array();

function showMenu(id)
{
	clearTimeout(closeTimeout[id]);
	if(arguments[1] != 1)
	{
		var element = document.getElementById(id);
		element.style.display = "block";
	}
}

function hideMenu(element)
{
    element = document.getElementById(element);
    closeTimeout[element.id] = setTimeout(
    function()
    {
        	element.style.display = "none";
    },
    timeToHide);
}

/* BIBLE SEARCH */
function bSearch(){
	var keywords = jQuery('#bsearchtxt').val();
	if(keywords != '')
		location.href = '/biblesearch/' + escape(keywords).replace('%20', '+').replace('%20', '+');
}

function setInputChange() {
	var both = jQuery("#username, #passwordFake");
	both.addClass("fadedInput");

	var usr = jQuery("#username");
	usr.val(usr.attr("defaultValue"));

	jQuery("#passwordFake").val(jQuery("#passwordFake").attr("defaultValue"));

	usr.bind("focus", function() {
		var t = jQuery(this);

		if (t.val() == this.defaultValue && t.hasClass("fadedInput")) {
			t.removeClass("fadedInput");
			t.val("");
		}
	});

	jQuery("#passwordFake").bind("focus", function() {
		var t = jQuery(this);

		t.css("display", "none");
		jQuery("#passwordReal").css("display", "inline");
		jQuery("#passwordReal").focus();
	});

	usr.bind("blur", function() {
		var t = jQuery(this);

		if(jQuery.trim(t.val()) == "") {
			t.addClass("fadedInput");
			t.val(this.defaultValue);
		}
	});

	jQuery("#passwordReal").bind("blur", function() {
		var t = jQuery(this);

		if (jQuery.trim(t.val()) == "") {
			jQuery("#passwordFake").css("display", "inline");
			t.css("display", "none");
		}
	});
}

// call Login
function callLogin()
{
    var username = jQuery.trim(jQuery("#username").attr("value"));
    var password = jQuery.trim(jQuery("#passwordReal").attr("value"));
    var keeplogg = "0";

	if (jQuery('#keeploggedin:checked').val() != null)
		keeplogg = "1";

	jQuery("#login_error_message").hide();

    if(username == "" || password == "" || username == "Username")
    {
		jQuery("#loginErrorTxt").html("Please fill in your username/password!");
		jQuery("#login_error_message").show(400);
		// dDialog.show('Error', 'Please fill in your email/password!', [dDialog.okButton], forCallback);
    } else {
	jQuery.ajax({
            type: "POST",
            url: "/home/ax",
            dataType: "json",
            data: "action=login&u=" + username + "&p=" + password + "&l=" + keeplogg + "&g=" + -(new Date).getTimezoneOffset()/60,
            success: checkLogin
          });
    }
}

function checkLogin(data)
{
    if(data["result"] == "true") {
        if(data["url"] != ""){
            window.location = "http://" + location.host  + "/" + data["url"];
        } else {
            if(window.location.pathname == "/")
                window.location = "http://" + location.host  + "/ax#!/dashboard";
            else
                window.location.reload(true);
        }
    } else {
		jQuery("#loginErrorTxt").html("Unable to login - please check your username/password!");
		jQuery("#login_error_message").show(400);
    }
}

/*
 * Created by: actionMan on 7/25/09 8:50AM
 * Last Update: 7/25/09 10:56AM
 * Contributors: penguinMaster
 */

var reg = {
    //The Fields that we need to validate
    fields: {
        "First Name": { name: "s_firstname", minChar: "3", regEx: /^.{3,}jQuery/ },
        "Last Name": {  name: "s_lastname", minChar: "3", regEx: /^.{3,}jQuery/ },
        "Username": { name: "s_username", minChar: "3", maxChar: "20", regEx: /^[A-Za-z0-9_-]{3,20}jQuery/ },
        "Password": { name: "s_password", minChar: "6", maxChar: "16", regEx: /^.{6,16}jQuery/ },
        "Email": { name: "s_email", regEx: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)jQuery/i },
        "Birthday Month": { name: "bmonth" },
        "Birthday Day": { name: "bday" },
        "Birthday Year": { name: "byear" }
    },

//        "Username": {name: "s_username", minChar: "3", maxChar: "20", regEx: /^[A-Za-z0-9_-]{3,20}jQuery/ },
//        "Password": { name: "s_password", minChar: "6", maxChar: "16", regEx: /^.{6,16}jQuery/ },


    //Populate reg.fields[""].ele
    populate: function() {
        for(key in reg.fields) {
            reg.fields[key].ele = jQuery("*[name=" + reg.fields[key].name + "]");
        }
    },

    //To loop through all the fields and make sure it is not empty
    validate: function()
    {
		jQuery("#errorTxt").html("");
		jQuery("#error_message").hide(0);
        for(key in reg.fields) {
            //Get current field object from loop
            var fieldObj = reg.fields[key];

            //Get the current field from the loop
            var field = fieldObj.ele;

            //Set the trimmed value
            var fieldValue = jQuery.trim(field.attr("value"));

            //It's a text field
            if(field.attr("type") == "text" || field.attr("type") == "password") {
                //Check if empty value
                if(fieldValue == "")
                {
                    //It's empty, let's show a error to the user
                    reg.error(key + " is empty. Please fill it in.", field);

                    //Break out of loop and return false
                    return false;

                } else if (!fieldObj.regEx.test(fieldValue)) { //Check against regExp
                    //Check to see if there is a min or max char specified
                    if(fieldObj.minChar || fieldObj.maxChar)
                    {
                        //Build char limit str
                        var charStr = (fieldObj.minChar) ? " must be " + fieldObj.minChar + " chars" : "";
                        charStr += (charStr == "" && fieldObj.maxChar) ? " must be " + fieldObj.maxChar + " chars" : (fieldObj.maxChar) ? " to " + fieldObj.maxChar + " characters" : "";

                        //Show char error
                        reg.error(key + charStr + ".", field);

                        //Break out of loop and return false
                        return false;

                    }
                    else { //Assume the problem is not a size issue but a validation issue
                        reg.error(key + " is not valid.", field);

                        //Break out of loop and return false
                        return false;
                    }
                }
            } else { //It's not a text field. We'll assume it's a select box
                if(fieldValue == "-1") {
                    reg.error("Please select your " + key + ".", field);

                    //Break out of loop and return false
                    return false;
                }
            }
        }

        //Most of the checks are now passed, let's do one of the final steps; determine how old the user is
        //The current date obj
        var currentDate = new Date();

        //Birthday month
        var bDayMonth = reg.fields["Birthday Month"].ele.attr("value");

        //Birthdate
        var bDate = reg.fields["Birthday Day"].ele.attr("value");

        //Birthday Year
        var bDayYear = reg.fields["Birthday Year"].ele.attr("value");

        //Birthday date object
        var bDayObj = new Date(bDayMonth + ", " + bDate + ", " + bDayYear);

        //Let's minus the bDay date obj from the current date obj, and divide it down to years
        var userYearAge = (currentDate - bDayObj)/1000/60/60/24/365;

        //Check if the user is over 13
        if (userYearAge < 14) {
            reg.error("Sorry, you are not eligible to register on TheD.", reg.fields["Birthday Month"].ele);

            //Break out of loop and return false
            return false;
        } else { //All checks have passed except the "In Use" username/email check, which is the final check
            reg.checkUse();
        }

        return true;
    },

    //Check if email or username is in use
    checkUse: function()
    {
        var usernameValue = reg.fields["Username"].ele.attr("value");
        var emailValue = reg.fields["Email"].ele.attr("value");
        var firstnameValue = reg.fields["First Name"].ele.attr("value");
        var lastnameValue = reg.fields["Last Name"].ele.attr("value");
		var passwordValue = reg.fields["Password"].ele.attr("value");
        var bDayMonth = reg.fields["Birthday Month"].ele.attr("value");
        var bDayDay = reg.fields["Birthday Day"].ele.attr("value");
        var bDayYear = reg.fields["Birthday Year"].ele.attr("value");

        jQuery.ajax({
            type: "POST",
            url: "/home/ax",
            dataType: "text",
            data: "action=registeruser&username=" + usernameValue + "&email=" + emailValue + "&firstname=" +
					firstnameValue + "&lastname=" + lastnameValue + "&password=" + passwordValue +
					"&bmonth=" + bDayMonth + "&bday=" + bDayDay + "&byear=" + bDayYear,
            success: function (inUse) {
                var usernameEle = reg.fields["Username"].ele;
                var emailEle = reg.fields["Email"].ele;

                switch(inUse)
                {
                    case "sweet":
                        reg.register();
                        break;
                    case "username":
                        reg.error("The username you picked is already in use.", usernameEle);
                        break;
                    case "email":
                        reg.error("The email you used is already registered.", emailEle);
                        break;
                    case "both":
                        reg.error("The username AND email you used is already registered.", usernameEle);
                        break;
                    case "validate":
                        reg.error("Unable to validate. Please check your information.", usernameEle);
                        break;
                }
            }
          });
    },

    register: function()
    {
		location.href = '/filldetails';
    },

    //To show the error to the user
    error: function(str, field)
    {
		jQuery("#errorTxt").html(str);
		jQuery("#error_message").show(400);
		field.focus();
    }
};


/*
 * jQuery UI Effects 1.8.6
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/
 */
jQuery.effects||function(f,j){function m(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1],
16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return n.transparent;return n[f.trim(c).toLowerCase()]}function s(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return m(b)}function o(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,
a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function p(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in t||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function u(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function k(c,a,b,d){if(typeof c=="object"){d=
a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}if(f.isFunction(b)){d=b;b=null}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:f.fx.speeds[b]||f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}function l(c){if(!c||typeof c==="number"||f.fx.speeds[c])return true;if(typeof c==="string"&&!f.effects[c])return true;return false}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor",
"borderColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=s(b.elem,a);b.end=m(b.end);b.colorInit=true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var n={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,
0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],
lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},q=["add","remove","toggle"],t={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=
b;b=null}return this.each(function(){var e=f(this),g=e.attr("style")||" ",h=p(o.call(this)),r,v=e.attr("className");f.each(q,function(w,i){c[i]&&e[i+"Class"](c[i])});r=p(o.call(this));e.attr("className",v);e.animate(u(h,r),a,b,function(){f.each(q,function(w,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments)})})};f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?
f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===j?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,
[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.8.6",save:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b=0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=
0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y:b}},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent();var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,
{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10)))a[e]="auto"});c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=
k.apply(this,arguments),b={options:a[1],duration:a[2],callback:a[3]};a=b.options.mode;var d=f.effects[c];if(f.fx.off||!d)return a?this[a](b.duration,b.callback):this.each(function(){b.callback&&b.callback.call(this)});return d.call(this,b)},_show:f.fn.show,show:function(c){if(l(c))return this._show.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(l(c))return this._hide.apply(this,arguments);else{var a=
k.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(l(c)||typeof c==="boolean"||f.isFunction(c))return this.__toggle.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,
a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*
(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,
a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2,10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,
a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)*a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+
d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeInOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==
j)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b},easeInOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*
(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0,d,e)*0.5+b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery);
;/*
 * jQuery UI Effects Shake 1.8.6
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Shake
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),j=["position","top","left"];d.effects.setMode(b,a.options.mode||"effect");var c=a.options.direction||"left",e=a.options.distance||20,l=a.options.times||3,f=a.duration||a.options.duration||140;d.effects.save(b,j);b.show();d.effects.createWrapper(b);var g=c=="up"||c=="down"?"top":"left",h=c=="up"||c=="left"?"pos":"neg";c={};var i={},k={};c[g]=(h=="pos"?"-=":"+=")+e;i[g]=(h=="pos"?"+=":"-=")+e*2;k[g]=(h=="pos"?"-=":"+=")+
e*2;b.animate(c,f,a.options.easing);for(e=1;e<l;e++)b.animate(i,f,a.options.easing).animate(k,f,a.options.easing);b.animate(i,f,a.options.easing).animate(c,f/2,a.options.easing,function(){d.effects.restore(b,j);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery);
;
