/*
 * Global variables (some must be set on page load) 
 */
var cookieEnabled = null;            /* Is persistent cookie available */
var latC = 52.22908744659406;        /* Initial latitude */
var lonC = 21.01311206817627;        /* Initial longitude */
var initZoom = 15;                   /* Initial zoom */
var trafficArray = new Array();      /* Array with traffic info objects */
var baseUrl = null;                  /* Base url context - set by server on page load */
var trafficButton = null;            /* Button to show/hide list */
var trafficIndicator = null;

/* Street type names */
var streetTypes = [                  
	"Droga szybkiego ruchu 1",
	"Droga szybkiego ruchu 2",
	"Droga szybkiego ruchu 3",
	"Droga krajowa",
	"G\u0142\u00F3wna droga lokalna", 
	"Zwyk\u0142a droga lokalna",
	"Uliczki osiedlowe",
	"Trasy zjazdy, wjazdy na drogi szybkiego ruchu, wiadukty",
	"Droga gruntowa, nieutwardzona",
	"Rondo"
];
/* Traffic type names */
var trafficTypes = [
	'Pe\u0142na przejezdno\u015B\u0107',
	'Ma\u0142e',
	'\u015Arednie',
	'Du\u017Ce',
	'Uporczywe korki'                
];        
//-----------------------------------------------------------------------------
//Globals
//Major version of Flash required
var requiredMajorVersion = 9;
//Minor version of Flash required
var requiredMinorVersion = 0;
//Minor version of Flash required
var requiredRevision = 28;
//-----------------------------------------------------------------------------

//FLASH

function check() {
	if ( hasProductInstall && !hasRequestedVersion ) {
		// DO NOT MODIFY THE FOLLOWING FOUR LINES
		// Location visited after installation is complete if installation is required
		var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
		var MMredirectURL = window.location;
		document.title = document.title.slice(0, 47) + " - Flash Player Installation";
		var MMdoctitle = document.title;

		AC_FL_RunContent(
				"src", "playerProductInstall",
				"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
				"width", "954px",
				"height", "400px",
				"align", "middle",
				"id", "MainTraffic",
				"quality", "high",
				"bgcolor", "#869ca7",
				"name", "MainTraffic",
				"allowScriptAccess","always",
				"type", "application/x-shockwave-flash",
				"pluginspage", "http://www.adobe.com/go/getflashplayer",
				"wmode", "transparent",
				"flashVars", "key=ABQIAAAAu2k314gmBerDgdxS9jpa5RSldWYbrYgqU-RmJBwkM0QwH7SlHxTYKPnIVn9B3P0L85fUrPIgmJbaSA&service=http://www.spoorle.com/korki/trafficArea.view"
		);
	} else if (hasRequestedVersion) {
		// if we've detected an acceptable version
		// embed the Flash Content SWF when all tests are passed
		AC_FL_RunContent(
			"src", "http://www.spoorle.com/korki/flex/MainTraffic",
			"width", "954px",
			"height", "400px",
			"align", "middle",
			"id", "MainTraffic",
			"quality", "high",
			"bgcolor", "#869ca7",
			"name", "MainTraffic",
			"allowScriptAccess","always",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer",
			"wmode", "transparent",
			"flashVars", "key=ABQIAAAAu2k314gmBerDgdxS9jpa5RSldWYbrYgqU-RmJBwkM0QwH7SlHxTYKPnIVn9B3P0L85fUrPIgmJbaSA&service=http://www.spoorle.com/korki/trafficArea.view"
		);
	} else {  // flash is too old or we can't detect the plugin
		var alternateContent = 'Alternate HTML content should be placed here. '
			+ 'This content requires the Adobe Flash Player. '
			+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
		document.write(alternateContent);  // insert non-flash content
	}
}

//-----------------------------------------------------------------------------



/**
 * Updates traffic box list - called from flex application.
 * @param {String} json - json response from servlet passed from map
 */
function updateTrafficFlexInvoke(json) {
	if(trafficIndicator) {
		trafficIndicator.style.display = 'none';
	}
	var jsonArray = json.evalJSON();
	trafficArray = new Array(jsonArray.traffic.length);
	for(var i=0; i<trafficArray.length; i++) {
		trafficArray[i] = jsonArray.traffic[i];
	}
	/* Sort array */
	trafficArray.sort(callbackSortFuncAlt);
	/* Update list */
	updateInfoUl(5);
}

/**
 * Shows popup window with track statistics for
 * given street id and name
 * @param {String} id
 * @param {String} name
 */
function showTracks(id, name) {
	window.location=baseUrl + '/streetInfo?streetId=' + id;
	/*
	var url = serverUrl + '/trafficArea.view?stats=' + id;
	return overlib(OLiframeContent(url, 510, 245, 'if2', 1, 'auto'),
				   WIDTH,510,
				   TEXTPADDING,0,
				   BORDER,2,
				   STICKY,
				   DRAGGABLE,
				   CLOSECLICK,
				   CAPTIONPADDING,4,
				   REF,id,
				   CAPTION, '<h3>' + name + '</h3> statistics - list of tracks:',
				   MIDX,0, 
				   MIDY,0,
				   STATUS,'');
	*/
}

/**
 * Updates info section about traffic on the map.
 * This is used at the main page (traffic section)
 * @param {Number} howMany max number of boxes in list, if null
 * 		show all
 */
function updateInfoUl(howMany) {
	var ul = document.getElementById('traffic_boxes');
	var lastLi = null;
	while(ul.childNodes.length > 2) {
		ul.removeChild(ul.firstChild);
	}
	var max;
	if(howMany && (howMany < trafficArray.length)) max = howMany;
	else max = trafficArray.length;
	for(var i=max-1; i>=0; i--) {		
		var el = document.createElement('li');
		var divBox = createBox(trafficArray[i].id, trafficArray[i].n);
		var tab = createTableToBox();
		/* First row of the table */
		var row = tab.insertRow(0);
	    /* Cell for a warn mark */
		var c = row.insertCell(0);
	    c.align = 'center';
	    c.className = 'tr_mark';
	    var img = null;
	    if(trafficArray[i].lv > 2) {
	    	img = document.createElement('img');
			img.src = './img/warn.gif';
			c.appendChild(img);
	    }
		/* Cell for a street name */
	    c = row.insertCell(0);
	    c.align = 'center';
	    c.className = 'tr_head';
	    c.innerHTML = trafficArray[i].n;
	    /* Cell for a thermometer mark */
	    c = row.insertCell(0);
	    c.rowSpan = 3;
	    c.align = 'center';
	    c.className = 'tr_term';
	    img = document.createElement('img');
	    img.src = './img/termometr' + trafficArray[i].lv + '.png';
	    c.appendChild(img);
	    /* Second row of the table */
		row = tab.insertRow(1);
		createTrafficInfoCell(row, 0, trafficArray[i]);
		/* Third row of the table */
		row = tab.insertRow(2);
		c = row.insertCell(0);
		c.colSpan = 2;
		c.align = 'right';
		c.style.paddingRight = '10px';
		c.style.paddingBottom = '10px';
		var link = document.createElement('a');
		link.innerHTML = 'Zobacz szczeg\u00F3\u0142y';
		link.href = baseUrl + '/streetInfo?streetId=' + trafficArray[i].id;//   '   javascript://nop/';
		//link.onclick = function() {showTracks(trafficArray[i].id, trafficArray[i].n); return false;};
		c.appendChild(link);
		/* Add this table do a div box */
		divBox.appendChild(tab);
		/* Add box to a list element */
		el.appendChild(divBox);
		/* Insert list element */
		ul.insertBefore(el, ul.firstChild);
	} 
	if(trafficButton) {
		if(howMany) {
			trafficButton.style.display = '';
			trafficButton.value = 'Zobacz wi\u0119cej';
			trafficButton.onclick = function() { updateInfoUl(); };
		} else {
			trafficButton.style.display = '';
			trafficButton.value = 'Ukryj';
			trafficButton.onclick = function() { updateInfoUl(5); };
		}		
	}
}

/**
 * Creates cell with information about traffic
 * @param row
 * @param index
 * @param info
 */ 
function createTrafficInfoCell(row, index, info) {
	var c = row.insertCell(0);
	c.colSpan = 2;
	c.align = 'left';
	c.className = 'tr_info';
	c.innerHTML = '<b>Typ ulicy: </b>' + streetTypes[info.st] + '<br>' + 
	              '<b>\u015Arednia pr\u0119dko\u015B\u0107: </b>' + info.avg + ' [km/h]<br>' + 
				  //'<b>Czas oczekiwania: </b>' + info.wt + ' [m]<br>' + 
				  //'<b>Liczba pojazdów: </b>' + info.cn + '<br>' +
				  '<b>Nat\u0119\u017Cenie ruchu: </b>';
	c.innerHTML += trafficTypes[info.v];			  	
}
 

/**
 * Creates table to put inside div box
 */
function createTableToBox() {
	var tab = document.createElement('table');
	tab.className = 'trInfo';
	tab.align = 'center';
	return tab;
}

/**
 * Creates box element for a list section with
 * given id and name
 * @param id
 * @param name
 */
function createBox(id, name) {
	var divBox = document.createElement('div');
	divBox.className = 'box';
	divBox.onmouseover = function() {this.className = "box_over";};
	divBox.onmouseout = function() {this.className = "box";};
	divBox.id = id;
	divBox.name = name;
	divBox.onclick = function() {showTracks(this.id, this.name);};
	return divBox;
}

/**
 * Creates cell in table row with given text
 */
function createCellRow(row, index, className, text) {
	var cell = row.insertCell(index);
	cell.className = className;
	cell.innerHTML = text;
	return cell;
}

/**
 * Writes a new cookie - map position and zoom,
 * called each time map changes view state (from flex application) 
 */
function updateCookie(lat, lng, zoom) {
	if(cookieEnabled) {
		writePersistentCookie('gmaps_position',zoom + '#' + 
			lat + '#' + lng, 'years', 1);
	}
}

/**
 * Initializes map params based on user's cookie
 */ 
function initCookie() {
	if(cookieEnabled) {
		var cookie = getCookieValue('gmaps_position');
		if(cookie) {
			var cookieArr = cookie.split('#');
			initZoom = parseInt(cookieArr[0]);
			latC = parseFloat(cookieArr[1]);
			lonC = parseFloat(cookieArr[2]);
		}
	}
}

/**
 * Returns initial zoom level for map - called from 
 * flex application
 * @return
 */
function getInitZoom() {
	return initZoom;
}

/**
 * Returns initial center latitude for map - called from 
 * flex application
 * @return
 */
function getLatC() {
	return latC;
}

/**
 * Returns initial center longitude for map - called from 
 * flex application
 * @return
 */
function getLngC() {
	return lonC;
}

/**
 * Returns base context name - called from flex map
 * @return
 */
function getBaseUrl() {
	return baseUrl;
}

/**
 * Prepares necessary variables (based on persistent cookie) to 
 * load flex map on page. If persistent cookie doesn't exists
 * creates new one.
 */
function initializeMain() {
	cookieEnabled = testPersistentCookie();
	initCookie();
	trafficButton = document.getElementById("traffic_more_button");
	trafficIndicator = document.getElementById("indicator");
}

/**
 * Sorting trafficArray which contains TrafficJson objects.
 * Compares by average speed value
 * @param a
 * @param b
 * @return
 */
function callbackSortFuncAlt(a,b){
	if(a.id == b.id){
 		return 0;
 	}
 	if(parseFloat(a.avg.replace(",", ".")) == parseFloat(b.avg.replace(",", "."))) return 0;
 	return (parseFloat(a.avg.replace(",", ".")) < parseFloat(b.avg.replace(",", "."))) ? -1 : 1;
} 
 
