/* wykonaj przy ladowaniu */
var selectedId;
var prev_hash;

function init()
{
    contResize();

    //licznik czekania na zaladowanie mapy dla ajaxa
    load_attempts = 0;
    mapState = 'loading...'

    var flashvars = {};
    var params = {};
    var attributes = {
        id: "map",
        name: "map"
    };
    var swf_map = "map_data/map"+swfModDate+".swf?"+mapUrl;
    //swfobject.embedSWF(swf_map, "map", "0", "0", "8.0.0", false, flashvars, params, attributes);
    var so = new SWFObject(swf_map, "map", "600", "600", "8", "#CCCC99");
    so.addVariable("displayPoi", "true");
    so.addParam("wmode", "window");
    so.write("map_swf");
	
    var myHistory;
    myHistory = new mapHistory();

    if(url_hash != '')
    {
        unFocus.History.addHistory(url_hash);
    }
		
    contResize();
}

/* ---------------------------------------------- HISTORIA MAPY ------------------------------------- */
function mapHistory() {
    // some application vars
    var stateVar = "", displayHere = document.getElementById("map_seeker_input");
	
    // This is the method that will recieve notifications from the History Keeper,
    // which will then update the state of the app.
    // :NOTE: This will be called when a new entry is added.
    // :NOTE: This will be called if another app on the page sets a history,
    //        so you will need to watch out for this, if you have more than
    //        one script using the history keeper, by doing some kind of
    //        check to make sure that the new hash belongs to this app.
    //        I wouldn't expect this to be a problem all that frequently.
    this.historyListener = function(historyHash) {
        if(historyHash)
        {
            var params = new Array();
            var prev_params = new Array();
            var tmp_params = new Array();
			
            tmp_params = historyHash.split('|');
            for(var i = 0; i < tmp_params.length; i++)
            {
                var temp = new Array();
                temp = tmp_params[i].split(':');
                if(temp[1])
                    params[temp[0]] = dashToSpace(temp[1]);
            }
            
            if(prev_hash)
            {
                tmp_params = prev_hash.split('|');
                for(var i = 0; i < tmp_params.length; i++)
                {
                    var temp = new Array();
                    temp = tmp_params[i].split(':');
                    prev_params[temp[0]] = dashToSpace(temp[1]);
                }
            }
			
            if(params['q'] && params['q'] != prev_params['q'])
            {
                prev_hash = historyHash;
                
//                if ( $.browser.webkit )
//                    displayHere.value = Url.decode(params['q']);
//                else
                    displayHere.value = params['q'];

                searchStreetCoord(params['r'],params['cl']);
            }
            else if(params['r'])
            {
                mapSetLocation(params['r']);
            }
            else if(!document.getElementById('map_warn'))
            {
                mapSetLocation(1);
            }
        }
    };
    unFocus.History.addEventListener('historyChange', this.historyListener);
    this.historyListener(unFocus.History.getCurrent());
};

function anchorAddHistory()
{
    var address = document.getElementById('map_seeker_input').value;
    address = seo_anchor(address);
    unFocus.History.addHistory("q:"+address);
}


/* --------------------------------------------------------------------------------------------------- */

/*-------------------------- parser seo ----------------------------*/

function seo_anchor(name)
{
    //    name = name.replace(/ê/g,'e');
    //    name = name.replace(/¿/g,'z');
    //    name = name.replace(/ó/g,'o');
    //    name = name.replace(/³/g,'l');
    //    name = name.replace(/æ/g,'c');
    //    name = name.replace(/¶/g,'s');
    //    name = name.replace(/¼/g,'z');
    //    name = name.replace(/ñ/g,'n');
    //    name = name.replace(/±/g,'a');
    //    name = name.replace(/Ê/g,'E');
    //    name = name.replace(/¯/g,'Z');
    //    name = name.replace(/Ó/g,'O');
    //    name = name.replace(/£/g,'L');
    //    name = name.replace(/Æ/g,'C');
    //    name = name.replace(/¦/g,'S');
    //    name = name.replace(/¬/g,'Z');
    //    name = name.replace(/Ñ/g,'N');
    //    name = name.replace(/¡/g,'A');
    name = name.replace(/[-]+/g,'_');
    //    name = name.replace(/[^a-zA-Z 0-9\/\.\(\)\-\_\']+/g,''); //
    name = name.replace(/^\s+|\s+$/g,'');
    name = name.replace(/\s+/g,'-');
    return name;
}
function dashToSpace(name)
{
    if(name === undefined) return name;

    name = name.replace(/-/g,' ');
    name = name.replace(/_/g,'-');
    return name;
}
/*------------------------------------------------------------------*/


/* zmiana wielkosci poszczegolnych konterow - gdy resizowane okno */
function contResize()
{
    var userAgent = navigator.userAgent;
    if(userAgent.search(/msie/i) != -1)
    {
        var recount_h = window.document.documentElement.clientHeight - 55;
    }
    else
    {
        var recount_h = window.innerHeight - 55;
    }

    if(recount_h < 250)
    {
        recount_h = 250;
    }
	
    document.getElementById("map_left_column").style.height = recount_h+"px";
    document.getElementById("map_right_column").style.height = recount_h+"px";
    document.getElementById("map_swf").style.height = recount_h+"px";
    document.getElementById("map-slim").style.height = recount_h+"px";
	
    //alert('total height:'+document.body.clientHeight+' / recount height:'+recount_h+' / scroll:'+document.getElementById("map_left_column").scrollHeight+' / height:'+document.getElementById("map_left_column").clientHeight);
    
    // poprawka buga w operze
    if(userAgent.search(/opera/i) != -1)
    {
        if(document.getElementById("map_left_column").clientHeight < document.getElementById("map_left_column").scrollHeight)
        {
	document.getElementById("map_left_column").style.width = "272px";
	recount_w = document.body.clientWidth - document.getElementById("map_left_column").scrollWidth -38;
	left = 289;
        }
        else
        {
	document.getElementById("map_left_column").style.width = "256px";
	recount_w = document.body.clientWidth - document.getElementById("map_left_column").scrollWidth -20;
	left = 273;
        }
    }
    else
    {
        if(document.getElementById("map_left_column").clientHeight < document.getElementById("map_left_column").scrollHeight)
        {
	document.getElementById("map_left_column").style.width = "272px";
	recount_w = document.body.clientWidth - document.getElementById("map_left_column").scrollWidth -28;
	left = 289;
        }
        else
        {
	document.getElementById("map_left_column").style.width = "256px";
	recount_w = document.body.clientWidth - document.getElementById("map_left_column").scrollWidth -12;
	left = 273;
        }
    }
 
	
    document.getElementById("map_swf").style.width = recount_w+"px";
    document.getElementById("map-slim").style.width = recount_w+"px";
    document.getElementById("map-slim").style.left = left+"px";
	
	
		
    width_swf = document.getElementById("map_swf").offsetWidth;
    height_swf = document.getElementById("map_swf").offsetHeight;
    width_over = document.getElementById("overlayBox").offsetWidth;
    height_over = document.getElementById("overlayBox").offsetHeight;
	
    if((width_swf - width_over)/2 > 0)
        pos_x = left + (width_swf - width_over)/2;
    else
        pos_x = left;
    if((height_swf - height_over)/2 > 0)
        pos_y = 50 + (height_swf - height_over)/2;
    else
        pos_y = 50;
		
    document.getElementById("overlayBox").style.left = pos_x+"px";
    document.getElementById("overlayBox").style.top = pos_y+"px";
	
    if(recount_w < 600) recount_w_m = 600;
    else if(recount_w >1500) recount_w_m = 1500;
    else recount_w_m = recount_w;
	
    if(recount_h < 370) recount_h_m = 370;
    else if(recount_h > 980) recount_h_m = 980;
    else recount_h_m = recount_h;

    if(thisMovie("map"))
    {
        document.getElementById("map").style.width = recount_w_m+"px";
        document.getElementById("map").style.height = recount_h_m+"px";
    }
    document.getElementById("map-slim-bg").style.width = recount_w_m+"px";
    document.getElementById("map-slim-bg").style.height = recount_h_m+"px"
}

function loadOverlay(page, title, width, height)
{
    thisMovie("map").getData();
    //thisMovie("map").positionMap(1,1,5);
    document.getElementById("map-slim").style.visibility = "visible";
    width_t = width-30;
    document.getElementById("overlayBoxTop").style.width = width+"px";
    document.getElementById("overlayBoxTitle").style.width = width_t+"px";
    document.getElementById("overlayBoxTitle").innerHTML = title;
    width_f = width-2;
    document.getElementById("overlayContent").innerHTML = '<iframe src="'+page+'" width="'+width_f +'" height="'+height+'" frameborder="0" scrolling="no">></iframe>';
    document.getElementById("overlayBox").style.visibility = "visible";
    document.getElementById("map_swf").style.visibility = "hidden";
    /*
	var swf_map = "map"+swfModDate+".swf?"+mapUrl;
	var so = new SWFObject(swf_map, "map", "600", "600", "8", "#CCCC99");
	so.addParam("wmode", "opaque");
	so.write("map_swf");
	*/
	
    contResize();
}
function unloadOverlay()
{
    /*
	thisMovie("map").getData();
	var swf_map = "map"+swfModDate+".swf?"+mapUrl;
	var so = new SWFObject(swf_map, "map", "600", "600", "8", "#CCCC99");
	so.write("map_swf");
	*/
    document.getElementById("map_swf").style.visibility = "visible";
    document.getElementById("map-slim").style.visibility = "hidden";
    document.getElementById("overlayBox").style.visibility = "hidden";
    contResize();
}
function setMapUrl(mU)
{
    mapUrl = mU;
}

function selectStreet(number)
{
    whatResult = (selectedId%2 == 0) ? 'A' : 'B';
    if(document.getElementById("result_"+selectedId))
        document.getElementById("result_"+selectedId).className= "map_seek_result_"+whatResult;
    selectedId = number;
    whatResult = (selectedId%2 == 0) ? 'A' : 'B';
    document.getElementById("result_"+selectedId).className= "map_seek_result_"+whatResult+" selected_result";
}

function mapSetLocation(focus_result)
{	
    if(mapState == 'loaded')
    {
        var address = document.getElementById('map_seeker_input').value;
        if(parseInt(focus_result) && document.getElementById('goto_'+parseInt(focus_result)) != null)
        {
            eval(document.getElementById('goto_'+focus_result).innerHTML);
        }
        else if(document.getElementById('goto_1') != null && !document.getElementById('map_warn'))
        {
            eval(document.getElementById('goto_1').innerHTML);
        }
        else if(document.getElementById('goto_0') != null && document.getElementById('map_warn'))
        {
            eval(document.getElementById('goto_0').innerHTML);
        }
    }
    else if(mapState == 'init' && load_attempts < 100)
    {
        setTimeout('mapSetLocation('+focus_result+')', 100);
        load_attempts++;
    }
    else if(load_attempts < 100)
    {
        setTimeout('mapSetLocation('+focus_result+')', 100);
        load_attempts++;
    }
	
}

/* komunikacja z flash/js */
function thisMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}

function positionMap(x,y,z,s,ox,oy) {
    thisMovie("map").positionMap(x,y,z,s,ox,oy);
}

function setMapState(str){
    mapState = str;
}

function changeInputAndRunSearch(address)
{
    document.getElementById('map_seeker_input').value = address;
    searchStreetCoord();
    return false;
}
function openMapLink() {
    thisMovie("map").copyLink();
//return false;
}
function openEdMapLink() {
    thisMovie("map").copyEdLink();
//return false;
}
function printMap() {
    thisMovie("map").printMap();
}


var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}