/**
 * Repost.us publisher side code
 * Copright 2011 Free Range Content Inc.
 * Author John Pettitt
 */

/**
 * Todo
 * Make this find all the curate/repost buttons on a page, collect up the url= params and send them withe the hostinfo request so we can get them into the system
 */
(function(window,document,undefined) {
    var jQuery, //Local jQuery
	ec = encodeURIComponent,
	repostUsEnable = false,
	curateUsEnable = false,
	curateUsQuoteEnable = false,
	repostUsCopyEnable = false,
	hostInfo = null,
	myHost = null,
	apikey = null,
	pageURLs = [],
	debugMode = false,
	hash = document.location.hash,
	sliderTimeout = null,
	myURL = null,
	wpPlugin='wpPlugVer=';
    
    if(top.location.href != document.location.href) {
	    return; //it's a frame up - bail
    }
    
    if(window.repostUs === true) {
	return;
    }
    window.repostUs = true;
    
    if (hash && hash.match(/^#rpudebug=/)) {
	debugMode = true;
    }
    
    //Find Jquery, hopefully we already have it (everybody should use Jquery :-)
    //We need 1.4.3 or higher
    if (window.jQuery === undefined || !/1\.(4\.3|5|6)/.test(window.jQuery.fn.jquery)) {
	if (document.location.protocol == 'https:') {
	    require("https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js", jqLoadDone); //Thanks Google!)
	} else {
	    require("http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js", jqLoadDone); //Thanks Google!)
	}
    } else {
	    jQuery = window.jQuery;
	    //Woot! we already have the right jQuery
	    repostUs(); //go 4 it
    }
    
    function deblog(msg) {
	try { 
            console.log(msg);
        } catch(e) {        
            // newer opera browsers support posting erros to their consoles
            try { 
                opera.postError(msg); 
            } catch(e) { }
        }
    }

    //Load complete handler for jq - restores users jQ and $ and hides ours
    function jqLoadDone() {
	    if (jQuery === undefined) {	//for some reason IE9 is calling this twice so we protect it
		    jQuery = window.jQuery.noConflict(true);
		    repostUs(); //go 4 it
	    } 
    }
    
    //Loader for JS files we need
    function require(jsfile, callback) {
	    var script_tag = document.createElement('script');
	    script_tag.setAttribute("type", "text/javascript");
	    script_tag.setAttribute("src", jsfile);
	    if (typeof callback == 'function') {
		    script_tag.onload = callback;
		    script_tag.onreadystatechange = function() { // IE
			    if (this.readyState == 'complete' || this.readyState == 'loaded') {
				    callback();
			    }
		    };
	    }
	    document.documentElement.appendChild(script_tag); 
    };
    
    
    function repostUs() {
	//Everything afteR this is in the jQuery ready() Closure
	jQuery(document).ready(function($) {
	    
	    //Catch the copy function
	    function bindCopy() {
		$('body').bind('copy',function(evt) {
		    
		    var s = userSelection(),
			wc = wordCount(s),
			sliderContent = null;
			
			
		    
		    if (!hostInfo || hostInfo.nopopup === true) return;
		    
		    $('#rpuIframe').remove();
		    $('body').unbind('click',closeSlider);
		
		    //Set the slider content
		    if (wc > 12 && ((wc < 80 && curateUsQuoteEnable) || !repostUsCopyEnable)) {
			//stuff to encode quote goes here
			sliderContent = '<div class="popdown-slider curate-us">'+
			    '<div><a href="http://repost.us" id="logo"></a></div>'+
			    '<div><a id="close" href=""><br><span id="close-text">Close</span></a></div>'+
			    '<div class="main"><div id="what"><a href="javascript:void();">What&rsquo;s this?</a></div>'+
			    '<div id="text"><a class="button button_cu" target="_blank" href="'+hostInfo.curateUs+'/create?frag=quote&url='+ec(document.location.href)+'&text='+ec(s)+'#quote">Share your copied text</a> as an elegant, formatted quote.</div>'+
			    '</div><div id="bottom"></div>'+
			    '<div id="what_this"><p><a href="http://Curate.Us" target="_blank">Curate.Us</a> lets you easily make formatted quotes of the text you selected. '+
			    'You can take those quotes and embed them almost anywhere, simply click "Share your copied text" to customize and embed your quote.<p>'+
			    '<p id="disable">Don&rsquo;t show me this next time I copy text <input type="checkbox" id="nopopup"></p><div id="closeWhat"></div></div>'+
			    '</div>';
		    }
		    //Override that if repostUs is enabled
		    if(wc >= 80 && repostUsCopyEnable) {
			sliderContent = '<div class="popdown-slider repost-us">'+
			    '<div><a href="http://repost.us" id="logo"></a></div>'+
			    '<div><a id="close" href=""><br><span id="close-text">Close</span></a></div>'+
			    '<div class="main"><div id="what"><a href="">What&rsquo;s this?</a></div>'+
			    '<div id="text">'+
			    '<a class="button button_rpu" target="_blank" href="'+hostInfo.repostUs+'/syndicate/create?url='+ec(document.location.href)+'">&lt;Embed&gt; this Article</a>';
			if (curateUsQuoteEnable) {
			    sliderContent = sliderContent + '&nbsp;&nbsp;or&nbsp;&nbsp;<a class="button button_cu" target="_blank" href="'+hostInfo.curateUs+'/create?frag=quote&url='+ec(document.location.href)+'&text='+ec(s)+'#quote">Share your Copied Text</a>';
			}
			sliderContent = sliderContent +
			    
			    '</div>'+
			    '</div><div id="bottom"></div>'+
			    '<div id="what_this"><p>This article can be syndicated on your web site using <a href="http://Repost.Us/" target="_blank">Repost.Us</a>. '+
			    'Simply click the "&lt;Embed&gt; this Article" button to get the embed code.<p>'+
			    '<p id="disable">Don&rsquo;t show me this next time I copy text <input type="checkbox" id="nopopup"></p><div id="closeWhat"></div></div>'+
			    '</div>';
		    }
		    if (sliderContent) {
			$('body').bind('click',closeSlider);
			$('body').prepend('<iframe id="rpuIframe" allowtransparency="true" scrolling="no" width="100%"  frameborder="0" style="height:100px;z-index:9999999;background:transparent;position:fixed;top:-100px;left:0px;padding:0;margin:0;">');
			//tinmeout to let dom settle (firefox)
			setTimeout( function() {
			    openSlider(sliderContent);   
			},1);
			sliderTimeout = setTimeout(closeSlider,20000);
		    }
		    //Add attribution if appropriate
		    if (!hostInfo.noattrib && wc > 10 && (curateUsQuoteEnable || repostUsCopyEnable)) {
			tagSelection();
		    }
		    //Log that that somebody copied this text.
		    if (curateUsEnable && hostInfo.pageHash) {
			var u = myHost+'/repost/createQuote.php?XDEBUG_SESSION_START=1';
			$.ajax({
			    type: 'GET',
			    url: u,
			    data: { 'quote': s,'p': hostInfo.pageHash},
			    dataType: 'jsonp'
			});
		    }
		});
		
		
	    }
	    
	    function openSlider(sliderContent) {
		$('#rpuIframe').contents().find('head').append('<link rel="stylesheet" type="text/css" media="screen" href="'+myHost+'/rjs/popdown-slider/popdown-slider.css" />');
			    $('#rpuIframe').contents().find('body').html(sliderContent);
			    $('#rpuIframe').animate({top:'0px'},400);
			    $('#rpuIframe').contents().find('#close').click(function(e) {
				closeSlider();
				e.preventDefault();
				return false;
			    });
			    $('#rpuIframe').contents().find('.button_rpu').click(function(e) {
				if (!hostInfo.onPageOK) {
				    closeSlider();
				    return true;
				}
				var url = $('a.rpuRepostUsButton,a.rpuRepostButton').attr('href'), origurl = url;
				url = url.replace(/.*\/syndicate\/create\??/,hostInfo.repostUs+"/syndicate/do_create?");
				if (!url.match(/url=/)) {
				    url = url+"url="+ec(document.location.href);
				}
				clearTimeout(sliderTimeout);
				$.getJSON(url+"&jsoncallback=?",function(res,textStatus) {
				    if (res.status == 'success') {
				    //timeout to let dom settle (firefox)
				        setTimeout( function() {
				            openSlider(sliderContent);
				            showEmbed(res.data);
				        },1);
				    } 
				}).error(function() {
				    deblog('json failed, jumping to web instead');
				    document.location.href = origurl;
				});
				e.preventDefault();
				return false;
			    })
			    $('#rpuIframe').contents().find('.button_cu').click(function(e) {
				closeSlider();
				return true;
			    })
			    $('#rpuIframe').contents().find('#what').click(function(e) {
				e.preventDefault();
				$('#rpuIframe').css('height','100%');
				$('#rpuIframe').contents().find('#what_this').fadeIn(250);
				return false;
			    });
			    $('#rpuIframe').contents().find('#nopopup').click(function(e) {
				deblog('Disable popups');
				e.preventDefault();
				$('#rpuIframe').contents().find("#disable").html('Disabled').css('color','red');
				setCookie('rpuNoPopup','true',365);
				hostInfo.nopopup = true;
				setTimeout(closeSlider,1000);
				return false;
			    });
	    }
	    
	    function closeSlider() {
		deblog('Slider close');
		$('#rpuIframe').attr('height',100).stop(true).animate({top:'-100px'},300,'swing',function() {
		    $('#rpuIframe').remove();
		    deblog('Kill frame');
		});
		$('body').unbind('click',closeSlider);
	    }
	    
	    function showEmbed(sinfo) {
		var sliderContent, lstring, embed;
		deblog('Show embed code');
		for(var i =0; i < sinfo.licenses.length; i++) {
		    sinfo.licenses[i] = '<a target="_blank" href="'+sinfo.licenses[i]+'">link</a>';
		}
		embed = "&lt;script src=&quot;http://static.1.rp-api.com/rjs/repost-article.js?1&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;\n"+
		    "&lt;div class=&#039;rpuArticle rpuJump-4 rpuRepost-"+sinfo.syndication_hash+"-top&#039; style=&#039;margin:0;padding:0;&#039;&gt;\n"+
		    "    &lt;a href=&#039;"+hostInfo.shorturl+"&#039;&gt;\n"+
		    "        &lt;img style=&#039;border:none;background:none;&#039; src=&#039;http://i.curate.us/img/"+hostInfo.pageHash+"?&#039; /&gt;\n"+
		    "    &lt;/a&gt;\n"+
		    "&lt;/div&gt;\n"+
		    "&lt;!-- put the 'tease' , 'jump' or 'more' break here --&gt;"+
		    "&lt;!--more--&gt;&lt;!--break--&gt;\n"+
		    "&lt;div class='rpuArticle rpuRepostMain rpuRepost-"+sinfo.syndication_hash+"-bottom'&gt;&lt;/div&gt;\n"+
		    "<!-- How to customize this embed: http://www.repost.us/customizing-repost-us-embeds/ -->\n";
		lstring = "By using this embed code you agree to the following terms: "+sinfo.licenses.join(', ');
		sliderContent = //'<div class="popdown-slider repost-us">'+
			    //'<div><a href="http://repost.us" id="small_logo"></a></div>'+
			    //'<div><a id="close" href=""><br><span id="close-text">Close</span></a></div>'+
			    '<div id="model_desc" class="center6"><div class="model_desc_text">Repost this entire article with the embed code below.</div></div>'+
			    '<div id="embedcode" class="center6"><strong>&lt;Embed&gt; Code:</strong><textarea wrap="off">'+embed+'</textarea>'+
			    '<div class="embed_help">Copy and paste this embed code into your blog or website.<br />'+
			    'The article will be automatically reformatted and re-sized to match your site.'+
			    '</div></div>'+
			    '<div id="licenses" class="center6">'+lstring+'</div>';
			    //'<div id="bottom"></div>'+
			    //'<div id="what_this"><p>This article can be republished (embedded) on your web site using <a href="http://Repost.Us/" target="_blank">Repost.Us</a>. '+
			    '//Simply click the "instant republishing" button to get the embed code.<p>'+
			    //'<p id="disable">Don&rsquo;t show me this next time I copy text <input type="checkbox" id="nopopup"></p><div id="closeWhat"></div></div>'+
			    //'</div>';
		
		//openSlider(sliderContent);
		$('#rpuIframe').contents().find('.main').html(sliderContent);
		$('#rpuIframe').contents().find('#logo').attr('id','small_logo');
		
		$('#rpuIframe').contents().find('textarea').mouseenter(function() {
		    $(this).select();
		}).mousemove(function(e) {
		    $(this).select();
		});
		$('#rpuIframe').contents().find('textarea').select();
		$('#rpuIframe').css({height:'395px'});
		$('#rpuIframe').contents().find(".popdown-slider").animate({height:'375px'},400);

	    }
	    
	    
	    // Figure out where we came from
	    function findHost() {
		var src = $('script[src*="rjs/repostus.js"]').attr('src');
		     
		if (src === undefined) {
		    src = 'http://1.rp-api.com/';
		}
		src = src.replace(/static\.(.*)/,"$1");
		if (hash && hash.match(/^#myhost=/)) {
			return hash.replace(/#myhost=/,'');
		}
		
		if (src.match(/^https?:\/\//)) {
			return src.replace(/(https?:\/\/[^\/]+).*/,"$1");
		} else {
			return window.location.href.replace(/(http:\/\/[^\/]+).*/,"$1");
		}
	    }
	    
	    //how many words did they copy
	    function wordCount(s) {
		var m = s.match(/[^\s]+/g);
		if (m) {
		    return m.length;
		} else {
		    return 0;
		}
	    }
	    
	    function userSelection() {
		//Assign to vars so closure complier can make them small
		var windowSelection = window.getSelection,
		documentGetSelection = document.getSelection,
		documentSelection = document.selection;
		return selection = (windowSelection ? windowSelection() :
		    (documentGetSelection) ? documentGetSelection() :
		    (documentSelection ? documentSelection.createRange().text: 0)) +"";  //force to string
	    }
	    
	    function tagSelection() {
		var windowSelection = window.getSelection,
		documentGetSelection = document.getSelection,
		documentSelection = document.selection;
		//now we tag the selection withe an attribtion
		var tagCode = "<p id='clply-tag' style='font-size: smaller; '>Source: <a href='"+
				     hostInfo.shorturl+"'>"+hostInfo.shortname+"</a> (<a href='"+hostInfo.shorturl+"'>"+hostInfo.shorturl+"</a>)</p>";
		//firefox and webkit browsers - we don't handle 4.0 browsers
		if (windowSelection) {
		    var v  = windowSelection(),
			focusNode = v.focusNode,focusOffset = v.focusOffset, anchorNode= v.anchorNode, anchorOffset = v.anchorOffset,
			selFrag = v.getRangeAt(0).cloneContents(),
			selDiv, sRange;
		    
		    $('body').append("<div id='rpuCopySelection' style='text-align: left; font-size: 12px; color: black; position:fixed;top:0;left:-5000px;width:2000px;display: block;'></div>");
		    selDiv = $('#rpuCopySelection');
		    $('#rpuCopySelection').append(selFrag);
		    $('#rpuCopySelection').append(tagCode);
		    sRange = document.createRange();
		    sRange.selectNodeContents(selDiv[0]);
		    if (v.setBaseAndExtent) {
			v.setBaseAndExtent(sRange.startContainer,sRange.startOffset,sRange.endContainer,sRange.endOffset);
		    } else {
			v.removeAllRanges();
			v.addRange(sRange);
		    }
		    //put the selection back
		    setTimeout(function() {
			if (v.setBaseAndExtent) {
			    v.setBaseAndExtent(anchorNode,anchorOffset,focusNode,focusOffset);
			} else {
			    sRange.setStart(anchorNode,anchorOffset);
			    sRange.setEnd(focusNode,focusOffset);
			    v.removeAllRanges();
			    v.addRange(sRange);
			}
			$('#rpuCopySelection').remove();	//get get rid of our selection object;
		    },1);	//fires 1ms after the copy is complete and restores the original selection
		} else if (documentSelection && documentSelection.type=='Text') {
		    var origSel = documentSelection.createRange(),
			selFrag = origSel.htmlText + tagCode,
			selDiv, newSel;
		    $('body').append("<div id='rpuCopySelection' style='text-align: left; font-size: 12px; color: black; position:fixed;top:0;left:-5000px;width:2000px;display: block;'></div>");
		    selDiv = $('#rpuCopySelection');
		    $('#rpuCopySelection').append(selFrag);
		    newSel = document.body.createTextRange();
		    newSel.moveToElementText(selDiv[0]);
		    newSel.select();
		    setTimeout(function() {
			origSel.select();
			$('#rpuCopySelection').remove();	//get get rid of our selection object;
		    },1);	//fires 1ms after the copy is complete and restores the original selection
		}
	    }
	    function getSyndicationInfo(callback,params) {
		var q = "";
		if (params !== undefined && params.length) {
		    q = params.join('&') +"&";
		}
		$.getJSON(myHost+"/repost/hostinfo.php?"+q+"jsoncallback=?",function(data,textStatus) {
		    (callback)(data);
		});
	    }
	    
	    function setCookie(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+"="+escape(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 unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	    }
	    
	    //enable buttons
	    function doButtons() {
		var targetCount = 0,
		    repostTargets = [];
		    
		if(repostUsEnable) {
		    $('a.rpuRepostUsButton,a.rpuRepostButton').each(function() {
			var target = $(this).attr('href');
			if (repostTargets[target] == undefined) {
			    repostTargets[target]=1;
			    targetCount++;
			}
		    });
		    
		    $('a.rpuRepostUsButton,a.rpuRepostButton').show().attr('_target','blank');
		}
		if(curateUsEnable) {
		    $('a.ClipThisButton,a.cuCurateUsButton').show().attr('_target','blank');
		}
		
		//If we're quote trapping or reposting with only one article on the page
		if(targetCount == 1  && $('.rpuArticle').size() == 0) {
		    repostUsCopyEnable = true;
		}
		
		if (curateUsQuoteEnable || repostUsCopyEnable) {
		    bindCopy();	//Only do copy intercept when there is one article on the page
		}
		//If we're enabled for on-page embed then attach to button click and do that
		if (hostInfo.onPageOK) {
		    $('a.rpuRepostUsButton,a.rpuRepostButton').click(function(e) {
			var sliderContent = '<div class="popdown-slider repost-us">'+
			    '<div><a href="http://repost.us" id="logo"></a></div>'+
			    '<div><a id="close" href=""><br><span id="close-text">Close</span></a></div>'+
			    '<div class="main">'+
			    '</div><div id="bottom"></div>',
			    url = $(this).attr('href'),
			    origurl = url;
			
			url = url.replace(/.*\/syndicate\/create\??/,hostInfo.repostUs+"/syndicate/do_create?");
			if (!url.match(/url=/)) {
			    url = url+"url="+ec(document.location.href);
			}
			e.preventDefault();
			$('body').bind('click',closeSlider);
			$('body').prepend('<iframe id="rpuIframe" allowtransparency="true" scrolling="no" width="100%"  frameborder="0" style="height:100px;z-index:9999999;background:transparent;position:fixed;top:-100px;left:0px;padding:0;margin:0;">');
			$.getJSON(url+"&jsoncallback=?",function(res,textStatus) {
			    if (res.status == 'success') {
				//timeout to let dom settle (firefox)
				setTimeout( function() {
				    openSlider(sliderContent);
				    showEmbed(res.data);
				},1);
			    } else {
				document.location.href = origurl;
			    }
			}).error(function() {
			    deblog('json failed, jumping to web instead');
			    document.location.href= origurl;	//if it didn't work just do the button thing.
			})
			return false;
			
		    })
		}
	    }
	    
	    //Meat start here
	    //Basic setup stuff
	    //If we have reposted articles on the page and we don't have the repost-article.js script add it
	    myHost = findHost() ; 
	    if($('.rpuArticle').size() != 0 && $('[src*="rjs/repost-article.js"]').size() == 0) {
		require(myHost+"/rjs/repost-article.js",function() { return; });
	    }
	    //Now see if we should even be here
	    if($('a.ClipThisButton,a.cuCurateUsButton,a.rpuRepostButton,a.rpuRepostUsButton').length == 0) {
		return;			//no buttons so bail
	    }
	    
	    
	    apikey= "apikey="+$('meta[name=RepostUsAPIKey]').attr('content');
	    
	    if (apikey == 'apikey=undefined') {
		var k = $('a.ClipThisButton').attr('href');
		if (k !== undefined) {
		    apikey = "apikey="+k.replace(/.*\/simple\/clipthis\/([^\/\?]*).*/,"$1");
		}
	    }
	    

	    $('a.ClipThisButton,a.cuCurateUsButton,a.rpuRepostButton,a.rpuRepostUsButton').each(function() {
		var href = $(this).attr('href');
		if (href.match(/\?.*url=.+/)) {
		    pageURLs.push(ec(href.replace(/.*\?.*url=([^&]*).*/,"$1")));
		}
	    });
	    
	    if (pageURLs.length ==1 ) {
		myURL = "url="+pageURLs.pop();
	    }
	    
	    if($('meta[name="rpuPlugin"]').size() > 0) {
		wpPlugin = "wpPlugVer="+$('meta[name="rpuPlugin"]').attr('content');
	    }
	    
	    
	    getSyndicationInfo(function(data) {
		if (data.status == 'LIVE' || data.status == 'BETA' || (data.status=='TESTING' && document.location.hash.match(/^#rputest/))) {
		    repostUsEnable = true;
		} else {
		    $('a.rpuRepostUsButton,a.rpuRepostButton').hide();
		}
		if (data.limit_mode > 0) {
		    if (data.limit_mode ==2) curateUsQuoteEnable = true;
		    curateUsEnable = true;
		} else {
		    $('.ClipThisButton,.cuCurateButton').hide();
		}
		hostInfo = data;
		/*if (readCookie('rpuNoPopup') == 'true') {
		    hostInfo.nopopup = true;
		}*/
		doButtons();
	    },Array(apikey, myURL, wpPlugin));
	    


	    
	    
	    
	});
    }
})(window,document);   



