/*!
 * Citer - Easily citing the web.
 * Copyright (c) 2010 Brad Cooper | http://willworkforart.net
 * Licensed under GNU General Public License v3
 * Date: 06/20/2011
 * @author Brad Cooper
 * @version: 0.21.3
 *
 * http://willworkforart.net/projects/citer
 *
 */
/*global document: false, window: false */
var allCiterOptions, theQuote, theDate, original = "test";
function getSelectedText() {
	var selectedText;
	if (window.getSelection) {
		selectedText = window.getSelection();
	} else if (document.selection) { 
		selectedText = document.selection.createRange();
	}
	return selectedText;
}
function getStyle(theItem, cssRule) {
	var theString = "";
	if (document.defaultView && document.defaultView.getComputedStyle) {
		theString = document.defaultView.getComputedStyle(theItem, "").getPropertyValue(cssRule);
	} else if (theItem.currentStyle) {
		cssRule = cssRule.replace(/\-(\w)/g, function (strMatch, p1) {
			return p1.toUpperCase();
		});
		theString = theItem.currentStyle[cssRule];
	}
	return theString;
}
function recognizeSite() {
	var theUrl, recognizedSites, matchedSite, i;
	theUrl = document.location;
	recognizedSites = ["status", "desketopo"];
	for (i = 0; i < recognizedSites.length; i = i + 1) {
		matchedSite = theUrl.toString().toLowerCase().match(recognizedSites[i]);
		if (matchedSite !== null) {
			break;
		}
	}
	return matchedSite;
}
function setupStyle() {
	var theStyle = document.createElement('link');
	theStyle.id = "citerStyle";
	theStyle.setAttribute('rel', 'stylesheet');
	theStyle.setAttribute('type', 'text/css');
	theStyle.setAttribute('href', 'http://code.willworkforart.net/citer/citer.css');
	
	document.body.appendChild(theStyle);
}
function setupTracking() {
	var theIframe = document.createElement('iframe');
	theIframe.id = "citerTracking";
	theIframe.setAttribute('src', 'http://code.willworkforart.net/citer/gaTracking.html');
	theIframe.setAttribute('style', 'width:0px; height:0px; display:none;');
	document.body.appendChild(theIframe);
}
function setupciterError() {
	var citerError = document.createElement("div");
	citerError.id = "citerError";
		
	document.body.appendChild(citerError);
}
function adjustQuote(original) {
	original = original.replace(/&quot;/gi, "'");
	original = original.replace(/ class="tweet-url web"/gi, "");
	original = original.replace(/ target="_blank"/gi, "");
	if (allCiterOptions.userDesign === true && allCiterOptions.externalStyle === true) {
		original = original.replace(/<a/gi, "<a style='color:" + theQuote.linkColor + ";' ");
	} else if (allCiterOptions.userDesign === true && allCiterOptions.externalStyle === false) {
		original = original.replace(/<a/gi, "<a style='color:" + theQuote.linkColor + ";' ");
	} else if (allCiterOptions.userDesign === false && allCiterOptions.externalStyle === false) {
		original = original.replace(/<a/gi, "<a style='color:#3e5381;' ");
	}

	return original;
}
function convertMonthToNumber(month) {
	var newMonth;
	switch(month) {
		case "Jan":
			newMonth = "01";
			break;
		case "Feb":
			newMonth = "02";
			break;
		case "Mar":
			newMonth = "03";
			break;
		case "Apr":
			newMonth = "04";
			break;
		case "May":
			newMonth = "05";
			break;
		case "Jun":
			newMonth = "06";
			break;
		case "Jul":
			newMonth = "07";
			break;
		case "Aug":
			newMonth = "08";
			break;
		case "Sep":
			newMonth = "09";
			break;
		case "Oct":
			newMonth = "10";
			break;
		case "Nov":
			newMonth = "11";
			break;
		case "Dec":
			newMonth = "12";
			break;
	}
	return newMonth;
}
function convertDateTime(originalDate) {
	var year, month, day, time;
	originalDate = originalDate.split(" ");
	day = originalDate[1];
	month = convertMonthToNumber(originalDate[2]);
	year = originalDate[3];
	time = originalDate[4];	
	originalDate = year + "-" + month + "-" + day + "T" + time;
	return originalDate;
}
function removeciter() {
	var thePage, toRemove;
	thePage = document.getElementsByTagName("body")[0];
	toRemove = document.getElementById("citerScript");
	thePage.removeChild(toRemove);
	toRemove = document.getElementById("citerStyle");
	thePage.removeChild(toRemove);
	toRemove = document.getElementById("citerApp");
	thePage.removeChild(toRemove);
}
function setMicrodata(item) {
	var theValue, microDataOption;
	
	theValue = item.getAttribute("value");
	microDataOption = document.getElementById("microdata");
	if (theValue === "html4") {
		microDataOption.checked = false;
		microDataOption.setAttribute("disabled", "disabled");
	} else {
		microDataOption.checked = true;
		microDataOption.removeAttribute("disabled");
	}
}
function getTwitterData() {
	var theTweet, twitterEntry, allDivs, allDivsLength, theDivClass, twitterAllItems, b, i, theClass, origDate;
	twitterEntry = document.getElementById("page-container");
	allDivs = twitterEntry.getElementsByTagName("div");
	
	allDivsLength = allDivs.length;
	for (b = 0; b < allDivsLength; b = b + 1) {
		theDivClass = allDivs[b].getAttribute("class");
		if (theDivClass === "components-middle") {
			twitterAllItems = allDivs[b].getElementsByTagName("*");
			for (i = 0; i < twitterAllItems.length; i = i + 1) {
				theClass = twitterAllItems[i].getAttribute("class");
				switch (theClass) {
				case "protected-icon protected-icon-timeline":
					alert("Sorry, this is a protected post and cannot be shared");
					return false;
					
				case "tweet-user-block-full-name":
					theQuote.name = twitterAllItems[i].innerHTML;
					break;
				
				case "tweet-user-block-screen-name user-profile-link":
					theQuote.nickname = twitterAllItems[i].innerHTML;
					theQuote.linkColor = getStyle(twitterAllItems[i], "color");
					break;
				
				case "tweet-text tweet-text-large":
					theTweet = twitterAllItems[i].innerHTML;
					theQuote.fontFamily = getStyle(twitterAllItems[i], "font-family");
					theQuote.fontColor = getStyle(twitterAllItems[i], "color");
					break;
				
				case "_old-timestamp":
					origDate = twitterAllItems[i].getAttribute("data-time");
					origDate = origDate.replace("000", "");
					theDate = new Date(origDate * 1000);
					theQuote.dateSpoken = theDate.toDateString();
					theQuote.dateTime = convertDateTime(theDate.toGMTString());
					break;
					
				case "_timestamp":
					origDate = twitterAllItems[i].getAttribute("data-time");
					origDate = origDate.replace("000", "");
					theDate = new Date(origDate * 1000);
					theQuote.dateSpoken = theDate.toDateString();
					theQuote.dateTime = convertDateTime(theDate.toGMTString());
					break;
				
				case "tweet-user-block":
					theQuote.avatarURL = twitterAllItems[i].getElementsByTagName("img")[0].getAttribute("src");
					theQuote.avatarWidth = 48;
					theQuote.avatarHeight = 48;
					break;
				}
			}
			theQuote.entry = theTweet;
			theQuote.url = window.location;
			theQuote.backgroundImage = getStyle(document.getElementsByTagName("body")[0], "background-image");
			theQuote.backgroundColor = getStyle(document.getElementsByTagName("body")[0], "background-color");
		}
	}
}
function setupciter() {
	var citerApp, marginLeft, windowWidth, citerHeader, citerArea, citerOptions, citerFooter, citerPreview, citerPreviewHeader, citerQuote, citerTimeData, citerQuoteWrap, citerBlockquote, citerTime, citerTimeLink, citerAvatar, citerAvatarLink, citerAvatarImg, citerNickName, citerNickNameSpan, citerNickNameLink, citerFullName, citerCode, citerCodeToFill, fullPreviewCode, theForm;

//create the App to inject into the page
	citerApp = document.createElement("div");
	citerApp.id = "citerApp";
	
//center Citer in the window
	windowWidth = document.documentElement.clientWidth;
	marginLeft = (windowWidth - 1000) / 2;
	citerApp.setAttribute("style", "margin-left:" + marginLeft + "px;");
	
//create the header
	citerHeader = document.createElement("div");
	citerHeader.id = "citerHeader";
	citerHeader.innerHTML = "<img src='http://code.willworkforart.net/citer/img/citer-logo.jpg' /><input type='submit' value='close' id='closeciter' onClick='removeciter();'/>";
	
//create the wrapper
	citerArea = document.createElement("div");
	citerArea.id = "citerArea";
	citerArea.className = "citerWrapper";
	
//create the options
	citerOptions = document.createElement("div");
	citerOptions.id = "citerOptions";
	citerOptions.className = "citerWrapper";
	citerOptions.innerHTML = "<h2>Options:</h2><form id='citerAllOptions' name='citerAllOptions'><p><input type='radio' name='html' id='html5' value='html5' checked='checked' onclick='setMicrodata(this)' /><label for='html5'>HTML 5</label><input type='radio' name='html' id='html4' value='html4' onclick='setMicrodata(this)' /><label for='html4'>HTML4</label></p><p><input type='checkbox' name='microdata' id='microdata' value='true' checked='checked' /><label for='microdata'>Include Microdata</label></p><p><input type='checkbox' name='inlineLayout' id='inlineLayout' value='false' /><label for='inlineLayout'>I will add styles to my own stylesheet (<a href='http://code.willworkforart.net/citer/example.css' target='_blank'>example css</a>)</label></p><p><input type='checkbox' name='userDesign' id='userDesign' value='true' checked='checked' /><label for='userDesign'>Include User Design (Background Image/Color & Link colors as inline CSS)</label></p><p><input type='submit' value='apply options' onclick='getOptions(); return false;' /></p></form>";	
	
//create the footer
	citerFooter = document.createElement("div");
	citerFooter.id = "citerFooter";
	citerFooter.innerHTML = "<p>Citer v0.21.2 &copy; 2010-2011 <a href='http://willworkforart.net' target='_blank'>Brad Cooper</a> | <a href='http://citer.uservoice.com' target='_blank'>submit a bug or request a feature</a> | visit the <a href='http://willworkforart.net/projects/citer' target='_blank'>Citer Project</a> website </p>";

//create the preview of the quote
	citerPreview = document.createElement("div");
	citerPreview.id = "citerPreview";
	
	citerPreviewHeader = document.createElement("h2");
	citerPreviewHeader.innerHTML = "Preview:";
		
//Create elements based on HTML type	
	if (allCiterOptions.html === "html5") {
		citerQuote = document.createElement("article");
		citerTimeData = document.createElement("time");
	} else {
		citerQuote = document.createElement("div");
		citerTimeData = document.createElement("p");
	}
	
	
//Create the Wrapper for the content
	citerQuoteWrap = document.createElement("div");
	
//create the Quote
	citerBlockquote = document.createElement("blockquote");
	theQuote.entryAdj = adjustQuote(theQuote.entry);
	citerBlockquote.innerHTML = theQuote.entryAdj;
	citerBlockquote.setAttribute("cite", theQuote.url);
	
//create the time
	citerTime = document.createElement("p");
	citerTimeLink = document.createElement("a");
	citerTimeLink.setAttribute("href", theQuote.url);
	citerTimeLink.setAttribute("rel", "bookmark");
	
//create the Avatar
	citerAvatar = document.createElement("p");
	citerAvatarLink = document.createElement("a");
	citerAvatarLink.setAttribute("href", "http://twitter.com/" + theQuote.nickname);
	
	citerAvatarImg = document.createElement("img");
	citerAvatarImg.setAttribute("src", theQuote.avatarURL);
	citerAvatarImg.setAttribute("width", theQuote.avatarWidth);
	citerAvatarImg.setAttribute("height", theQuote.avatarHeight);
	citerAvatarImg.setAttribute("alt", theQuote.nickname + " Avatar");
	
//create the NickName & Link
	citerNickName = document.createElement("p");
	
	citerNickNameSpan = document.createElement("span");
	
	citerNickNameLink = document.createElement("a");
	citerNickNameLink.setAttribute("href", "http://twitter.com/" + theQuote.nickname);
	citerNickNameLink.innerHTML = theQuote.nickname;
		
//create the full name
	citerFullName = document.createElement("p");
	citerFullName.innerHTML = theQuote.name;

//Set the Microdata
	if (allCiterOptions.theData === "microdata") {
		citerQuote.setAttribute("itemscope", "itemscope");
		citerQuote.setAttribute("itemtype", "http://schema.org/Person");
		
		citerTimeData.setAttribute("datetime", theQuote.dateTime);
		citerTimeData.innerHTML = theQuote.dateSpoken;
		citerTimeLink.appendChild(citerTimeData);
		
		citerAvatarLink.setAttribute("itemprop", "url");
		citerAvatarImg.setAttribute("itemprop", "photo");
		
		citerNickNameSpan.setAttribute("itemprop", "nickname");
		
		citerFullName.setAttribute("itemprop", "name");
	} else {
		citerTimeLink.innerHTML = theQuote.dateSpoken;
	}
		
//Set all the styles/inline styles/user designs
	
	//Inline Styles for JUST User Design (using external stylesheet)
	if (allCiterOptions.userDesign === true && allCiterOptions.externalStyle === true) {
		if (theQuote.backgroundImage !== "none") {
			citerQuote.setAttribute("style", "background:" + theQuote.backgroundImage);
		} else {
			citerQuote.setAttribute("style", "background-color:" + theQuote.backgroundColor);
		}
		citerBlockquote.setAttribute("style", "font-family:" + theQuote.fontFamily + "; color:" + theQuote.fontColor);
		citerTimeLink.setAttribute("style", "color:" + theQuote.linkColor);
		citerAvatarLink.setAttribute("style", "color:" + theQuote.linkColor);
		citerNickNameLink.setAttribute("style", "color:" + theQuote.linkColor);
		
		citerQuote.className = "citer";
	} else if (allCiterOptions.userDesign === true && allCiterOptions.externalStyle === false) {
	//Inline Styles for User Design AND Layout (using inline styles)
		if (theQuote.backgroundImage !== "none") {
			citerQuote.setAttribute("style", "padding:1em 2em; display:block; margin:0 1em; background-image:" + theQuote.backgroundImage + "; background-color: #3e5381;");

		} else {
			citerQuote.setAttribute("style", "padding:1em 2em; display:block; margin:0 1em; background-color:" + theQuote.backgroundColor);
		}
		citerQuoteWrap.setAttribute("style", "padding:2em 2em 3em 2em; background-color:#fff;");
		citerBlockquote.setAttribute("style", "clear:both; margin:0 0 0.2em; border:0; font-style:normal; font-size:28px; line-height:36px; font-family:" + theQuote.fontFamily + "; color:" + theQuote.fontColor);
		citerTime.setAttribute("style", "padding:0;");
		citerTimeLink.setAttribute("style", "text-decoration:none; color:" + theQuote.linkColor);
		citerNickName.setAttribute("style", "font-size:20px; line-height:24px;");
		citerAvatar.setAttribute("style", "padding:0; line-height:0;");
		citerFullName.setAttribute("style", "font-size:14px;");
		citerAvatarLink.setAttribute("style", "color:" + theQuote.linkColor);
		citerAvatarImg.setAttribute("style", "float:left; margin:0 1em 1em 0; width:48px; height:48px;");
		citerNickNameLink.setAttribute("style", "font-size:20px; text-decoration:none; color:" + theQuote.linkColor);
		
	} else if (allCiterOptions.userDesign === false && allCiterOptions.externalStyle === false) {
	//Inline Styles for JUST Layout, Plus Generic Colors. (using inline styles, no user design)
		citerQuoteWrap.setAttribute("style", "padding:2em 2em 3em 2em; background-color:#fff;");
		citerQuote.setAttribute("style", "padding:1em 2em; background-color:#3e5381; display:block; margin:0 1em;");
		citerBlockquote.setAttribute("style", "clear:both; margin:0 0 0.2em; font-size:28px; line-height:36px; font-family:arial; color:808080");
		citerTimeLink.setAttribute("style", "text-decoration:none; color:#3e5381;");
		citerAvatarLink.setAttribute("style", "color:#3e5381;");
		citerAvatarImg.setAttribute("style", "float:left; margin:0 1em 1em 0; width:48px; height:48px;");
		citerNickNameLink.setAttribute("style", "font-size:20px; text-decoration:none; color:#3e5381;");
	} else {
	//No style sheets have to be set for a False/True scenerio because everything pulls external Stylesheets - just need a hook.
		citerQuote.className = "citer";
	}
	
//create the blank copy-code area
	citerCode = document.createElement("div");
	citerCode.id = "citerCode";
	citerCode.innerHTML = "<h2>Copy this code:</h2><textarea id='citerCodeTextarea' onClick='this.focus();this.select();'></textarea>";
	
//Append everything to the Citer window
	citerTime.appendChild(citerTimeLink);
	
	citerAvatarLink.appendChild(citerAvatarImg);
	citerAvatar.appendChild(citerAvatarLink);
		
	citerNickNameSpan.appendChild(citerNickNameLink);
	citerNickName.appendChild(citerNickNameSpan);
	
	citerQuoteWrap.appendChild(citerAvatar);
	citerQuoteWrap.appendChild(citerNickName);
	citerQuoteWrap.appendChild(citerFullName);
	citerQuoteWrap.appendChild(citerBlockquote);
	citerQuoteWrap.appendChild(citerTime);
	
	citerQuote.appendChild(citerQuoteWrap);
		
	citerPreview.appendChild(citerQuote);
	
	citerArea.appendChild(citerCode);
	citerArea.appendChild(citerPreviewHeader);
	citerArea.appendChild(citerPreview);
	
	citerApp.appendChild(citerHeader);
	citerApp.appendChild(citerArea);
	citerApp.appendChild(citerOptions);
	citerApp.appendChild(citerFooter);
	
	document.body.appendChild(citerApp);
	
//put the Output Code into the textbox
	citerCodeToFill = document.getElementById("citerCodeTextarea");
	fullPreviewCode = document.getElementById("citerPreview");
	fullPreviewCode = fullPreviewCode.innerHTML.replace(/="itemscope"/gi, "");
	citerCodeToFill.value = fullPreviewCode.replace(/&quot;/gi, "'");
	
//set the options choices based on current settings
	theForm = document.getElementById("citerAllOptions");
	if (allCiterOptions.html === "html5") {
		theForm[0].checked = true;
		theForm[1].checked = false;
	} else if (allCiterOptions.html === "html4") {
		theForm[0].checked = false;
		theForm[1].checked = true;
	}
	if (allCiterOptions.theData === "microdata") {
		theForm[2].checked = true;
	} else {
		theForm[2].checked = false;
	}
	
	if (allCiterOptions.externalStyle === false) {
		theForm[3].checked = false;
	} else {
		theForm[3].checked = true;
	}
	
	if (allCiterOptions.userDesign === true) {
		theForm[4].checked = true;
	} else {
		theForm[4].checked = false;
	}
}
function getOptions() {
	var theForm, i, thePage, toRemove, theName;

//grab all the Output Code options
	theForm = document.getElementById("citerAllOptions");
	for (i = 0; i < theForm.length; i = i + 1) {
		theName = theForm[i].name;
		
		switch (theName) {
		case "html":
			if (theForm[i].checked === true) {
				allCiterOptions.html = theForm[i].value;
			}
			break;
		case "microdata":
			if (theForm[i].checked === true) {
				allCiterOptions.theData = "microdata";
			} else {
				allCiterOptions.theData = "none";
			}
			break;
		case "userDesign":
			if (theForm[i].checked === true) {
				allCiterOptions.userDesign = true;
			} else {
				allCiterOptions.userDesign = false;
			}
			break;
		case "inlineLayout":
			if (theForm[i].checked === false) {
				allCiterOptions.externalStyle = false;
			} else {
				allCiterOptions.externalStyle = true;
			}
			break;
		}
	}
	
//remove Citer from the current page
	thePage = document.getElementsByTagName("body")[0];
	toRemove = document.getElementById("citerApp");
	thePage.removeChild(toRemove);
	
//inject Citer onto the current page
	setupciter();	
}
function init() {
	var selectedText, theSite;

	setupStyle();
	setupTracking();
	theQuote = {};
	allCiterOptions = {};
	allCiterOptions.html = "html5";
	allCiterOptions.userDesign = true;
	allCiterOptions.theData = "microdata";
	allCiterOptions.externalStyle = false;
	
	theSite = recognizeSite();
	if (theSite !== null) {
		theSite = theSite.toString();
	} else {
		alert("Citer didn't recognize this Twitter post.");
	}
	if (theSite === 'status') {
		getTwitterData();
	}
	setupciter();
}
window.onload = init;
