var mapType = 'map';

function calcFuel(atstumas, kiekis)
{
	atstumas = atstumas.replace(/,/g, '.');
	kiekis = kiekis.replace(/,/g, '.');

	atstumas = parseFloat(atstumas);
	kiekis = parseFloat(kiekis);
	
	ats = (100*kiekis) / atstumas;
	
	ats = Math.round(ats*Math.pow(10,2))/Math.pow(10,2);
	
	document.getElementById('answer').innerHTML = (ats) + ' litrų 100 km.';
}

function loadUrl()
{
	var city = document.getElementById('city').value;
	var station = document.getElementById('station').value;
	var path = document.location.pathname;
	
	document.location.href = path+'?city='+city+'&station='+station;
}

function changeChart()
{
	var nuo = document.getElementById('nuo').value;
	var iki = document.getElementById('iki').value;
	var station = document.getElementById('station').value;
	var type = document.getElementById('type').value;
	
	/*var path = document.location.pathname;
	
	document.location.href = path+'?startDate='+nuo+'&endDate='+iki+'&station='+station+'&fuel='+type;
	*/
	
	chart = findSWF("my_chart");
	
	chart.reload('/Stations/stationsData/'+nuo+'/'+iki+'/'+type+'/'+station);

}

function findSWF(movieName)
{
	if(navigator.appName.indexOf("Microsoft")!= -1)
	{
		return window["ie_" + movieName];
	} else 
	{
		return document[movieName];
	}
}


function loadLeftMapBlock(city, street)
{
	/*
	if(!city)
		city = 0;
	
	if(!street)
		street = 0;
	*/
	var path = document.location.pathname;
	
	document.location.href = path+'?city='+city+'&station=0&street='+street+'#googleMap';
	/*
	clearAllMarkers();
	setcookie('filters', json_encode(new Array()), 7);
	
	jQuery(document).ready(function(){
		jQuery('#bottomLeft').load('/Stations/markBest/0/1/'+city+'/'+street);
	});
	*/
}

function clearAllMarkers()
{
	jQuery('#map1').jmap('clearOverlays');
}

function showOnMap(location, zoom, notClear, notCenter, icon, n)
{ 
	if(!n)
	{
		n = 1;
	}
		
	if(!notClear)
	{
		clearAllMarkers();
	}
	
	if(!zoom)
	{
		zoom = 12;
	}
	
    jQuery('#map1').jmap('SearchAddress', {
        'query': location,
        'returnType': 'getLocations',
        'countryCode': 'lt'
    }, function(result, options) {
    	
        var valid = Mapifies.SearchCode(result.Status.code);
        if (valid.success) {
            if(1==1){
	            jQuery.each(result.Placemark, function(i, point){
	            	if(i<3)
	            	{
		            	if(icon)
		            	{
		            		var sk = (parseInt($('#sk_'+n).html(), 10));
		            		if(sk>99)
		            		{
		            			url = '/Stations/placePic/'+icon+'/'+sk+'/big';
		            		} else
		            		{
		            			url = '/Stations/placePic/'+icon+'/'+sk;
		            		}

		            		ico = new GIcon(G_DEFAULT_ICON);
		                    ico.image = url;
		                    
		                    if(sk>99)
		                    {
		                    	ico.iconSize = new GSize(37,29);
		                    }else
		                    {
		                    	ico.iconSize = new GSize(21,29);
		                    }
		
		            		jQuery('#map1').jmap('AddMarker',{
		                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
		                        'pointHTML':point.address,
		                        'pointIcon': ico
		                        	
		                    });
		            	} else
		            	{
		            		jQuery('#map1').jmap('AddMarker',{
		                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
		                        'pointHTML':point.address
		                    });
		            	}
		                
		                if(!notCenter)
		                {
		                	jQuery('#map1').jmap('MoveTo', {'mapType':mapType,'mapZoom':zoom,'mapCenter':[point.Point.coordinates[1], point.Point.coordinates[0]]});
		                }
	            	}
	            });
            }
            
        } else {
            //alert(valid.message+' '+location);
        }
    });
    return false;   
}

function marks(type)
{
	var filters = getcookie('filters');
	jQuery('.'+type).toggleClass("active");
	
	if(type == 'degalai_95')
	{
		jQuery('#'+type).toggleClass('first95');
	} else if(type == 'degalai_98')
	{
		jQuery('#'+type).toggleClass('first98');
    } else if(type == 'degalai_dyzel')
    {
		jQuery('#'+type).toggleClass('firstD');
    } else if(type == 'degalai_dz')
    {
		jQuery('#'+type).toggleClass('firstDz');
    } else if(type == 'degalai_gas')
    {
		jQuery('#'+type).toggleClass('firstDujos');
    }
	
	if(filters.indexOf(type)<0)
	{
		filters = eval(filters);
		filters[filters.length] = type;
		filters = json_encode(filters);
		
	} else
	{
		filters = eval(filters);
		
		var tmp = new Array();
		x = 0;
		$.each(filters,function(i,item){ 
			if(item!=type)
			{
				tmp[x] = item;
				x++;
			}
		});
			
		filters = json_encode(tmp);
	}
	
	setcookie('filters', filters, 7);
		
	generateMarks();
}

function clearAllMarks()
{
	var types = new Array('degalai_95', 'degalai_98', 'degalai_dyzel', 'degalai_dz', 'degalai_gas');
	
	for(var i = 0; i<6; i++)
	{
		var filters = getcookie('filters');
		
		var type = types[i];
		
		jQuery('.'+type).removeClass("active");
	
		if(type == 'degalai_95')
		{
			jQuery('#'+type).removeClass('first95');
		} else if(type == 'degalai_98')
		{
			jQuery('#'+type).removeClass('first98');
	    } else if(type == 'degalai_dyzel')
	    {
			jQuery('#'+type).removeClass('firstD');
 		} else if(type == 'degalai_dz')
 		{
			jQuery('#'+type).removeClass('firstDz');
 		} else if(type == 'degalai_gas')
 		{
			jQuery('#'+type).removeClass('firstDujos');
 		}
	
		if(filters.indexOf(type)<0)
		{
			filters = eval(filters);
			filters[filters.length] = type;
			filters = json_encode(filters);
			
		} else
		{
			filters = eval(filters);
			
			tmp = new Array;
			x = 0;
			$.each(filters,function(i,item){ 
				if(item!=type)
				{
					tmp[x] = item;
					x++;
				}
			});
				
			filters = json_encode(tmp);
		}
	
		setcookie('filters', filters, 7);
		
		generateMarks();
	}
}

function generateMarks()
{
	clearAllMarkers();
	
	var filters = getcookie('filters');
	filters = eval(filters);

	$.each(filters,function(i,item){ 
		
		var tmp = getcookie(item);
		tmp = eval(tmp);
		
		$.each(tmp,function(x,location){

			var n = x+1;
			showOnMap(location, 7, true, true, item, n);
		
		} );
		
	} );
}

jQuery(document).ready(function(){

    jQuery('#map1').jmap('init', {'mapType':mapType,'mapCenter':[55.169438,23.881275],'mapZoom':7,'mapControl':'large'});

    //showOnMap('Europe, Lithuania', 7);
    /*
    jQuery('#address-submit-1').click(function(){
        jQuery('#map1').jmap('SearchAddress', {
            'query': jQuery('#address').val(),
            'returnType': 'getLocations'
        }, function(result, options) {
            
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
            jQuery.each(result.Placemark, function(i, point){
                jQuery('#map1').jmap('AddMarker',{
                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML':point.address,
                    });
                jQuery('#map1').jmap('MoveTo', {'mapType':mapType,'mapCenter':[point.Point.coordinates[1], point.Point.coordinates[0]]});
                });
            } else {
                jQuery('#address').val(valid.message);
            }
        });
        return false;   
    });
    */
});

function setcookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getcookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function deletecookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}

function json_encode(mixed_val) {
    // http://kevin.vanzonneveld.net
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: json_encode(['e', {pluribus: 'unum'}]);
    // *     returns 1: '[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]'
 
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */
    
    var value = mixed_val;
 
    var quote = function (string) {
        var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };
 
        escapable.lastIndex = 0;
        return escapable.test(string) ?
        '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
            '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' :
        '"' + string + '"';
    };
 
    var str = function(key, holder) {
        var gap = '';
        var indent = '    ';
        var i = 0;          // The loop counter.
        var k = '';          // The member key.
        var v = '';          // The member value.
        var length = 0;
        var mind = gap;
        var partial = [];
        var value = holder[key];
 
        // If the value has a toJSON method, call it to obtain a replacement value.
        if (value && typeof value === 'object' &&
            typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        
        // What happens next depends on the value's type.
        switch (typeof value) {
            case 'string':
                return quote(value);
 
            case 'number':
                // JSON numbers must be finite. Encode non-finite numbers as null.
                return isFinite(value) ? String(value) : 'null';
 
            case 'boolean':
            case 'null':
                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.
 
                return String(value);
 
            case 'object':
                // If the type is 'object', we might be dealing with an object or an array or
                // null.
                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.
                if (!value) {
                    return 'null';
                }
 
                // Make an array to hold the partial results of stringifying this object value.
                gap += indent;
                partial = [];
 
                // Is the value an array?
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.
 
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }
 
                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.
                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                    partial.join(',\n' + gap) + '\n' +
                    mind + ']' :
                    '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
 
                // Iterate through all of the keys in the object.
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
 
                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.
                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    };
 
    // Make a fake root object containing our value under the key of ''.
    // Return the result of stringifying the value.
    return str('', {
        '': value
    });
}



