var hoverOpenTimer, hoverCloseTimer, iActiveShelfId = 0;
// Open external link in a new window - fix for strict doctype invalidation

$(document).ready(function() {
    // TODO: Pending removal
    // Use <a href="http://address.com/" title="Title Here" onclick="window.open(this.href,'newwin'); return false;">Insert Link Title</a>
    $(".new-window").attr("target", "_blank");
    $("form").submit(RemoveParentheses);
    showBBCodeHelpReference();
});
function RemoveParentheses() {
    var inputs = $('[type=text],textarea');
    inputs.each(function(i, val) {
    inputs[i].value = inputs[i].value.replace(/</g, ' ').replace(/>/g, ' ');
    });   
}

// Settings for generic modal
showModal = function(oDim) {
    sHtml = '<div style="height:' + oDim.iH + 'px"><img id="imgLoading" src="/images/hoverModloader.gif" alt="Loading" width="16" height="16" /></div>';

    // Set coordinates for msie instead
    var oPos = ($.browser.msie) ? [(($(window).width()) / 2) - (oDim.iW / 2), (($(window).height()) / 2) - (oDim.iH / 2)] : "center";

    // Hide any hovers
    $(".hoverMod2").hide();
    var oMc = $('<div id="modalcopy" style="width:' + (oDim.iW + 16) + ';height:' + oDim.iH + ';">' + sHtml + '</div>');
    d = $("<div style='width:" + oDim.iW + ";height:" + oDim.iH + ";'>").append(oMc);
    d.dialog({ close: function() { $(this).parents(".ebModal").remove(); }, show: "fadeIn", resizable: false, dialogClass: "ebModal", modal: true, overlay: { "background-color": "#000", "opacity": "0.60", "-moz-opacity": "0.60" }, position: oPos, width: oDim.iW, height: oDim.iH });

    if ($.browser.msie && (parseInt($.browser.version) < 7)) {
        d.parents(".ebModal").pngFix();
        d.parents(".ebModal").bgiframe({ left: -20, top: -20, width: oDim.iW + 40, height: oDim.iH + 40 });
    }
    $(oMc).change(function() {
    $("input[name=submit],input[type=submit],input[type=image],input[type=button]").click(RemoveParentheses);
    });
    return oMc;
}

// Generic error modal
showError=function(sErr)
{
	// TODO: Use a nice modal
	alert(sErr);
}



//BBCodes Logic
showBBCodeHelpReference = function() {
    var helpLink = "<div id='bbcodehelpLink'><a href='javascript:showBBCodeHelp()'>BBCodes help</a></div>" +
    "<div id='popupBBCodes'></div>";
    $(helpLink).insertAfter('.bbcodeitem');
    $(".bbcodeitem").removeClass("bbcodeitem");

}
//popupBBCodes
showBBCodeHelp = function() {
    var oMod = showModalWithoutOverlay({ iW: 560, iH: 495 });
    $.post("/modals/bbcodehelp.aspx", function(c) {
        oMod.html(c);
    });
}
showModalWithoutOverlay = function(oDim) {
    sHtml = '<div style="height:' + oDim.iH + 'px"><img id="imgLoading" src="/images/hoverModloader.gif" alt="Loading" width="16" height="16" /></div>';

    // Set coordinates for msie instead
    var oPos = ($.browser.msie) ? [(($(window).width()) / 2) - (oDim.iW / 2), (($(window).height()) / 2) - (oDim.iH / 2)] : "center";

    // Hide any hovers
    $(".hoverMod2").hide();
    var oMc = $('<div id="modalcopy" style="width:' + (oDim.iW + 16) + ';height:' + oDim.iH + ';">' + sHtml + '</div>');
    d = $("<div style='width:" + oDim.iW + ";height:" + oDim.iH + ";'>").append(oMc);
    d.dialog({ close: function() { $(this).parents(".ebModal").remove(); }, show: "fadeIn", resizable: false, dialogClass: "ebModal", modal: false, position: oPos, width: oDim.iW, height: oDim.iH });

    if ($.browser.msie && (parseInt($.browser.version) < 7)) {
        d.parents(".ebModal").pngFix();
        d.parents(".ebModal").bgiframe({ left: -20, top: -20, width: oDim.iW + 40, height: oDim.iH + 40 });
    }
    return oMc;
}

/////////////////////////
// Book Hover Info
/////////////////////////
// On Hover event handler for hover modal
hoverOver = function(e, url, inbody, delay) {
    var oTarget = (e.currentTarget) ? $(e.currentTarget) : $(e.target);
    var iDelay = delay ? delay : 2000;
    if (!oTarget.attr("class").length) return;
    var _arrClasses = $.grep(oTarget.attr("class").split(" "), function(i) { return /^(book|group|user)-\d+$/.test(i) });
    if (_arrClasses.length <= 0) return;
    var _idSplit = (_arrClasses[0]).split("-");
    var sUrl;
    var existingPopup = $("#" + _arrClasses + ".hoverMod2")
    if (existingPopup.length > 0) {
        if (existingPopup[0].style.display != "none") {
            clearTimeout(hoverCloseTimer);
            return false;
        }
    }
    $(".hoverMod2").hide();
    oTarget.find(".coverLoading:first").show();
    if (url) {
        sUrl = url;
    }
    else {
        switch (_idSplit[0]) {
            case "book":
                sUrl = "/modals/bookoptions.aspx";
                break;
            case "group":
                sUrl = "/modals/groupoptions.aspx";
                break;
            case "user":
                sUrl = "/modals/memberoptions.aspx";
                break;
        }
    }

    hoverOpenTimer = setTimeout(function() {
        clearTimeout(hoverCloseTimer);
        var hoverTarget = oTarget.find(".hoverMod2");
        oTarget.find(".coverLoading").hide();

        if (!hoverTarget.length || hoverTarget.css("display") == "none") {
            var bBounce = $(".hoverMod2:visible").hide().parent().css("position", "").length;
            var bCached = hoverTarget.hide().length;
            var bArrow = 0;
            oTarget.css("position", "relative");

            var sPointer, iInvertedOffset;
            var de = document.documentElement;
            var b = document.body;

            if (!bCached) {
                hoverTarget = $('<div id="' + _arrClasses + '" class="hoverMod2"><div class="rightedge"></div><div class="leftedge"></div><div class="bottomegde"></div><div class="topedge"></div><div class="topleft"></div><div class="topright"></div><div class="bottomleft"></div><div class="bottomright"></div><div id="modalcopy"><div class="modalloading"><img id="imgLoading" src="/images/hoverModloader.gif" alt="Loading" width="16" height="16" /></div></div>');
                oTarget.append(hoverTarget);
            }

            var hoverOverflow = oTarget.offset().left - hoverTarget.width() + (oTarget.width() / 2) - 10;
            hoverTarget.css("right", ((hoverOverflow < 0) ? (oTarget.width() / 2) - 10 + hoverOverflow : (oTarget.width() / 2) - 10));

            if (oTarget.offset().top - oTarget.height() - (de.scrollTop || b.scrollTop) < 0) {	// Hover below if its exceeding viewport
                sPointer = '<div class="informationarrowtop" style="right:' + ((hoverOverflow < 0) ? -(hoverOverflow) : 0) + 'px"><img src="/images/modal-arrow-top.png" alt="" width="25" height="13" /></div>';
                if (!oTarget.find(".informationarrowtop").length) {
                    bArrow = 1;
                    oTarget.find(".informationarrow").remove();
                    hoverTarget.append(sPointer);
                }
                iInvertedOffset = 1;
            }
            else {
                sPointer = '<div class="informationarrow" style="right:' + ((hoverOverflow < 0) ? -(hoverOverflow) : 0) + 'px"><img src="/images/modal-arrow-base.png" alt="" width="25" height="13" /></div>';
                if (!oTarget.find(".informationarrow").length) {
                    bArrow = 1;
                    oTarget.find(".informationarrowtop").remove();
                    hoverTarget.append(sPointer);
                }
            }

            var tmpTop = (iInvertedOffset) ? oTarget.height() + 20 : -20 - (hoverTarget.height());
            if (bBounce > 0) {
                hoverTarget.css("top", tmpTop).show();
            }
            else {
                hoverTarget.css("top", (iInvertedOffset ? 200 : -200)).show().animate({ top: tmpTop }, 500, "easeOutBounce");
            }

            if (bArrow && $.browser.msie && (parseInt($.browser.version) < 7)) {
                hoverTarget.pngFix();
                hoverTarget.bgiframe({ left: -20, top: -20, width: 400, height: 132 });
            }

            if (!bCached) {
                $.ajaxSetup({ cache: false });
                $.get(sUrl, { id: _idSplit[1] },
					function(c) {
					    oTarget.find("#modalcopy").html(c);
					}
				);
            }
            else {
                if (_idSplit[0] == "book") hoverTarget.find(".moreoptionscontainer").hide();
            }
        }
    }, iDelay);

    e.stopPropagation();
    e.cancelBubble = true;
    return false;
}

// Off Hover event handler for hover modal
hoverOff=function(e)
{
	e.stopPropagation();
	e.cancelBubble=true;

	var currTarget=(e.currentTarget)?$(e.currentTarget):$(e.target);
	currTarget.find(".coverLoading").hide();
	clearTimeout(hoverOpenTimer);
	hoverCloseTimer=setTimeout(function()
	{
		$(currTarget).css("position","").find(".hoverMod2").hide();
	}, 2000);
	return false;
}

// Wrappers for backward compatibility, please use new function names
hoverOverBook=hoverOver;
hoverOverUser=hoverOver;
hoverOffBook=hoverOff;

showHoverModal=function(sHtml,oDim)
{
	var de = document.documentElement;
	var b = document.body;
	var checkX=oDim.iX-oDim.iW+(oDim.iOW/2)+25;
	var oPos=[((checkX>15)?checkX:15)-(de.scrollLeft||b.scrollLeft),(oDim.iY-oDim.iH-(de.scrollTop||b.scrollTop)-60)];
	var sPointer,iInvertedOffset;
	if(oPos[1]<15)
	{	// Hover below if its exceeding viewport
		oPos[1]+=oDim.iH+oDim.iOH+120;
		sPointer='<div class="informationarrowtop" style="right:'+((checkX<0)?-(checkX)+20:20)+'px"><img src="/images/modal-arrow-top.png" alt="" width="25" height="13" /></div>';
		iInvertedOffset=1;
	}
	else
	{
		sPointer='<div class="informationarrow" style="right:'+((checkX<0)?-(checkX)+20:20)+'px"><img src="/images/modal-arrow-base.png" alt="" width="25" height="13" /></div>';
	}	

	d=$("<div style='width:"+oDim.iW+";height:"+oDim.iH+";'>").html('<div id="modalcopy" style="width:'+(oDim.iW + 16)+';height:'+oDim.iH+';">'+sHtml+'</div>'+sPointer);
	d.dialog({close:function(){$(this).parents(".hoverMod").remove();},resizable:false, dialogClass: "hoverMod", position: oPos, width: oDim.iW, height: oDim.iH });

	var tmpTop=$(".hoverMod").offset().top+((iInvertedOffset)?(-30):30);

	$(".hoverMod").animate({ top: tmpTop },500,"easeOutBounce")
		.hover(
			function(e){
				e.stopPropagation();
				e.cancelBubble=true;
				clearTimeout(hoverCloseTimer);
				clearTimeout(hoverOpenTimer);
			},
			function(e){
				e.stopPropagation();
				e.cancelBubble=true;
				activeHoverModal="";
				$(".hoverMod").remove();
			}
		);

	if($.browser.msie && (parseInt($.browser.version)<7))
	{
		d.parents(".hoverMod").pngFix();
		d.parents(".hoverMod").bgiframe({left:-20,top:-20,width:oDim.iW+40,height:oDim.iH+40 });
		$(".ui-resizable-e,.ui-resizable-w").height(oDim.iH);
	}
}

// On Hover event handler for hover modal
hoverOverBody=function(e,url)
{
	var oTarget=(e.currentTarget)?$(e.currentTarget):$(e.target);
	if(!oTarget.attr("class").length) return;
	var _arrClasses=$.grep(oTarget.attr("class").split(" "),function(i){ return /^book-\d+$/.test(i) });
	if(_arrClasses.length<=0) return;
	
	var _parId=_arrClasses[0];
	var sUrl=(url)?url:"/modals/bookoptions.aspx";
	var bookid=(_parId.split("-"))[1];

	activeHoverModal=_parId;
	clearTimeout(hoverCloseTimer);
	hoverOpenTimer=setTimeout(function()
	{
		if(!$(".ui-draggable-dragging, #hov"+_parId).length && $("#book-"+bookid).length && activeHoverModal==_parId)
		{
			$.get(sUrl,{id:bookid}, 
				function(c)
				{
					$(".hoverMod,.hoverMod2").remove();
					if(!$(".ui-draggable-dragging").length && $("#book-"+bookid).length)
					{
						showHoverModal(c ,{iW:444, iH:92, iX: oTarget.offset().left ,iY: oTarget.offset().top, iOW: oTarget.width(), iOH: oTarget.height() });
					}
					activeHoverModal="";
				}
			);
		}
	}, 500);
	e.stopPropagation();
	e.cancelBubble=true;
	return false;
}

// Off Hover event handler for hover modal
hoverOffBody=function(e)
{
	e.stopPropagation();
	e.cancelBubble=true;

	if(this==e.currentTarget || this==e.target)
	{
		activeHoverModal="";
		hoverCloseTimer=setTimeout('$(".hoverMod").remove();',500);
	}
	return false;
}

showAddToBookshelf=function(id)
{
	var oMod=showModal({iW:544, iH:290});
	$.post("/modals/bookshelf.aspx",{id:id}, 
		function(c) { 
			oMod.html(c);
			$('.ebModal .controlbookitem').click(
				function(e)
				{
					if(!$(this).hasClass('addedtoshelf'))
					{
						var sid=this.id.split("-")[1];
						var isGroup=Number($(this).hasClass('groupitem'));
						if($(this).hasClass('addedItem'))
						{
							$("#check-"+sid).removeAttr("checked");
							var shelflabel=$(this).removeClass('addedItem').find("label");
							shelflabel.text(shelflabel.text().replace("Added to ",""));
							$.get("/ajax/removeBookFromShelf.aspx",{shelf: sid, book: id, group: isGroup});
						}
						else
						{
							$("#check-"+sid).attr("checked",1);
							$(this).addClass('addedItem').find("label").prepend("Added to ");
							addBookToShelf(sid,id,null,isGroup);
						}
					}
				}
			);
			if (iReadBooksShelf>0 && iReadBooksShelf==iActiveShelfId)
			{
				$("#f_alreadyRead").attr("checked",true);
			}
			// Ajax call for adding to Books I've read shelf
			$("#f_alreadyRead").change(
				function()
				{
					if(this.checked)
					{
						$.get("/ajax/addBookToShelf.aspx",{shelf: iReadBooksShelf, book: id, shelftype: "smart" });
					}
					else
					{
						$.get("/ajax/removeBookFromShelf.aspx",{shelf: iReadBooksShelf, book: id});
					}
				}
			);
		}
	);
}

function showBuyThisBook(id)
{
	var oMod=showModal({iW:404,iH:150});
	$.get("/modals/buythisbook.aspx",{b:id},function(c) { oMod.html(c); }); 
}

readThisBook=function(id,obj)
{
	if(checkLogin())
	{
		var iRead=(typeof iReadBooksShelf == "undefined")?0:iReadBooksShelf;
		$.post("/ajax/addBookToShelf.aspx",{shelf: iRead, book: id, shelftype: "smart" }, 
			function(r)
			{
				if(r==1)
				{
					$(obj).text("Marked as read");
				}
			}
		);
	}
}

// Ajax call for toggle add as friend
toggleFriend=function(uid,obj)
{
	if(checkLogin()&&!$(obj).hasClass("dontfriend"))
	{
    	var sUrl,sTxt,sCls;

		if($(obj).hasClass("delfriend"))
		{
			sUrl="/ajax/deleteFriend.aspx";
			sTxt="Add as friend";
			sCls="addfriend";
		}
		else
		{
			sUrl="/ajax/addFriend.aspx";
			sTxt="Unfriend";
			sCls="delfriend";
		}
		
		$.post(sUrl,{uid:uid},function(d)
			{
				if(d>0 && obj)
				{
					$(obj).removeClass("addfriend delfriend").addClass(sCls).find("span").text(sTxt);
				}	
			}
		);
	}
}

// Ajax call for toggle add as fan
toggleFan = function(uid, obj)
{
    if(checkLogin()&&!$(obj).hasClass("dontfan"))
    {
        var sUrl, sTxt, sCls;
        if ($(obj).hasClass("delfan"))
        {
            sUrl = "/ajax/deleteFan.aspx";
            sTxt = "Become a fan";
            sCls = "addfan";
        }
        else
        {
            sUrl = "/ajax/addFan.aspx";
            sTxt = "Unfan";
            sCls = "delfan";
        }

        $.post(sUrl, { uid: uid }, function(d)
            {
                if (d > 0 && obj)
                {
                    $(obj).removeClass("addfan delfan").addClass(sCls).find("span").text(sTxt);
                }
            }
		);
    }
}


// Ajax call for toggling adding of bookgroup
toggleGroup=function(id,obj)
{
    if(checkLogin()&&!$(obj).hasClass("mygroup"))
	{
	    var sUrl,sTxt,sCls;
	    if($(obj).hasClass("delgroup"))
	    {
	        $.post("/ajax/leaveBookGroup.aspx",{id:id},function(d)
		        {
			        if(d>0 && obj)
			        {
				        $(obj).removeClass().addClass("addgroup").find("span").text("Join Group");
			        }	
		        }
	        );	
	    }
	    else
	    {
            window.location.href="/group/join.aspx?g="+id;
	    }
	}
}

// Ajax call for adding book to List
addBookToList=function(listid,bookid,isGroup,callback)
{
	$.post("/ajax/addBookToList.aspx",{list: listid, book: bookid, shelftype: (isGroup?"group":"user") },callback);
}

// Ajax call for adding book to shelf
addBookToShelf=function(shelfid,bookid,fromid,type)
{
	$.post("/ajax/addBookToShelf.aspx",{shelf: shelfid, book: bookid, shelftype: type },
		function(r)
		{
			addBookToShelfCB(r,shelfid,fromid);
		}
	);
}

// dummy callback for pages that dont require callbacks
addBookToShelfCB=function(){}

showAddToReadlist=function(id)
{
	var oMod=showModal({iW:544, iH:290});
	$.post("/modals/readinglist.aspx",{id:id}, 
		function(c) { 
			oMod.html(c);
			$('.ebModal .controlbookitem').click(
				function(e)
				{
					var lid=this.id.split("-")[1];
					if(!$(this).hasClass('addedtoshelf'))
					{
						var isGroup=Number($(this).hasClass('groupitem'));
						if($(this).hasClass('addedItem'))
						{
							$("#check-"+lid).removeAttr("checked");
							var shelflabel=$(this).removeClass('addedItem').find("label");
							shelflabel.text(shelflabel.text().replace("Added to ",""));
							$.get("/ajax/removeBookFromList.aspx",{list: lid, book: id, group:isGroup});
						}
						else
						{
							$("#check-"+lid).attr("checked",1);
							$(this).addClass('addedItem').find("label").prepend("Added to ");
							addBookToList(lid,id,isGroup);
						}
					}
				}
			);
		}
	);
}

showAddTags=function(sType,iId)
{
	if(checkLogin())
	{
		var oMod=showModal({iW:313, iH:121});
		$.get("/modals/addtags.aspx", {ttype: sType, tid: iId},function(c){oMod.html(c);});
	}
}

// Change Currently Reading
function showCurrentlyReadingModal()
{
    var oMod=showModal({ iW: 613, iH: 475 });
    $.post("/modals/currentlyreading.aspx",{},
        function(c) {
        	oMod.html(c);
            runOnload();
        }
    );
}

// Login to the reader
function showLoginModal(showtext)
{
	var oParam=new Object();
	if (showtext == 1) oParam.l = 1;

	var oMod = showModal({ iW: 544, iH: 284 });

    $.get("/modals/login.aspx",oParam,
        function(c)
        {
            oMod.html(c);
            $("#f_username").focus();
        }
    );
}

// Friend Request Notification
function showFriendRequestModal(id)
{
    var oMod=showModal({ iW: 404, iH: 138 });
    $.post("/modals/friendrequest.aspx",{id:id},
        function(c) {
        	oMod.html(c);
        }
    );
}

// checks if user is logged in
function checkLogin(funct)
{
	if(getCookie("u")!="" && getCookie("cv")!="")
	{
		if($.isFunction(funct))
		{
			funct();
		}
		else
		{
			eval(funct);
		}
		return true;
	}
	else
	{
		showLoginModal();
		return false;
	}
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function cutTitle(sWord,iMax)
{
	if(sWord.length>iMax)
	{
		return sWord.substr(0,iMax)+"...";
	}
	return sWord;
}

function breakWord(sWord,iMax)
{
	if(!iMax)
	{
		iMax=5;
	}
	return $.map(sWord.split(" "),function(o){ return $.map(o.split(""), function(i,j){ return i+((j>iMax)?"<wbr>":"")}).join("") }).join(" ");
}

var editPermBit=2;
var delPermBit=4;

// generic flag content template
function flagContentTpl(id,type,bid,show,isAdmin)
{
	return '<div class="reportoptions"'+(show?" style='display:block'":"")+'><div class="reportoptiontext">Report this...</div>'+
		'<div class="reportoptionslist"><a href="javascript:void(0)" onclick="flagContent(this,\''+id+'\',\''+type+'\',\''+bid+'\',2);">Report as spam</a>'+
		'<a href="javascript:void(0)" onclick="flagContent(this,\''+id+'\',\''+type+'\',\''+bid+'\',1);">Report as inappropriate</a>'+
		(((isAdmin&editPermBit)==editPermBit)? ((type=="book")?'<a href="javascript:void(0)" onclick="excludeContent(\''+id+'\');">Exclude this</a>':'')+
		'<a href="javascript:void(0)" onclick="editContent(\''+id+'\',\''+type+'\');">Edit Content</a>':'')+
		(((isAdmin&delPermBit)==delPermBit && type !="user" && type !="group" && type !="book")?'<a href="javascript:void(0)" onclick="removeContent(\''+id+'\',\''+type+'\');">Remove Content</a>':'')+
		'</div></div>';
}

function writeFlagContent(id,type,bid,show,isAdmin)
{
	document.write(flagContentTpl(id,type,bid,show,isAdmin));
	$(".reportoptions:last").hover(function(){$(this).children('.reportoptionslist').show() },function(){ $(this).children('.reportoptionslist').hide() });
}

function editContent(id,type)
{
    if(!checkLogin()) return;
    if(id>=0)
    {
        // TODO: Fix this url hard codes
        switch(type)
        {
            case "book":
                window.location="/book/metadata-edit.aspx?b="+id
                break;

            case "discuss":
                window.location="/book/discussion-edit.aspx?d="+id
                break;
               
            case "discusspost":
                showDiscussionEditModal(id);
                break;

            case "chat":
                break;

            case "group":
                window.location="/group/preferences.aspx?g="+id
                break;
 
            case "list":
                window.location="/books/readinglist-edit.aspx?l="+id
                break;

            case "user":
                window.location="/home/profile.aspx?u="+id
                break;

            case "quote":
                window.location="/book/quotes-edit.aspx?q="+id
                break;
                
            case "review":
                window.location="/book/review-edit.aspx?r="+id
                break;

            case "reviewreply":
                window.location="/book/review-reply-edit.aspx?r="+id
                break;

            case "tag":
                alert("You cannot edit a tag");
                break;
        }
    }
}

function removeContent(id,type)
{
    if(!checkLogin()) return;
	$.post("/ajax/removeContent.aspx",{id: id, t: type},function(r)
	    {
	        if(r>0) window.location.reload();
	    }
	);
}

// ajax call to flag content
function flagContent(obj,id,type,bid,flag)
{
    if(!checkLogin()) return;
	$(obj).parents(".reportoptions").html('<div class="itemreported">Reported</div>');
	$.post("/ajax/flagContent.aspx",{f:flag, bid: bid, id: id, t: type});
}

function excludeContent(id,type)
{
    if(!checkLogin()) return;
    $.post("/ajax/excludeContent.aspx",{id: id},function(){$('.reportoptionslist').hide()});
}

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */


/* 
 * Live Chat
 */

function displayCountDown(startDate) {

    var inputDate = new Date(startDate);
    var utcDate = new Date();

    var utcMilliseconds = utcDate.getTime() + (utcDate.getTimezoneOffset() * 1000 * 60);
    var diff = utcMilliseconds - inputDate.getTime();
    diff = Math.floor(diff / (1000 * 60));
    
    if (diff >= 0) {
        return "<div class=\"datetime\"><strong>Chat has started</strong></div>";
    } else if (diff >= -300) {
        diff = diff * -1;
        var hours = Math.floor(diff / 60);
        var mins = diff - (hours * 60);
        if (hours == 0) {
            mins = (mins == 1) ? mins + " min" : mins + " mins";
            return "<div class=\"datetime\"><strong>Starts in " + mins + "</strong></div>";
        } else {
            hours = (hours == 1) ? hours + " hr" : hours + " hrs";
            mins = (mins == 1) ? mins + " min" : mins + " mins";
            return "<div class=\"datetime\"><strong>Starts in " + hours + ", " + mins + "</strong></div>";
        }
    }
    return "";
}

function displayRegisterForReminderOrChatNow(startDate, id) {

    var inputDate = new Date(startDate);
    var utcDate = new Date();
    var utcMilliseconds = utcDate.getTime() + (utcDate.getTimezoneOffset() * 1000 * 60);
    var diff = utcMilliseconds - inputDate.getTime();
    diff = Math.floor(diff / (1000 * 60));
    if (diff >= -60) {
        return "<a href=\"javascript:OpenRDR(" + id + ",0);\" class=\"arrowlink\">Join chat room</a>";
    } else {
        return "<a href=\"javascript:reminder('remind', " + id + ");\" class=\"arrowlink\">Register for a reminder</a>";
    }
    return "";
}

function openBookHref(obj)
{
    var par=$(obj).parents('a');
    $(".hoverMod2").hide();
    par.parent().mouseout();
    if(par.length)
    {
        window.location=par.attr('href');
    }
}

/* Launch the Tour Modal */
function tourPop(url) {
	var winH = 584;
	var winW = 980;
		if($.browser.msie) {
			var winH = 613;
		}
		if($.browser.safari) {
			var winH = 599;
		}
	window.open(url,"amigoTour",'height='+winH+',width='+winW+',status=yes,toolbar=no,menubar=no,location=no,scrolling=no');
}

function inputClearOnFocus(o)
{
    o=$(o);
    if($.trim(o.val())==o.attr("title"))
    {
        o.val("");
    }
}

function inputFillOnBlur(o)
{
    o=$(o);
    if($.trim(o.val())=="")
    {
        o.val(o.attr("title"));
    }
   }

// Rate of the book
function showRateBookModal(bookId) {

	$.post("/ajax/getbooknumstars.aspx", { book: bookId},
			function(num) {
			var oMod = showModal({ iW: 480, iH: 240 });
			$.get("/modals/rateBook.aspx", { book: bookId, stars: num },
				function(c) {
					oMod.html(c);
				}
			);
			}
		);
}


function showSendPrivateMessageModal(opts) {
    var oMod = showModal({ iW: 513, iH: 313 });
    $.post("/modals/sendprivatemesage.aspx?ts=" + new Date().getTime(), opts,
			function(c) {
    oMod.html(c);
    showBBCodeHelpReference();
			}
	);
}

function showRecaptchaModal(opts) {
    if (!IsAllowedMessageLength(opts.messageTextId, opts.allowedLength))
        return false;
    $('#SecurityCheckRequire').val('true');
    var oMod = showModal({ iW: 513, iH: 313 });
    $.post("/modals/checkrecaptcha.aspx?ts=" + new Date().getTime(), opts,
			function(c) {
			    oMod.html(c);
			}
	);
	return true;
}

function ClearValidationData() {
    var SecurityCheckRequire = $('#SecurityCheckRequire')
    var CheckRecaptchaValid = $('#CheckRecaptchaValid')

    if ((SecurityCheckRequire && SecurityCheckRequire.val() == 'true')
            && (CheckRecaptchaValid && CheckRecaptchaValid.val() == 'true')) {
        $('#SecurityCheckRequire').val('false')
        $('#CheckRecaptchaValid').val('false');
    }
}

function sendCheckrecaptcha(form) {
    var form = $("#frmCheckrecaptcha")[0];
    if (form && form.recaptcha_response_field) {
        if (form.recaptcha_response_field.value == '') {
            $(".formStatus").html("Sorry, you must enter the security check text.").slideDown();
            $(form.recaptcha_response_field).focus();
            return false;
        }
    }

    var data = {}
    data.action = 'submit';
    if (form.recaptcha_challenge_field) data.recaptcha_challenge_field = form.recaptcha_challenge_field.value;
    if (form.recaptcha_response_field) data.recaptcha_response_field = form.recaptcha_response_field.value;

    $.ajax({ type: 'POST', url: "/modals/checkrecaptcha.aspx?ts=" + new Date().getTime(), data: data, success: function(data, textStatus, httpObj) {
        if (data == 1) {
            $('#CheckRecaptchaValid').val('true');
            $('#checkrecaptcha').parents('.ebModal').find('.ui-dialog-titlebar-close').click();
            __doPostBack('UpdatePanel1', '');
        }
        else if (data.length > 0) {
            if ($.trim(data).indexOf("error:") == 0 && $.trim(data).length > 6) {
                showError(data.substring(6));
            } else {
                $('#checkrecaptcha').parents('.ebModal').find('.ui-dialog-titlebar-close').click();
            }
        }
    },
        error: function(data) { showError(data); }
    });
}



function sendPrivateMessage(form) {
    if (form.messagetext && $.trim(form.messagetext.value) == "") {
        showError("Sorry, you did not enter a valid message text");
        return false;
    }

    if (form.subject && $.trim(form.subject.value) == "") {
        showError("Sorry, you did not enter a valid Subject text");
        return false;
    }

    var errorText = "";
    var subjectAllowedLength = form.subjectAllowedLenth.value;
    var messageAllowedLength = form.messageAllowedLength.value;

    if (form.subject && $.trim(form.subject.value).length > subjectAllowedLength)
        errorText += " - Subject field can not have more than " + subjectAllowedLength + " characters"
                      + " (current Subject has " + $.trim(form.subject.value).length + " characters).\n";

    if (form.messagetext && $.trim(form.messagetext.value).length > messageAllowedLength)
        errorText += " - Message field can not have more than " + messageAllowedLength + " characters"
                   + " (current Message has " + $.trim(form.messagetext.value).length + " characters).\n";

    if (errorText != "") {
        errorText = "Sorry, there are some errors in message data : \n" + errorText;
        showError(errorText);
        return false;
    }

    if (form.recipients && $.trim(form.recipients.value) == "") {
        showError("Sorry, you did not specify any recipients");
        return false;
    }

    var form = $("#frmPrivateMessage")[0];
    if (form && form.recaptcha_response_field) {
        if (form.recaptcha_response_field.value == '') {
            $(".formStatus").html("Sorry, you must enter the security check text.").slideDown();
            $(form.recaptcha_response_field).focus();
            return false;
        }
    }

    var data = {}
    data.action = 'submit';
    if (form.messageid) data.messageid = form.messageid.value;
    if (form.messagetext) data.messagetext = form.messagetext.value;
    if (form.messagetype) data.messagetype = form.messagetype.value;
    if (form.subject) data.subject = form.subject.value;
    if (form.recipients) data.recipients = form.recipients.value;
    if (form.userid) data.userid = form.userid.value;
    if (form.groupid) data.groupid = form.groupid.value;
    if (form.recaptcha_challenge_field) data.recaptcha_challenge_field = form.recaptcha_challenge_field.value;
    if (form.recaptcha_response_field) data.recaptcha_response_field = form.recaptcha_response_field.value;

    $.ajax({ type: 'POST', url: "/modals/sendprivatemesage.aspx?ts=" + new Date().getTime(), data: data, success: function(data, textStatus, httpObj) {
        if (data == 1) {
            $('#sendprivatemesage').parents('.ebModal').find('.ui-dialog-titlebar-close').click();
        }
        else if (data.length > 0) {
            if ($.trim(data).indexOf("error:") == 0 && $.trim(data).length > 6) {
                showError(data.substring(6));
            } else {
                $("#sendprivatemesage .recaptchaarea").html(data).css('display', 'block');
            }
        }
    },
        error: function(data) { showError(data); }
    });

}

function IsAllowedMessageLength(messageTextId, allowedLength) {
    var messageText = $('#' + messageTextId).val();
    
    if (messageText.length > allowedLength) {
        var errorText = "Message can not have more than " + allowedLength + " characters (current Message has " + messageText.length + " characters)."
        showError(errorText);
        return false;
    }

    return true;
}

function UpdateUnreadCount(message) {
    var title = $("#myAmigoMessageTitle");
    if (title.length > 0)
        title.html(message)

    title = $("#homeauthorMessageTitle");
    if (title.length > 0)
        title.html(message)

    title = $("#homeMessageTitle");
    if (title.length > 0)
        title.html(message)

    title = $("#messages_subnav>a");
    if (title.length > 0)
        title.html(message)

}