var xmlHttp
function UpdateData()
{
	if(iteration != 0)
		document.getElementById('newresultcount').innerHTML = "please wait";
	initialize();
	document.getElementById("refreshtext").innerHTML = "Refreshing...";
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	var url="/getdata.php?city="+cityID+"&since="+sinceID+"&sid="+Math.random();
	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
} 

var trenddata = "";
function stateChanged()
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		result = xmlHttp.responseText.split("<");
		
		result[0] = result[0].replace(/&lt;/g, "<");
		result[1] = result[1].replace(/&lt;/g, "<");
		result[2] = result[2].replace(/&lt;/g, "<");
		result[3] = result[3].replace(/&lt;/g, "<");
		
		sinceID = result[0];
		if(result[1] != "")
			document.getElementById("tweetdata").innerHTML="<ul>"+result[1]+"</ul>"+document.getElementById("tweetdata").innerHTML;
		var jsongrid = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(result[2].replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + result[2] + ')');
		if(iteration == 0)
			gridarray = jsongrid;
		else
		{
			document.getElementById('newresultcount').innerHTML='Found '+jsongrid.length+' new result(s)';
			gridarray = jsongrid.concat(gridarray);
		}
		var gridhtml = '';
		
		var i = 1;
		for(x in gridarray)
		{
			gridhtml += '<td><a title="'+gridarray[x][0]+'" href="'+gridarray[x][1]+'" target="_blank"><img height="48" width="48" src="'+gridarray[x][2]+'"/></a></td>';
			if(i++ % 6 == 0)
				gridhtml += '</tr><tr>';
			if(i>gridmax)
				break;
		}
		document.getElementById("griddata").innerHTML='<table class="grid"><tr>'+gridhtml+'</tr></table>';
		
		trenddata = result[3]+trenddata;
		cloudinput = keyword_extract(trenddata);
		generateCloud(cloudinput, false);
		
		
		iteration++;
		document.getElementById("refreshtext").innerHTML = "Refresh";
		setTimeout('UpdateData()', autorefreshtime*1000);
	}
}
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}
/*****************************************/

function arsort (inputArr, sort_flags)
{
    var valArr=[], keyArr=[], k, i, ret, sorter, that = this;

    switch (sort_flags)
	{
        case 'SORT_REGULAR':
        default:
            sorter = function (a, b)
			{
                if (a > b)
				{
                    return 1;
                }
                if (a < b)
				{
                    return -1;
                }
                return 0;
            };
            break;
    }

    var bubbleSort = function (keyArr, inputArr)
	{
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--)
		{
            for (j = 0; j <= i; j++)
			{
                ret = sorter(inputArr[j+1], inputArr[j]);
                if (ret > 0)
				{
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }
    };

    for (k in inputArr)
	{
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k];
    }
    try
	{
        bubbleSort(keyArr, valArr);
    }
	catch (e)
	{
        return false;
    }

    for (i = 0; i < valArr.length; i++)
	{
        inputArr[keyArr[i]] = valArr[i];
    }

    return true;
}
function trim(str)
{
	chars = "\\s";
	str = str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	str = str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	return str;
}

function array_count_values (array)
{
    var tmp_arr = {}, key = '', t = '';
    
    var __getType = function (obj)
	{
        var t = typeof obj;
        t = t.toLowerCase();
        if (t == "object")
		{
            t = "array";
        }
        return t;
    };

    var __countValue = function (value)
	{
        switch (typeof(value))
		{
            case "number":
                if (Math.floor(value) != value)
				{
                    return;
                }
            case "string":
                if (value in this)
				{
                    ++this[value];
                }
				else
				{
                    this[value] = 1;
                }
        }
    };
    
    t = __getType(array);
    if (t == 'array')
	{
        for ( key in array )
		{
            __countValue.call(tmp_arr, array[key]);
        }
    } 
    return tmp_arr;
}

function keyword_extract(text)
{
	text = text.toLowerCase();
	text = text.replace(/[:;,.?()'"\\/]/g, " ");
	
    commonWords ="about after all also am an and another any are as at be because been before being between both but by came can come could did do does each else for from get got has had he have her here him himself his how if in into is it its just like make many me might more most much must my never now of on only or other our out over re said same see should since so some still such take than that the their them then there these they this those through to too under up use very want was way we well were what when where which while who will with would you your near not nearby weight quot nbsp gt lt com amp var raquo middot ndash";
	commonWords += " http www bit tiny";
	commonWords = commonWords.toLowerCase();
	commonWords = commonWords.split(" ");
	words = text.split(" ");
	keywords = new Array();
	
	for(value in words)
	{
		v = words[value];
		v = trim(v);
        common = false;
        if (v.length >= 3)
		{
            for(commonWord in commonWords)
			{
                if (commonWords[commonWord] == v)
				{
                    common = true;
                }
            }
            if(common != true)
			{
                keywords[keywords.length+1] = v;
            }
        }
        else
		{
        }
    }

    keywords = array_count_values(keywords);
	arsort(keywords);
	output = "";
	i = 1;
    for (key in keywords)
	{
        if (keywords[key] > 0)
		{
            output += keywords[key]+","+key+"\n";
        }
		if(i++==maxtagitems)
			break;
    }
	return output;
}

//text = "The twelve, o!'\" clock project marketing data suggests we should hire twelve project marketing graduates to work on twelve marketing concepts to be presented to the twelve marketing project managers at the project marketing meeting.";
//cloudinput = keyword_extract(text);
//document.write(cloudinput);

function getFontSize(min,max,val) 
{
	return Math.round((100.0*(1.0+(1.5*val-max/2)/max)));
}

function generateCloud(txt, logarithmic) 
{
	var lines = txt.split(/\r?\n/);
	var min = 10000000000;
	var max = 0;
	for(var i=0;i<lines.length;i++)
	{
		var line = lines[i];
		var data = line.split(/,/);
		if(data.length != 2)
		{
			lines.splice(i,1);
			continue;
		}
		data[0] = parseFloat(data[0]);
		lines[i] = data;
		if(data[0] > max) 
		max = data[0];
		if(data[0] < min)
		min = data[0];
	}

	lines.sort(function (a,b) 
	{
		var A = a[1].toLowerCase();
		var B = b[1].toLowerCase();
		return A>B ? 1 : (A<B ? -1 : 0);
	});

	var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
	if(logarithmic)
	{
		max = Math.log(max);
		min = Math.log(min);
	}
	for(var i=0;i<lines.length;i++)
	{
		var val = lines[i][0];
		if(logarithmic) val = Math.log(val);
		var fsize = getFontSize(min,max,val);
		html += " <a target='_blank' href='http://search.twitter.com/search?q="+encodeURIComponent(lines[i][1])+"' style='font-size:"+fsize+"%;' title='"+lines[i][0]+" times'>"+lines[i][1]+"</a> ";
	}
	html += "</div>";
	var cloud = document.getElementById("cloud");
	cloud.innerHTML = html;
}