var searchState = false;
var searchType = defaultSearchType;
var searchAction = defaultSearchAction;
var wlSearchType = defaultWlSearchType;
var preloaded = new Array();
var tabs = defaultTabs;
var nowPlaying;
var divNum = 0;
var commentsNum = 0;
var commentsIndex = 0;
var form_id = 0;
var comments;

function ProcessTopStories() {
    var content = '';
    return content;
}

function urldecode(str) {
    str = unescape(str);
    return str;
}

function ProcessPopularStories(resp) {
    var content = '';
    var stories = '';
    
    for (var i = 0; i < resp.stories.length; i++) {
        stories += '<h2><li><a href="' + resp.stories[i].url + '?popular=true">' + urldecode(resp.stories[i].title).replace(/[^\x0d\x0a\x20-\x7e\t]/g, '').replace(/\&rsquot;/g, '\'') + '</a></li></h2>';
    }
    
    content += '' +
    '<ul class="popularStories">' +
    '   ' + stories +
    '</ul>';
    
    $('#popular-stories-title').css('display', 'block');
    $('#popular-stories').html(content).css('display', 'block');
    
    return content;
}

Array.prototype.inArray = function (value)
	{
		var i;
		for (i=0; i < this.length; i++)
			{
				if (this[i] == value)
				{
					return i;
				}
			}
		return false;
	};
	
String.prototype.stripTags = function () {
   return this.replace(/<([^>]+)>/g,'');
}

String.prototype.truncate = function(length) {
  trunc = this.substring(0, length);
  return trunc.replace(/\w+$/, '');
}

function PreloadImages()
	{
		for (var i = 0; i < PreloadImages.arguments.length; i++)
		{
			preloaded[i] = document.createElement('img');
			preloaded[i].setAttribute('src',arguments[i]);
		}
	}

function SetStyle(objId,style,value) 
	{
		document.getElementById(objId).style[style] = value;
	}

function SwapStyle(objId,className) 
	{
		document.getElementById(objId).className = className;
	}

function ToggleSearch(action)
	{
		if (action == 'open')
		{
			if (searchState == false)
			{
				SetStyle('keywords','backgroundPosition','0 -34px');
				SetStyle('wickedAds728x90','display','none');
				//new Effect.Appear('searchExpanded',{duration: .2});
				document.getElementById('searchExpanded').style.display = 'block';
				SetSearch(searchType,searchAction,wlSearchType);
				searchState = true;
			}
		}
		else if (action == 'close')
		{
			if (document.getElementById('keywords').value == '')
			{
				SetStyle('keywords','backgroundPosition','0 0');
			}
			//new Effect.Fade('searchExpanded',{duration: .2});
			document.getElementById('searchExpanded').style.display = 'none';
			SetStyle('wickedAds728x90','display','block');
			searchState = false;
		}
	}

function SetSearch(objId,action,wlSearchType)
	{
		SwapStyle(searchType,'searchOptionOff');
		SwapStyle(objId,'searchOptionDown');
		document.getElementById('searchForm').action = action;

		if (objId == 'search_homes_div') {document.getElementById('searchForm').method = 'post';}

		document.getElementById('p').value = wlSearchType;
		checkedField = objId.replace(/_div.*/, '');
		document.getElementById(checkedField).checked = 'checked';
		searchType = objId;
	}

function SubmitSearch()
	{
		var keywords = document.getElementById('keywords').value;
		document.getElementById('q').value = keywords;
		document.getElementById('qKeywords').value = keywords;
		document.getElementById('qCity').value = keywords;
		document.getElementById('keywords_all').value = keywords;
		document.getElementById('kw').value = keywords;
		document.getElementById('se.category.kq').value = keywords;
		document.getElementById('searchForm').submit();
	}

function ToggleTab(tab,override)
	{
		var anchor = tab+"_a";
		var tabData = tab.split("_");
		var tabSet = tabData[0];
		var tabContent = tab+"_content";
		
		if ((tabs.inArray(tab) == false) || (override == true))
		{
			if (override != true)
			{
				for (i=0; i < tabs.length; i++)
				{
					thisTabSet = tabs[i].split("_");
					if (tabSet == thisTabSet[0])
					{
						currentTab = i;
					}
				}
				SwapStyle(tabs[currentTab]+"_a",'unselected');
				SetStyle(tabs[currentTab]+"_content",'display','none');
				tabs[currentTab] = tab;
			}
			SetStyle(tabContent,'display','block');
			SwapStyle(anchor,'selected');
		}
	}

function ToggleShare()
	{
		if (document.getElementById('share').style.display == 'none')
		{
			document.getElementById('shareButton').innerHTML = 'Close';
			document.getElementById('shareButton').title = 'Close';
			SwapStyle('shareButton','close');
			//new Effect.BlindDown('shareContainer',{duration: .1});
			//new Effect.Appear('share',{duration: .4});
			document.getElementById('shareContainer').style.display = 'block';
			document.getElementById('share').style.display = 'block';
		}
		else
		{
			document.getElementById('shareButton').innerHTML = 'Share';
			document.getElementById('shareButton').title = 'Share Story';
			SwapStyle('shareButton','share');
			//new Effect.BlindUp('shareContainer',{duration: .4});
			//new Effect.Fade('share',{duration: .1});
			document.getElementById('shareContainer').style.display = 'none';
			document.getElementById('share').style.display = 'none';
		}
	}

function ToggleRelated(content) {
  return false;
}

function ProcessFeed(feed,type,args)
	{
		if (type == 'blog')
		{
			if (feed.entry[0].title != 'NULL') {
				feedData = '<div class="blog_tease"><h3><a href="'+feed['channel']['link']+'" title="'+feed['channel']['title']+'">'+feed['channel']['title']+'</a></h3><h2><a href="'+feed.entry[0].link+'" title="'+feed.entry[0].title+'"><span>New:</span> '+feed.entry[0].title+'</a></h2></div>';
				
				document.write(feedData);
				feedData = '';
			}
		}

		if (type == 'photo')
		{
			for (var i = 0; i < feed.entry.length; i++)
			{
				photoTitle = feed.entry[i].title;
				photoUrl = feed.entry[i].link;
				photoThumb = feed.entry[i].thumbnail;
				photoAuthor = feed.entry[i].author;
				
				if (photoUrl != 'NULL')
				{
					feedData = '<a href="'+photoUrl+'" class="photo clearfix" title="'+photoTitle+'"><img src="'+photoThumb+'" alt="'+photoTitle+'" title="'+photoTitle+'" />'+photoTitle+'<br />by <span>'+photoAuthor+'</span></a>';
				}

				document.write(feedData);
				feedData = '';
			}
		}

		if (type == 'top_ads')
		{
			for (var i = 0; i < feed.advertisers.length; i++)
			{
				adName = travAdvListData.advertisers[i].advertiser.name;
				adTitle = travAdvListData.advertisers[i].advertiser.title;
				adID = travAdvListData.advertisers[i].advertiser.id;

				feedData = '<div class="ad"><a href="http://'+args+'.shopping.wickedlocal.com/ROP/ads.aspx?advid='+adID+'" title="'+adTitle+'">'+adName+'</a></div>';
				
				document.write(feedData);
				feedData = '';
			}
		}
		
		if (type == 'weather')
		{
			var currentTemp = weather_json.TemperatureF;
			
			if (currentTemp != 'undefined')
			{
				document.getElementById('weather_data_target').innerHTML = '<a class="now" href="' + site_url + '/weather" title="Current Conditions" onclick="this.blur();">'+currentTemp+'&deg;</a>';
				document.getElementById('weather_button_target').innerHTML = '<a class="weather" href="' + site_url + '/weather" title="'+args+' Weather" onclick="this.blur();">'+args+' Weather</a>';
			}
		}

	}

function BuildSoundSlide(object, title, size)
 {
    size = size.replace('(', '');
    size = size.replace(')', '');
    size = size.split(',');
    var ssWin = window.open('', 'ssWin', 'width=' + size[0] + ',height=' + size[1]);
    with(ssWin.document) {
        open('text/html', 'replace');
        write('<html><head><title>' + title + '</title></head><body style="margin: 0;">' + object + '</body></html>');
        close();
    }
}

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" }, { 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" }, { 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" } ]
	};

BrowserDetect.init();

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 * 
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification 
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 * 
 * Licensed under the MIT license.
 */

function humane_date(date_str) {
    var time_formats = [
    [60, 'just now'],
    [90, '1 minute'],
    // 60*1.5
    [3600, 'minutes', 60],
    // 60*60, 60
    [5400, '1 hour'],
    // 60*60*1.5
    [86400, 'hours', 3600],
    // 60*60*24, 60*60
    [129600, '1 day'],
    // 60*60*24*1.5
    [604800, 'days', 86400],
    // 60*60*24*7, 60*60*24
    [907200, '1 week'],
    // 60*60*24*7*1.5
    [2628000, 'weeks', 604800],
    // 60*60*24*(365/12), 60*60*24*7
    [3942000, '1 month'],
    // 60*60*24*(365/12)*1.5
    [31536000, 'months', 2628000],
    // 60*60*24*365, 60*60*24*(365/12)
    [47304000, '1 year'],
    // 60*60*24*365*1.5
    [3153600000, 'years', 31536000],
    // 60*60*24*365*100, 60*60*24*365
    [4730400000, '1 century'],
    // 60*60*24*365*100*1.5
    ];

    var time = ('' + date_str).replace(/-/g, "/").replace(/[TZ]/g, " "),
    dt = new Date,
    seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
    token = ' ago',
    i = 0,
    format;

    if (seconds < 0) {
        seconds = Math.abs(seconds);
        token = '';
    }

    while (format = time_formats[i++]) {
        if (seconds < format[0]) {
            if (format.length == 2) {
                return format[1] + (i > 1 ? token: '');
                // Conditional so we don't return Just Now Ago
            } else {
                return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token: '');
            }
        }
    }

    // overflow for centuries
    if (seconds > 4730400000)
    return Math.round(seconds / 4730400000) + ' centuries' + token;

    return date_str;
};

$(function() {
  for (var i = 0; i < tabs.length; i++)
  	{
  		ToggleTab(tabs[i],true);
  	}

  if (document.getElementById('cutline'))
  {
  	document.getElementById('cutline').innerHTML = document.getElementById('cutline').innerHTML.stripTags();
  	document.getElementById('cutline').innerHTML = document.getElementById('cutline').innerHTML.truncate(125);
  	SetStyle('cutline','display','block');
  }

  if (document.getElementById('storyDateline'))
  {
  	var dlSwitch = false;
  	if (document.getElementById('storyBody'))
  	{
  		//ProcessDateline(document.getElementById('storyDateline'),document.getElementById('storyBody'));
  		SetStyle('storyBody','display','block');
  	}
  }

  if (document.getElementById('firstVideo'))
  {
  	nowPlaying = document.getElementById('firstVideo');
  }
});