//////////////////////////////////////////////////////////////////////
// Object-functional programming utilities
//////////////////////////////////////////////////////////////////////

if (typeof Object.beget !== 'function' ) {
    Object.beget = function(o) {
        var F = function() {};
        F.prototype = o;
        return new F();
    };
}

var linkPrefix = null;
var originatingPathWithinApplication = null;
var originalLocation = null;
var windowLocationLabel = "window-location-cookie";

function initSpinspotterProperty(name, value) {
	if (name == 'linkPrefix') {
		linkPrefix = value;
	}
	else if (name == 'originatingPathWithinApplication') {
		originatingPathWithinApplication = value;
	}

	if (originalLocation == null) {
		var windowLocationCookie = readSpinspotterCookie(windowLocationLabel);
		var localOriginalLocation = new String(window.location);
		if (windowLocationCookie != null && localOriginalLocation.lastIndexOf('#') < 0) {
			originalLocation = windowLocationCookie;
		}
		else {
			originalLocation = localOriginalLocation;
			createSpinspotterCookie(windowLocationLabel, originalLocation, 0);
		}
	}
}

function initSpinspotterJS() {
	var localTabLocation = getSpinspotterTabLocation();
	var localTabBookmark = getSpinspotterTabBookmark();
	var currentLocation = new String(window.location);
	var currentLocationBookmarkIndex = currentLocation.lastIndexOf('#');

	if (currentLocationBookmarkIndex > -1) {
		currentLocation = currentLocation.substring(0, currentLocationBookmarkIndex);
	}

	if (localTabBookmark != null && localTabLocation == currentLocation) {
		if (localTabBookmark != null && localTabBookmark.length < 1) {
			localTabBookmark = null;
		}
		initSpinspotterJSCallback(originatingPathWithinApplication, localTabBookmark);
	}
}

function createSpinspotterCookie(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 readSpinspotterCookie(name) {
	var value = null;
	var cookieIndex = document.cookie.indexOf(name + '=');
	if (cookieIndex > -1) {
		cookieIndex += name.length + 1;
		var endIndex = document.cookie.indexOf(';', cookieIndex);
		value = endIndex > -1 ?
			document.cookie.substring(cookieIndex, endIndex) : document.cookie.substring(cookieIndex);
	}
	return value;
}

function eraseSpinspotterCookie(name) {
	createSpinspotterCookie(name, "", -1);
}

function getSpinspotterTabBookmark() {
	var urlBookmark = null;
	if (originalLocation != null && originalLocation.length > 0) {
		var bookmarkIndex = originalLocation.lastIndexOf('#');
		if (bookmarkIndex > -1) {
			urlBookmark = originalLocation.substring(bookmarkIndex + 1);
			if (urlBookmark.length < 1) {
				urlBookmark = null;
			}
		}
	}
	return urlBookmark;
}

function getSpinspotterTabLocation() {
	var urlLocation = null;
	if (originalLocation != null && originalLocation.length > 0) {
		bookmarkIndex = originalLocation.lastIndexOf('#');
		urlLocation = bookmarkIndex > -1 ?
				originalLocation.substring(0, bookmarkIndex) : originalLocation;
	}
	return urlLocation;
}

function adjustSpinspotterBookmarkUrl(tabBookmark) {
	var bookmarkUrl = "";
	var oldTabBookmark = null;
	var windowLocationString = new String(window.location);
	var newWindowLocationString = windowLocationString;
	var bookmarkIndex = windowLocationString.lastIndexOf('#');

	if (bookmarkIndex > -1) {
		oldTabBookmark = windowLocationString.substring(bookmarkIndex + 1);
		newWindowLocationString = windowLocationString.substring(0, bookmarkIndex);
	}
	else {
		var localOldTabBookmark = getSpinspotterTabBookmark();
		if (localOldTabBookmark != null) {
			oldTabBookmark = localOldTabBookmark;
		}
	}

	if (tabBookmark != null && tabBookmark.length < 1) {
		tabBookmark = null;
		oldTabBookmark = null;
	}

	if (tabBookmark != null || oldTabBookmark != null) {
		if (tabBookmark != null) {
			bookmarkUrl += tabBookmark;
		}
		else if (oldTabBookmark != null) {
			bookmarkUrl += oldTabBookmark;
		}

		newWindowLocationString = newWindowLocationString + '#' + bookmarkUrl;
	}
	createSpinspotterCookie(windowLocationLabel, newWindowLocationString, 0);
	var pageYOffset = window.pageYOffset;
	window.location = newWindowLocationString;
}


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function fitTextOnOneLine(textElementId, numberOfLines) {
	var oneLiner = document.getElementById(textElementId);
	var baseText = oneLiner.innerHTML;
	var originalHeight = oneLiner.offsetHeight;
	oneLiner.innerHTML = "!";
	var baseHeight = oneLiner.offsetHeight;
	oneLiner.innerHTML = baseText;

	if (numberOfLines == null) {
		numberOfLines = 1;
	}

	if (originalHeight != baseHeight) {
		var originalText = baseText.trim();

		var closingDirectives = new Array();
		var choppedText;
		var choppedHeight;
		var previousChoppedText = "";
		var inDirective = false;
		var inCloseDirective = false;
		var removeClosingDirective = false;
		var openDirectiveIndex = -1;
		var closeDirectiveIndex = -1;
		var endDirectiveIndex = -1;
		var currentLine = 0;
		var currentIndex;
		var currentChar;

		for (currentIndex = 0; currentIndex < originalText.length; ++currentIndex) {
			currentChar = originalText.charAt(currentIndex);
			if (!inDirective && currentChar == " ") {
				choppedText = originalText.substring(0, currentIndex);
				for (var removeIndex = closingDirectives.length - 1; removeIndex >= 0; --removeIndex) {
					choppedText = choppedText + closingDirectives[removeIndex];
				}
				oneLiner.innerHTML = choppedText;
				choppedHeight = oneLiner.offsetHeight;
				if (choppedHeight != baseHeight) {
					++currentLine;
					if (currentLine == numberOfLines) {
						oneLiner.innerHTML = previousChoppedText;
						break;
					}
					else {
						baseHeight = oneLiner.offsetHeight;
						oneLiner.innerHTML = baseText;
						previousChoppedText = choppedText;
					}
				}
				else {
					oneLiner.innerHTML = baseText;
					previousChoppedText = choppedText;
				}
			}
			else if (!inDirective && currentChar == "<") {
				openDirectiveIndex = currentIndex;
				endDirectiveIndex = -1;
				closeDirectiveIndex = -1;
				inDirective = true;
				inCloseDirective = false;
				removeClosingDirective = false;
			}
			else if (inDirective && currentChar == "/") {
				closeDirectiveIndex = currentIndex;
				if (endDirectiveIndex == openDirectiveIndex + 1) {
					inCloseDirective = true;
					removeClosingDirective = true;
				}
			}
			else if (inDirective && currentChar == ">") {
				inDirective = false;
				endDirectiveIndex = currentIndex;
				if (!inCloseDirective && closeDirectiveIndex == endDirectiveIndex - 1) {
					inCloseDirective = true;
				}

				var theDirective = "</" +
					originalText.substring(openDirectiveIndex + 1, endDirectiveIndex + 1);
				var closeSpaceIndex = theDirective.indexOf(" ");
				if (closeSpaceIndex > -1) {
					theDirective = theDirective.substring(0, closeSpaceIndex) + ">";
				}

				if (!inCloseDirective) {
					closingDirectives[closingDirectives.length] = theDirective;
				}
				else if (removeClosingDirective) {
					var newClosingDirectives = new Array();
					var newRemoveIndex = 0;
					for (var removeIndex = 0; removeIndex < closingDirectives.length; ++removeIndex) {
						if (closingDirectives[removeIndex] != theDirective) {
							newClosingDirectives[newRemoveIndex++] =
								closingDirectives[removeIndex];
						}
					}
				}
			}
		}
	}
}

/////////////////////////////////////////////////////
// setActiveNavTab
// Sets which tab in the upper navigation bar should
// be active, based on the url.
/////////////////////////////////////////////////////
function setActiveNavTab(){
	var url = document.location.href;
	var splitURL = [];
		splitUrl = url.split("/");
	// We only care about the last member of the array,
	// which should be the final sub-directory
	var page = splitUrl[splitUrl.length -1];
	// First, set all tabs to inactive
	$("#nav li.active").each(function(){
		$(this).removeClass('active');
	});
	switch(page){
		case "":
		case "home":
			$('#n_home').addClass('green');
			break;
		case "events":
			$('#n_myspot').addClass('green');
			break;
		case "create":
			$('#n_getstarted').addClass('green');
			break;
		case "faq":
			$('#n_support').addClass('green');
			break;
		default:
			break;
	}
}
/////////////////////////////////////////////////////
// change_smartbar
// Requires jquery
/////////////////////////////////////////////////////

function change_smartbar(state){
	var smartbarTabs = $('.smartbar_tab');
	var currentTab = document.getElementById(state);
	for (var i = 0; i < smartbarTabs.length; i++){
		if(smartbarTabs[i].id != state){
			smartbarTabs[i].style.display="none";
		} else { smartbarTabs[i].style.display="";
		}
	}
	return false;
}


/////////////////////////////////////////////////////
// changeTab()
// Requires jquery
/////////////////////////////////////////////////////

function changeTabHelper(e, tab, defaultParm) {
	var tabs = $('.bubbleTab');
	var tabItems = $('.tabList li:not(".righter")');
	tabItems.each(function(i){$(this).removeClass("active");});
	$(e).addClass('active');
	document.getElementById(tab).style.display="";
	for (var i = 0; i < tabs.length; i++){
		if(tabs[i].id != tab){
			tabs[i].style.display="none";
		}
	}

	if (defaultParm) {
		adjustSpinspotterBookmarkUrl("");
	}
	else {
		adjustSpinspotterBookmarkUrl(tab);
	}
}

function changeTabDefault(e, tab) {
	changeTabHelper(e, tab, true);
}

function changeTab(e, tab) {
	changeTabHelper(e, tab, false);
}

/////////////////////////////////////////////////////
/////////////////////////////////////////////////////

var initedLinkPrefix = linkPrefix == null ? "" : linkPrefix;
var howItWorksText = [[
    '<a href="' + initedLinkPrefix + 'download">Get your Spinoculars&trade;</a>',
    'Surf any site and ask, <br />&ldquo;Is that true?&rdquo;',
    'Resuscitate objective journalism'
]];

function selectHowItWorksText() {
    var index = Math.round(Math.random() * (howItWorksText.length - 1));
    var stuff = howItWorksText[index];
    $("#hdiw_1").html(stuff[0]);
    $("#hdiw_2").html(stuff[1]);
    $("#hdiw_3").html(stuff[2]);
}

jQuery(selectHowItWorksText);

/////////////////////////////////////////////////////
/////////////////////////////////////////////////////

var articlePromotionRotatorText = new Array(
    "Wanna see some living, breathing spin in action?  Subscribe to HotSpots!", "Want to know what others are marking as spin? Visit our Top Spotters", "Curious about the latest on truth and transparency online? Visit our SpinSpotter blog!"
);

var articlePromotionRotatorUris = new Array(
	"/home/hotspots", "/home/top-spotters", "http://spinspotter.wordpress.com"
);

function selectArticlePromotionRotatorText() {
    var index = Math.round(Math.random() * (articlePromotionRotatorText.length - 1));
    var selectedPromotionRotatorText = articlePromotionRotatorText[index];
    var selectedPromotionRotatorUri = articlePromotionRotatorUris[index];
    var localLinkPrefix = selectedPromotionRotatorUri.length > 0 && selectedPromotionRotatorUri.substring(0, 1) == "/" ? linkPrefix.substring(0, linkPrefix.length - 1) : "";
    $("#cell_downloadspinoculars").html("<a href='" + localLinkPrefix + selectedPromotionRotatorUri + "'>" + selectedPromotionRotatorText + "</a>");
}

jQuery(selectArticlePromotionRotatorText);


/////////////////////////////////////////////////////
// 
/////////////////////////////////////////////////////


var confirmAbort = {
	confirmAbortActiveFlag: false,
	textObject: null,

	confirmAbortActive: function(caafParm, textIdParm) {
		var callingError = false;

		if (caafParm == true || caafParm == false) {
			confirmAbortActiveFlag = caafParm;
			textObject = confirmAbortActiveFlag ? document.getElementById(textIdParm) : null;

			if (confirmAbortActiveFlag && textObject == null) {
				callingError = true;
			}
		}
		else {
			callingError = true;
		}

		if (callingError) {
			alert("confirmAbort.confirmAbortActive not called correctly! [" +
				caafParm + ", " + textIdParm + "]");
		}
	},

	handleConfirmAbort: function() {
		if (typeof confirmAbortActiveFlag != 'undefined' && confirmAbortActiveFlag && textObject != null && !confirmAbort.isBlank(textObject.value)) {
			return "You have an unsaved post on this page.";
		}
		else {
			return;
		}
	},

	isBlank: function(stringCheck) {
		var blank = true;
		var inDirective = false;
		var currentChar;
		if (stringCheck != null && stringCheck.length > 0) {
			for (var index = 0; index < stringCheck.length; ++index) {
				currentChar = stringCheck.charAt(index);
				if (currentChar == '<') {
					if (!inDirective) {
						inDirective = true;
					}
					else {
						blank = false;
						break;
					}
				}
				else if (inDirective && currentChar == '>') {
					inDirective = false;
				}
				else if (!inDirective && currentChar == '&') {
					if ("&nbsp;" == stringCheck.substring(index, index + 6).toLowerCase()) {
						index += 5;
					}
					else {
						blank = false;
						break;
					}
				}
				else if (!inDirective && currentChar != ' ') {
					blank = false;
					break;
				}
			}
		}
		return blank;
	}
};


/////////////////////////////////////////////////////
// 
/////////////////////////////////////////////////////


var displayList = {
    defaultQuery : 10,

    displayError: function(message) { 
        this.div.html("<p><em>Error loading the list.  Click the tab again.  If the problem persists " +
        "contact us at <a mailto=\"support@spinspotter.com\">support@spinspotter.com</a>." + 
        "Please tell us you were trying to access the <strong>" + this.list + "</strong> list.</em></p>" +
        "<p>Reason: " + message + "</p>");
    },

    display : function(html) {
        this.div.html(html);
        $("#caption-" + this.params.list).html(this.params.caption);
    },

    paramSet : {
        "spin-blog" : {
            system: "listBlog", 
            list: "spin-blog",
            caption: "Created by the SpinSpotter editorial team."
        },
        "top-stories" : {
            system: "listArticle", 
            list: "top-articles",
            caption: "Articles that are receiving a lot of activity."
        },
        "best-markers" : {
            system: "listMarker", 
            list: "top-spotters",
            caption: "Spotters who have created markers recently and have high trust."
        },
        "top-spotters" : {
            system: "listMarker", 
            list: "recent-top-spotters",
            caption: "Continually feeds all human created markers loaded into the system." 
        }
    },

    takingAWhile : function(me) {
        me.div.html("<em>Sorry, it's taking a while...</em>");
    },

	
    takingAWhile : function(me) {
        me.div.html("<em>Sorry, it's taking a while...</em>");
    },

    go : function(list, count, pageAttribute) {
        var context = Object.beget(this);

        if ( typeof(count) === "undefined" || count < 0 ) {
            count = this.defaultQuery;
        }

        if (pageAttribute == null) {
            pageAttribute = "";
        }
        if (pageAttribute.length > 0) {
            pageAttribute = "&" + pageAttribute;
        }

        context.list = list;
        context.div = $("#" + list);
        context.div.html("<em>Loading...</em>");
        context.params = context.paramSet[list];
        context.uri = context.params.system + "/" + context.params.list + "?" + count + pageAttribute;
        context.timeoutID = window.setTimeout(context.takingAWhile, 3000, context); 

        $.ajax({
            context: context,
            url: context.uri,
            type: 'GET',
            dataType: 'html',
            timeout: 10000,
            error: function(request, message) {
                window.clearTimeout(this.context.timeoutID);
                this.context.displayError(message);
            },
            success: function(html) {
                window.clearTimeout(this.context.timeoutID);
                this.context.display(html);
            }
        });
    }
};

/////////////////////////////////////////////////////
// BrowserDetect by Peter-Paul Koch
// From: http://www.quirksmode.org/js/detect.html
// BrowserDetect.browser is the browser
// BrowserDetect.version is the version
/////////////////////////////////////////////////////

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};