

var clply_clipthis_loaded;

function clply_clip() {
    //functiuons
    var hostData = null;
    var clplyhost = 'clp.ly';	// set to clp.ly for production
       
    var doc = document;
    var body = doc.getElementsByTagName("body").item(0);
    
    if (!body) {
	setTimeout('clply_clip()',100);
        return;
    }
    var s, ok = false;
    //are we ready yet?
    //load jq if needed
    
    if(top.location.href != document.location.href) {
        return; //it's a frame up - bail
    }
    
    
    
    if (!doc.getElementById('clply-jq')) {
	
//document.write(unescape("%3Cscript src='http://clp.ly/jq.js' type='text/javascript' id='clply-jq'%3E%3C/script%3E"));


        s = doc.createElement('script');
        s.src = 'http://'+clplyhost+'/jq.js';
	s.language='javascript';
	s.type='text/javascript';
        s.id = 'clply-jq';
        body.appendChild(s);
        s = document.createElement('link'); 
        s.href = "http://"+clplyhost+"/sidebar/clipthis.css";
        s.rel = 'stylesheet';
        s.type = 'text/css';
        s.id = 'clplysbloadcss';
        body.appendChild(s);
    }
    try { 
        ok = (typeof clpQuery != 'undefined');
    } catch (e) {}

    if (!ok) {
        setTimeout('clply_clip()',200);
        return;
    }
   
    if (clply_clipthis_loaded) {
	return;
    }

    clply_clipthis_loaded = true;	//even if we fail mark us as done so we don't ddos ourselves by trying multiple times.
    var $ = clpQuery; //We like using $ for jquery
    $(document).ready(function() {
	if (!$('.ClipThisButton').length) {    //bail
	    return;
	}   
	//now we know we have a button
	var clkey;
	try { clkey = $('.ClipThisButton:first').attr('href').replace(/.*clipthis\//,""); } catch(e) { clkey='badkey';};
	var ref = document.location.href;
	$.getJSON("http://"+clplyhost+"/buildclp.php?key="+clkey+"&url="+encodeURIComponent(ref)+"&jsoncallback=?",function(data,textStatus) {
	    hostData = data;
	    var button = $(".ClipThisButton");
	    var trackback = $(".clply-msg-block");
	    
	    if (data.extras && data.show_trackbacks != 0) {
		//if we have a pre-define trackback div use it else add one after the button
		if (trackback.length == 1) {
		    $(trackback).html(data.extras);
		} else if (button.length == 1) { //show trackbacks if needed.
		    $(button).wrap('<div class="clply-button"></div>');
		    $(button).after('<div class="clply-msg-block">'+data.extras+'</div>');               
		}
	    }
	});
	$("a.ClipThisButton").click(function() {
	    var d = document, l = d.location, ec = encodeURIComponent, s = encodeSelection();     
	    var u = 'http://'+clplyhost+'/create?url=' + ec(l.href) + '&text=' + s;
	    if (s.length) u = u+"#quote";
	    this.href = u;
	    this.target = "_blank";
	    return true; 
      
	});
	
	$('body').bind('copy',function(evt) {
	    if (hostData == null || hostData.limit ==0) return;	//bail if tagging is not enabled #todo still log the quote
	    var s = encodeSelection();
	    if (s.length == 0) return;	//don't fire on zero length clips
	    var u = getQuoteFrameURL(s);
	    if (hostData.limit < 2)  {
		//no popup - we call the quote frame to log the quote but don't display it
		$.get(u);
		return;				//bail if popup is not enabled
	    }
	    
	    
	    $('body').append('<div id="clply-quote-popup"><div id="clply-dialog">'+
			      '<div class="clply-hdr"><a href="#" class="clply-close"><img height="24" width="24" src="http://'+clplyhost+'/clply/closeround.png" alt="close"></a></div>'+
			      '<iframe border="0" scrolling="no" frameborder="0" width="220" height="200" src="'+u+'" />'+
			      '</div></div>'); 
				
	    
	    dialog_position(evt);
    
	    //transition effect  
	    $('#clply-dialog').fadeIn(400);
	    
	    $('.clply-close, body').click(function (e) {  
	    //Cancel the link behavior
		if ($('#clply-quote-popup').length > 0) {
		    e.preventDefault();  
		    $('#clply-quote-popup').remove();
		    $("#clply-tag").remove();
		}
		return true;
	    });       
	      
	    
	})
	
       
	$(window).resize(function() { dialog_position() });
	    
	
	function dialog_position(evt) {
	    //Get the window height and width
	    var id= '#clply-dialog';
	    var winH = $(window).height();  
	    var winW = $(window).width();  
		    
	    //Set the popup window to center  
	    $(id).css('left',winW/2-$(id).width()/2).css('top', winH/2-$(id).height()/2);
	    
	}
	function encodeSelection() {
	    var d = document,
	    w = window,
	    e = w.getSelection,
	    k = d.getSelection,
	    x = d.selection,
	    s = (e ? e() : (k) ? k() : (x ? x.createRange().text: 0)) +"";  //force to string
	    if (s.length > 2000)  {
		s = s.substring(0,1999);
	    }
	    var c = wordCount(s);
	    s = encodeURIComponent(s.replace(/\s*$/,""));
	    

	    
	    if (c < 20) {
		return s;			//don't tag if it's short - it's annoying
	    }
	    //now we tag the selection
	    var tagCode = "<p id='clply-tag' style='font-size: smaller; '>Source: <a href='"+
				 hostData.shorturl+"'>"+hostData.shortname+"</a> (<a href='"+hostData.shorturl+"'>"+hostData.shorturl+"</a>)</p>";
	    //firefox and webkit browsers - we don't handle 4.0 browsers
	    if (e) {
		var v  = e();
		var focusNode = v.focusNode,focusOffset = v.focusOffset, anchorNode= v.anchorNode, anchorOffset = v.anchorOffset;
		
		var selFrag = v.getRangeAt(0).cloneContents();
		
		$('body').append("<div id='clply-selection' style='text-align: left; font-size: 12px; color: black; position:fixed;top:0;left:-5000px;width:2000px;display: block;'></div>");
		var selDiv = $('#clply-selection');
		$('#clply-selection').append(selFrag);
		$('#clply-selection').append(tagCode);
		var r = document.createRange();
		r.selectNodeContents(selDiv[0]);
		if (v.setBaseAndExtent) {
		    v.setBaseAndExtent(r.startContainer,r.startOffset,r.endContainer,r.endOffset);
		} else {
		    v.removeAllRanges();
		    v.addRange(r);
		}
		//put the selection back
		setTimeout(function() {
		    if (v.setBaseAndExtent) {
			v.setBaseAndExtent(anchorNode,anchorOffset,focusNode,focusOffset);
		    } else {
			r.setStart(anchorNode,anchorOffset);
			r.setEnd(focusNode,focusOffset);
			v.removeAllRanges();
			v.addRange(r);
		    }
		    $('#clply-selection').remove();	//get get rid of our selection object;
		},1);	//fires 1ms after the copy is complete and restores the original selection
	    } else if (x && x.type=='Text') {
		var origSel = x.createRange();
		var selFrag = origSel.htmlText + tagCode;
		$('body').append("<div id='clply-selection' style='text-align: left; font-size: 12px; color: black; position:fixed;top:0;left:-5000px;width:2000px;display: block;'></div>");
		var selDiv = $('#clply-selection');
		$('#clply-selection').append(selFrag);
		
		var newSel = document.body.createTextRange();
		newSel.moveToElementText(selDiv[0]);
		newSel.select();
		setTimeout(function() {
		    origSel.select();
		    $('#clply-selection').remove();	//get get rid of our selection object;
		},1);	//fires 1ms after the copy is complete and restores the original selection
		
		
		
	    }
	    return (s);
	}
	function getRangeObject(selectionObject) {
	    if (selectionObject.getRangeAt)
		    return selectionObject.getRangeAt(0);
	    else { // Safari!
		    var range = document.createRange();
		    range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
		    range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
		    return range;
	    }
	}
    
	function getQuoteFrameURL(s) {
	    var w=window, d = document, l = d.location, ec = encodeURIComponent, pq;
	    
	    var u = 'http://'+clplyhost+'/frame_create?url=' + ec(l.href) + '&text=' + s;
	    return u;
	}
	
	function wordCount(s) {
	    var m = s.match(/[^\s]+/g);
	    return m.length;
	}
    });
               
}   

clply_clip();
