var max_tweets = 90;
var max_secondtweets = 3;
var max_trends = 5;
var current_geocode = '55.9501755%2C-3.1875359%2C15mi';
var current_language = 'en';
var google_api_key = 'ABQIAAAAxz7XFfg1XJNYWVp0S3U2qxRPWrhF_Hf9VRWwqHRaBUJfKB4XxxR4k4XGkZY1TyXJ63e6D7hB6locmg';
var radius = '15mi';

function debug(msg) {
    if (typeof(console) != "undefined") {
        console.log(msg);
    }
}

function geocodeError() {
    alert("I can't geolocate that city!");
    return false;
}

function changeLocation(location) {
//    if (location.indexOf(',') == -1) {
//        location+=',uk';
//    }
    var url = 'http://maps.google.com/maps/geo?q='+location+'&output=json&key='+google_api_key+'&sensor=false&callback=?';

    debug(url);

    $.getJSON(url, function(json) {
        if (typeof(json.Placemark) == 'undefined') {
            return geocodeError();
        }

        var locality, country, lat, lon;

        try
        {
            lat = json.Placemark[0].Point.coordinates[0];
            lon = json.Placemark[0].Point.coordinates[1];
        }
        catch(err)
        {
            return geocodeError();
        }

        try
        {
            locality = json.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
        }
        catch(err)
        {
            try
            {
                locality = json.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
            }
            catch(err)
            {
                try
                {
                    locality = json.name;
                }
                catch(err)
                {
                    return geocodeError();
                }
            }
        }

        try
        {
            country = json.Placemark[0].AddressDetails.Country.CountryName;
        }
        catch(err)
        {
            return geocodeError();
        }

        current_geocode = ''+lon+'%2C'+lat+'%2C'+radius;
        current_location = locality+', '+country;
        $('#current-location').val(current_location);

        firstweets();
        $.cookie('last_geocode', current_geocode);
        $.cookie('last_location', current_location);
    });
}

function loadTweets() {
    $('div.tweets').each(function(){
        var keyword = $(this).attr('title');
        var $wrapper = $(this).closest('div.tweet-wrapper');
        var $elem = $(this).find('.tweets-keyword');
		var $adspace = $(this).find('.adspace');
        var date = $('#actual-date').val();

// reformat date and take a day off because, well, it's yesterday in California...
        var tmp = date.split('-');
        tmp = new Date(tmp[0], tmp[1], tmp[2] - 1);
        var y = tmp.getFullYear();
        var m = tmp.getMonth();
        var d = tmp.getDate();
        if (m < 10) {
            m = '0'+m;
        }
        if (d < 10) {
            d = '0'+d;
        }
        date = y+'-'+m+'-'+d;

        var url="http://search.twitter.com/search.json?q="+keyword+"&rpp="+(max_secondtweets + 10)+"&since="+date+"&geocode="+current_geocode+"&callback=?";

        $elem = $(this).find('.tweets-keyword');
        $elem.text(keyword);

        var count = 0;
        $elem = $(this).find('.tweets-content');
        $elem.html('<span class="loading">&nbsp;</span>');

        $.getJSON(url, function(json) {
            $(json.results).each(function() {
                if (count > max_secondtweets || this.iso_language_code != current_language) {
					//$("#page-container").dynaCloud();
					//for (var i = 1; i < max_secondtweets; ++i) {
					/*$adspace.append('<script type="text/javascript">google_ad_client = "pub-9774312811245135";google_ad_slot = "4228577926";google_ad_width = 468;google_ad_height = 15;</script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>');*/
					//}
                    return;
					
                }

// Txt spk is a disease. Meet the cure.
                var text = this.text;
                text = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;\?\/.=]+/g, '');
                text = text.replace(/[@#][A-Za-z0-9_]+[\s:!\.,]/g, ''); // no directing messages
                text = text.replace(/rt[@:]/ig, ''); // no retweet tag
                text = text.replace(/(plz|please)\srt/ig, ''); // no begging for retweets
                text = text.replace(/<.+>/g, ''); // strip tags
                text = text.replace(/\[!?]+?[!?]+/g, '?');
                text = text.replace(/!+/g, '!');

                temparray=text.split(' ');
				temptext='';
				
				jQuery('a', temparray).each(function() {
  					jQuery(this).click(function() {
						if((jQuery(this).text()!='Share')&&(jQuery(this).text()!='')){
						$('#current-category').val(jQuery(this).text());
						newCategory();
						}
						return false;
					});
				});
				for (var i = 0; i < temparray.length; ++i) {
   					temptext+=('<a href="#' + temparray[i] + '" >' + temparray[i] + '</a> ');
   				}
	   
	   
                if (!count) {
                    $elem.html('');
                }
                count++;

                $elem.append('<span>'+temptext+'</span>&nbsp;');
            });
            if (!count) {
                $wrapper.slideUp('slow', function() {
                   $wrapper.remove();
                });
            }
            $elem.corner();
        });

        return true;
    });
}

function firstweets() {
    $('div.firsttweet').each(function(){
        var keyword = $(this).attr('title');
        var $wrapper = $(this).closest('div.tweet-wrapper');
        var $elem = $(this).find('.tweets-keyword');
		var $adspace = $('.adspace');
		/*$adspace.append('<div><script type="text/javascript">google_ad_client = "pub-9774312811245135";google_ad_slot = "4228577926";google_ad_width = 468;google_ad_height = 15;</script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></div>');*/
        var date = $('#actual-date').val();

// reformat date and take a day off because, well, it's yesterday in California...
        var tmp = date.split('-');
        tmp = new Date(tmp[0], tmp[1], tmp[2] - 1);
        var y = tmp.getFullYear();
        var m = tmp.getMonth();
        var d = tmp.getDate();
        if (m < 10) {
            m = '0'+m;
        }
        if (d < 10) {
            d = '0'+d;
        }
        date = y+'-'+m+'-'+d;

        var url="http://search.twitter.com/search.json?q="+keyword+"&rpp="+(max_tweets + 10)+"&since="+date+"&geocode="+current_geocode+"&callback=?";

        $elem = $(this).find('.tweets-keyword');
        $elem.text(keyword);

        var count = 0;
        $elem = $(this).find('.tweets-content');
        $elem.html('<span class="loading">&nbsp;</span>');

        $.getJSON(url, function(json) {
            $(json.results).each(function() {
                if (count > max_tweets || this.iso_language_code != current_language) {
					
                    return;
					
                }

// Txt spk is a disease. Meet the cure.
                var text = this.text;
                text = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;\?\/.=]+/g, '');
                text = text.replace(/[@#][A-Za-z0-9_]+[\s:!\.,]/g, ''); // no directing messages
                text = text.replace(/rt[@:]/ig, ''); // no retweet tag
                text = text.replace(/(plz|please)\srt/ig, ''); // no begging for retweets
                text = text.replace(/<.+>/g, ''); // strip tags
                text = text.replace(/\[!?]+?[!?]+/g, '?');
                text = text.replace(/!+/g, '!');
				
				
                temparray=text.split(' ');
				temptext='';
				
				jQuery('a', temparray).each(function() {
  					jQuery(this).click(function() {
						if(jQuery(this).text()!=''){
						$('#current-category').val(jQuery(this).text());
						newCategory();
						}
						return false;
					});
				});
				for (var i = 0; i < temparray.length; ++i) {
   					temptext+=('<a href="#' + temparray[i] + '" >' + temparray[i] + '</a> ');
   				}
	   
	   
                if (!count) {
                    $elem.html('');
                }
                
				if(count<4){
					$elem.append('<span>'+temptext+'</span>&nbsp;');
				}else{
                	$elem.append('<span style="display:none;">'+temptext+'</span>&nbsp;');
				}
				count++;
				
            });
            if (!count) {
                $wrapper.slideUp('slow', function() {
                   $wrapper.remove();
                });
            }
			$("#firsttweet-container").dynaCloud();
			
            $elem.corner();
        });
		
        return true;
    });
}


function loadTrends() {
    var url="http://search.twitter.com/trends.json?callback=?";

    $.getJSON(url, function(json) {
        var index = 0;
        var $trends = $('ul#trends');
        $trends.html('');

        $(json.trends).each(function() {
            if (index++ < max_trends) {
                var text = this.name.replace(/^#/, '');

                $trends.append('<li>'+text+'</li>');

                $('#tweet-'+index).attr('title', text);
            }
        });

        $.cookie('last_category', '0');
        firstweets();
    });
}

function loadCookies() {
    var tmp = $.cookie('last_location');
    if (tmp) {
        current_location = tmp;
        current_geocode = $.cookie('last_geocode');
        $('select#current-location option:selected').text(current_location);
    }
	
	var $_GET = {};

	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
		function decode(s) {
			return decodeURIComponent(s.split("+").join(" "));
		}
	
		$_GET[decode(arguments[1])] = decode(arguments[2]);
	});
	
	t=$_GET["t"];

    tmp = $.cookie('last_category');
	if((tmp!=t)&&(t!='')) tmp=t;
    if (tmp) {
        //$('select#categories option[value="'+$.cookie('last_category')+'"]').attr('selected', 'selected');
		$('#current-category').val(tmp);
        newCategory();
    }
    else {
        //$('select#categories option[value="0"]').attr('selected', 'selected');
		$('#current-category').val('news');
        firstweets();
    }
}
function loadAdSense(){
	
}

function getCategory() {
    return $('#current-category').val();
}
function newCategory(){
	var keyword = $('#current-category').val();
    var $tweet_container = $('div#firsttweet-container');
	var $socialcontainer = $('div#socialcontainer');
	var $othertweet_container = $('div#tweet-container');
    var $trends = $('ul#trends');
	keyword =   keyword.replace(/[^a-zA-Z 0-9 £$]+/g,'');
	document.title=keyword+' is The Word On The Tweet';

    $trends.html('');
    $tweet_container.html('');
	$othertweet_container.html('');
	
	$tweet_container.html('<div class="tweet-wrapper" ><div class="firsttweet odd" id="tweet-00" title="'+keyword+'"><div class="tweets-keyword" ></div><div id="adspace0" class="adspace"></div><div class="tweets-share-main" ><div style="float:left;"><a href="http://twitter.com/home?status='+encodeURIComponent(keyword)+' is The Word On The Tweet http://www.thewordonthetweet.com?t='+encodeURIComponent(keyword)+'" title="Click to share this post on Twitter" onClick="twt_click(\''+keyword+'\')" ><img src="images/social/twitter.png" alt="Share on Twitter"></a></div><a name="fb_share" id="fb_share" type="button" href="http://www.facebook.com/sharer.php?u=http://www.thewordonthetweet.com?t='+keyword+'&t='+keyword+' is The Word On The Tweet" onClick="fbs_click(\'http://www.thewordonthetweet.com?t='+keyword+'\',\''+keyword+' is The Word On The Tweet\')"><img src="images/social/facebook.png" alt="Share on Facebook" /></a></div><div class="tweets-content" ><span class="loading">&nbsp;</span></div></div></div>');
	firstweets();
    $('.tweets-content').corner();
	
}
function changeCategory(keywords,maxlength) {
    //var keywords = $('#categories').find('option:selected').val().split(', ');
    if (keywords.length && keywords[0] == '0') {
        loadTrends();
    }
    else {
        var $tweet_container = $('div#tweet-container');
		var $socialcontainer = $('div#socialcontainer');
        var $trends = $('ul#trends');

        $trends.html('');
        $tweet_container.html('');
		$socialcontainer.html('');
		

        var row;
		

        for(i = 0; i < maxlength; i++) {
            row = (i % 2) ? 'odd' : 'even';
            $tweet_container.append('<div class="tweet-wrapper"><div class="tweets '+row+'" id="tweet-'+i+'"><div class="tweets-keyword"></div><div class="tweets-share" ></div><div class="tweets-content"><span class="loading">&nbsp;</span></div></div></div>');
		}

        var index = 0;
        $('div.tweets').each(function(){
            if (index < maxlength) {
				
                $(this).attr('title', keywords[index].el);
                $trends.append('<li>'+keywords[index].el+'</li>');
                index++;
				
            }
        });
		index = 0;
        $('div.tweets-share').each(function(){
            if (index < maxlength) {
				$(this).append('<div id="adspace'+index+'" class="adspace"></div><div style="float:left;"><a href="http://twitter.com/home?status='+encodeURIComponent(keywords[index].el)+' is The Word On The Tweet http://www.thewordonthetweet.com?t='+encodeURIComponent(keywords[index].el)+'" title="Click to share this post on Twitter" onClick="twt_click(\''+keywords[index].el+'\')" ><img src="images/social/twitter.png" alt="Share on Twitter"></a></div><div ><a name="fb_share_'+i+'" id="fb_share_'+i+'" type="button"  href="http://www.facebook.com/sharer.php?u=http://www.thewordonthetweet.com?t='+encodeURIComponent(keywords[index].el)+'&t='+encodeURIComponent(keywords[index].el)+' is The Word On The Tweet" onClick="fbs_click(\'http://www.thewordonthetweet.com?t='+keywords[index].el+'\',\''+keywords[index].el+' is The Word On The Tweet\')"><img src="images/social/facebook.png" alt="Share on Facebook" /></a></div>');
                
                index++;
				
            }
        });

        $.cookie('last_category', getCategory());
        loadTweets();
        $('.tweets-content').corner();
		
    }
}
function fbs_click(u,t) {
	
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=630,height=440');
	return false;
	}
function twt_click(t) {
	
	window.open('http://twitter.com/home?status='+encodeURIComponent(t)+' is The Word On The Tweet http://www.thewordonthetweet.com?t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=800,height=440');
	return false;
	}

$(document).ready(function() {
    $('body').removeClass('no-js');
    $('noscript').remove(); // Stupid IE8

    $('h1').corner(); // Stupid IE

    var d = new Date;
    var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    var oldDate = days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()];
    $('#current-date').attr('value', oldDate);
    
    loadCookies();

    $('#current-date').datepicker({
        onClose: function() {
            var newDate = $(this).val();
            if (newDate != oldDate) {
                firstweets();
            }
        },
        minDate: '-7d',
        maxDate: '+0d',
        altField: '#actual-date',
        altFormat: 'yy-mm-dd',
        dateFormat: 'D d MM'
    });


    $('#current-category').change(newCategory);

    newCategory();
    
    $('#current-location').click(function() {
        changeLocation(prompt('where do you want to go today?'));
    });

    $('form[name="suggest_keywords"]').submit(function() {
        $('input[name="add_category"]').val(getCategory());

        if ($('input[name="add_keywords"]').val().length) {
            return true;
        }

        alert('You have to type something first!');
        return false;
    });
});


