// add style
var style="#lastposts{width:375px;padding-left:5px;padding-bottom:5px;background-color:#fee;font-size:13px;border:1px solid #ddd;}.choosepost{background-color:#fff;line-height:1.4em;display:block;width:372px;border-bottom:1px dashed #bbb;cursor:pointer;}.cl_type_icon{margin-right:3px;border:none;}.heart_tip{margin-left:5px;display:inline;}.finalbig{padding:3px;-moz-border-radius-topleft:8px;-khtml-border-top-left-radius:8px;-webkit-border-top-left-radius:8px;border-top-left-radius:8px;-moz-border-radius-topright:8px;-khtml-border-top-right-radius:8px;-webkit-border-top-right-radius:8px;border-top-right-radius:8px;-moz-border-radius-bottomleft:8px;-khtml-border-bottom-left-radius:8px;-webkit-border-bottom-left-radius:8px;border-bottom-left-radius:8px;-moz-border-radius-bottomright:8px;-khtml-border-bottom-right-radius:8px;-webkit-border-bottom-right-radius:8px;border-bottom-right-radius:8px;font-size:1em;}.finalbig img{margin:3px;}";
document.write('<style type="text/css">' + style + '</style>');
/* <![CDATA[ */
cl_settings = {
	name: "author",
	url: "js-CmtUrl",
	comment: "js-CmtText",
	email: "email",
	prepend: "",
	badge: "http://scripts.comluv.com/images/CL91x17-black2.gif",
	show_text: "CommentLuv Enabled",
	badge_text: "",
	heart_tip: "on",
	default_on: "checked",
	select_text: "choose a different post to show",
	cl_version: "jskit",
	images: "http://scripts.comluv.com/images/",
	api_url: "http://api.comluv.com/cl_api/commentluvapi.php"
}
/* ]]> */
jQuery.noConflict();

(function($) {
	$(document).ready(function(){
		if($('#js-CmtText-0').length > 0) {
			makeReady();
		} else {
			JSKitLib.addEventHandler(window, ['load'], function(){ makeReady(); });
		}
	});
	 
	
	//$(document).ready(function(){
	//	function try_again(){
	//		if($('#js-CmtText-0').length > 0){makeReady();}
	//		else{ console.log("waiting");
	//		setTimeout(try_again, 500);}
	//		}
	//		        }
	//		); 
	
	function makeReady(){
		// convert short codes to heart image
		do_hearts();
		// settings use added text field for url value
		cl_settings['url'] = "clurl";
		
		$("textarea[name='" + cl_settings['comment'] + "']").after('<input type="hidden" id="clurl" name="clurl"/>');	
		$("textarea[name='" + cl_settings['comment'] + "']").after('<br/><div id="commentluv"><input type="checkbox" style="width: 25px;" checked="" name="doluv" id="doluv"/><span style="clear: both;" id="mylastpost"><a target="_blank" href="http://comluv.com"><img border="0" title="CommentLuv Enabled" alt="CommentLuv Enabled" src="http://commentluv-jskit.googlecode.com/files/CL91x17-white2.gif"/></a></span><img style="display: none;" alt="show more" src="http://commentluv-jskit.googlecode.com/files/down-arrow.gif" id="showmore" class="clarrow"/></div><div id="lastposts" style="display: none;"></div>');
		$('#lastposts').hide();
		$('#showmore').hide();
		
		if($('.js-kit-from-field').length > 0){
			// is logged out. add url field
			$('.js-kit-from-menuAnonymousWrap').after('<div class="js-kit-from-menuAnonymousWrap" style="margin-top: 3px;"><div class="jskit-MenuRootHTML"><div class="jskit-GoogleLikeMenuBar" style="background-image: url(//js-kit.com/images/google-like-button.png); font-weight: bolder;">URL</div></div><div class="js-kit-from-name-ipe"><input type="text" id="clurlman" name="clurlman" tabindex="1"/></div></div>');
			cl_settings['url'] = "clurlman";
			$('#clurlman').empty();
		} else {
			// is logged in with some ID, check for url
			$('#clurl').val($('.js-kit-linksItem-icon:last').attr("title"));
			if($("input[name='" + cl_settings['url'] + "']").length > 0){
				var check=$("input[name='" + cl_settings['url'] + "']").val();
			} else {
				var check = '';
			}
			// ^^^ gets value of clurlman if logged out, uses clurl if logged in
			if(check.indexOf("http://") < 0 ) {
				$('#mylastpost').empty().append('<b>CommentLuv cannot see your url</b><br/>Please add it to the list above by clicking "Add another site" and click on "my site", (use http:// prefix) then uncheck/check the box again');
			}
		}
		
		$("#showmore").click(function(){
			// hide drop down box for click outside
			$(document.body).click(function(){
				$('#lastposts').hide();
			});
			$("#lastposts").slideDown(1000);
		});
				
		$("input[name='js-Cmtsubmit']").after('<input type="button" id="clsubmit" value="submit" onclick="addstuff();"/>');
		$("input[name='js-Cmtsubmit']").hide();
		$("#js-CmtText-0").focus(function(){dostuff();	});
		var x = readCookie('commentluvjs');
		if(x) {
			$("input[name='" + cl_settings['url'] + "']").val(x);
		}
		$('.js-singleCommentText a').click(function(){
			var url = $(this).attr("href");
			var addit= "?type=click&url=" + url + "&callback=?";
			var clurl=cl_settings['api_url'] + addit;
			// call api, don't worry about returned data
			$.getJSON(clurl);
			$(this).attr("target","_blank");
			return true;
		});
		// set the event listener for the click of the checkbox
		$('#doluv').click(function(){
			$('#lastposts').hide();
			if($(this).is(":checked")){
				// was unchecked, now is checked
				$('#mylastpost').fadeTo("fast",1);
				dostuff();
			} else {
				// was checked, user unchecked it so empty hidden fields in form
				cl_settings['cl_post'] = "" ;
				cl_settings['cl_type'] = "" ;
				cl_settings['request_id'] = "";
				cl_settings['choice_id'] = "" ;
				$('#mylastpost').fadeTo("slow",0.3);
			}
		});
		// set hover event for heart tip

		$('.heart_tip_box').hoverIntent({over:heart_big,out: do_nowt,interval : 50,timeout: 50});

		function heart_big(){
			$("body").append('<span id="heart_tip_big" style="position:absolute; z-index: 1000; background-color: pink; width: 62px;"><img src="' + cl_settings['images'] + 'loader.gif" alt="Loading" width="62" height="13" /></span>');
			// find where to put left edge of info box (in case at right hand side of screen
			//opera Netscape 6 Netscape 4x Mozilla
			if (window.innerWidth || window.innerHeight){
				docwidth = window.innerWidth;
				docheight = window.innerHeight;
			}
			//IE Mozilla
			if (document.body.clientWidth || document.body.clientHeight){
				docwidth = document.body.clientWidth;
				docheight = document.body.clientHeight;
			}

			var hasarea = docwidth - getAbsoluteLeft(this);
			if(hasarea > 350){
				var xpos = getAbsoluteLeft(this);
			} else {
				var xpos = getAbsoluteLeft(this) - 300;
			}
			if(xpos > (docwidth - 350)){
				xpos = xpos - 320;
			}
			var ypos = getAbsoluteTop(this);
			$('#heart_tip_big').css({'left':xpos + "px", 'top' :ypos + "px" });
			$('#heart_tip_big').hoverIntent({over:do_nowt,out: heart_small, interval : 50, timeout: 350});
			var link = $(this).prev("span a").attr("href");
			var url = cl_settings['api_url'] + "?type=info&url=" + link + '&callback=?';
			do_info(url);
		}
		function heart_small(){
			$("body").find("#heart_tip_big").remove();
		}
		function do_nowt(){
			return;
		}
	} // end makeready
	function getAbsoluteLeft(objectId) {
		// Get an object left position from the upper left viewport corner
		o = objectId;
		oLeft = o.offsetLeft            // Get left position from the parent object
		while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
			oParent = o.offsetParent    // Get parent object reference
			oLeft += oParent.offsetLeft // Add parent left position
			o = oParent
		}
		return oLeft
	}
	function getAbsoluteTop(objectId) {
		// Get an object top position from the upper left viewport corner
		o = objectId;
		oTop = o.offsetTop            // Get top position from the parent object
		while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
			oParent = o.offsetParent  // Get parent object reference
			oTop += oParent.offsetTop // Add parent top position
			o = oParent
		}
		return oTop
	}
	function do_info(url){
		$.getJSON(url,function(data){
			$('#heart_tip_big').css("width","350px");
			$('#heart_tip_big').addClass("finalbig");
			var title = data.items[0].title;
			$('#heart_tip_big img').remove();
			$('#heart_tip_big').html(title);
		});
	}
	function dostuff(){
		// get value from last link in list (nothing there if not logged on)
		// cl_settings is using clurl as url field name or clurlman if not logged on.
		$('#clurl').val($('.js-kit-linksItem-icon:last').attr("title"));
		if($('#doluv').is(":checked")){ //$('#mylastpost a').length > 0 &&
			if($("input[name='" + cl_settings['url'] + "']").length > 0){
				var check=$("input[name='" + cl_settings['url'] + "']").val();
			}
			// ^^^ gets value of clurlman if logged out, uses clurl if logged in
			if(check.indexOf("http://") < 0 ) {
				if($('.js-kit-from-field').length > 0){
					// user is logged out
					$('#mylastpost').empty().append('<b>CommentLuv cannot see your url, please add it in the field above if you want to see your last posts returned</b><br/>');
				} else {
					// user is logged in but no url found
					$('#mylastpost').empty().append('<b>CommentLuv cannot see your url</b><br/>Please add it to the list above by clicking "Add another site" and click on "my site", then uncheck/check the box again');
				}
				return
			}
			var xyz=check;
			var url=cl_settings['api_url'] + "?type=request&url="+check+"&version="+ cl_settings['cl_version'] +"&callback=?";
			$.getJSON(url,function(data){
				$('#showmore').show();
				$('#lastposts').empty();
				// get if is a member and other meta data
				var ismember = data.meta[0].ismember;
				cl_settings['request_id'] = data.meta[0].request_id;
				cl_settings['alert_message'] = data.meta[0].alert_message;
				// add the returned data to select box (or div)
				$('#lastposts').append(cl_settings['select_text'] + '<br/>');
				$.each(data.items, function(j,item){
					//get image type for this item
					var imageurl = '<img class="cl_type_icon" src="' + cl_settings['images'] + data.items[j]['type'] + '.gif"' + ' alt="' + data.items[j]['type'] + '" border=0 />';
					// construct vars for clchoose function
					var titlestr = data.items[j]['title'];
					// replace single and double quotes with backslash versions (to prevent the onclick=".. from getting split)
					titlestr = titlestr.replace(/\'/g,"\\\'");
					titlestr = titlestr.replace(/\"/g,"\\\'");
					$('#lastposts').append("<span onClick=\"clchoose('" + data.items[j]['type'] + "','" + data.items[j].url + "','" + titlestr + "'," + j + "," + data.meta[0].request_id + ");\"  class=\"choosepost\">" + imageurl + data.items[j]['title'] + "</span>");
				});
				cl_settings['typeimage'] = '<img class="cl_type_icon" src="' + cl_settings['images'] + data.items[0]['type'] + '.gif"' + ' alt="' + data.items[0]['type'] + '" border=0 />';
				$('#mylastpost').html(cl_settings['typeimage'] + ' <a href="' + data.items[0].url +'" title="' + data.items[0]['type'] + '"> ' + data.items[0]['title'] + '</a>').fadeIn(1000);
				cl_settings['choice_id'] = "0";
				cl_settings['cl_type'] = data.items[0]['type'];
				cl_settings['cl_post'] = '<a href="' + data.items[0].url + '">' + data.items[0]['title'] + '</a>';
				
			});
			$("input[name='" + cl_settings['url'] + "']").change(function(){
				$('#lastposts').empty();
				dostuff();
			});
			// disable focus event
			$("textarea[name='" + cl_settings['comment'] + "']").unbind();
		}
	}

})(jQuery);
// functions called with onclick (outside scope of above block)
function clchoose(ptype,purl,pstr,pid,preq){
(function($) {
	if(purl == "0"){
		return;
	}
	// set hidden fields in form to hold values for identifying this choice
	cl_settings['choice_id'] = pid;
	cl_settings['request_id'] = preq;
	cl_settings['cl_type'] = ptype;
	$('#mylastpost a').attr("href",purl).text(pstr);
	cl_settings['cl_post'] = '<a href="' + purl + '">' + pstr + '</a>';
	$('#mylastpost img').attr({src: cl_settings['images'] + ptype + '.gif',alt: ptype});
	if($('#luv').is(":checked")){
		cl_settings['cl_post'] = '<a href="' + purl + '">' + pstr + '</a>';
	}
})(jQuery);
}
function addstuff(){
(function($){
	try {
		var checkdef = cl_settings['cl_type'].length;
	}
	catch(e){
		$("input[name='js-Cmtsubmit']").click();
		return;
	}
	if(($('#mylastpost a').length > 0) && $('#doluv').is(":checked")){
		if($('#mylastpost a').attr('href') != 0 && $('#mylastpost a').attr('href').indexOf("commentluv.com/error")<0 && $("input[name='" + cl_settings['url'] + "']").val().indexOf("undefined")<0)
		$("textarea[name='js-CmtText']").val($("textarea[name='js-CmtText']").val() + "\n\nRecent " + cl_settings['cl_type'] + ":=- <a href=\"" + $('#mylastpost a').attr('href') + "\">" + $('#mylastpost a').text() + '</a>\n');
	}
	
	try {
		var author_url=$("input[name='" + cl_settings['url'] + "']").val();
		createCookie('commentluvjs',author_url,60);
		// confirm to comluv
		var url=cl_settings['api_url'] + "?type=approve&url="+ $('#mylastpost a').attr('href') +"&request_id="+cl_settings['request_id'] + "&post_id=" +cl_settings['choice_id']+ "&version="+ cl_settings['cl_version'] +"&callback=?";
		$.getJSON(url);
	}
	catch(e){
		$("input[name='js-Cmtsubmit']").click();
		return;
	}
	$("input[name='js-Cmtsubmit']").click();
})(jQuery);
}
//http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else { var expires = ""; }
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') {c = c.substring(1,c.length);}
		if (c.indexOf(nameEQ) == 0){ return c.substring(nameEQ.length,c.length);}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function do_hearts(){
(function($){
	$(".js-singleCommentText a").each(function(){
		var commentText = $(this).parents('.js-singleCommentText').html();
		if(commentText.indexOf(':=-') > 0) {
			// this appends to the a
			$(this).after('<span class="heart_tip_box"><img class="heart_tip" src="http://scripts.comluv.com/images/littleheart.gif"/></span>');
		}

	});
})(jQuery);
}
