JSON_REQUESTS_PATH = "dispatcher";
ADDR_HINTS_MAX_HEIGHT = 210;
YP_BASE_URL = 'http://www.pf.pl/serwis/';

var search_nearest;
var trace_route;

var last_msg_timeout;
var msg_delay = 8;
var mvfa;

var page_bottom_margin = 4;

var search_nearest_what;
var search_nearest_where;
var search_nearest_where_location;
var search_nearest_new_page;

var search_results_list_animator;

var is_mouse_over_simulated = false;

var nearest_alt_categories = [];
var my_places_count = 0;
var my_places = [];

var page_name="Szukaj w pobliżu";

var adsList = [];
var adsListById = [];
var basePOIsList = []
var basePOIsListById = [];
var prev_adverts_body = "";

var vcard_visible = false;
var vcard_show = true;
var vcard_flash_data = [];

var locations_meta = {};


swf_initialized = false;

var menu_route = {};
var menu_search = {};

var printdata = [];

var adverts_box_visible = false;

var routeHintTimeoutHandler;
var sidebar_state;

var dir_pois = [];
var dir_detailed_pois = [];

var sidepanel_state_before_MOP;

var search_nearest_results_visible = 'none';

var last_succesfull_search_params = [];

var eventMapper = new EventMapper();
var linkHereDB = new LinkHereDB();

function switchtopage(panel) {
    var pages = new Array();
    pages[0] = 'search_nearest';
    pages[1] = 'trace_route';

    for (ctrl in pages) {
        if (pages[ctrl] == panel) {
            addElementClass(pages[ctrl],"sidebar_item_active");
            removeElementClass(pages[ctrl],"sidebar_item");
        } else {
            addElementClass(pages[ctrl],"sidebar_item");
            removeElementClass(pages[ctrl],"sidebar_item_active");
        }
    }
}

function onPOIMouseOver(type,pid) {
    var cbox;
    var topbox;
    if (type=='poi-s' && !is_mouse_over_simulated && (page_name == 'Szukaj w pobliżu')) {
        if (vcard_visible!=true) {
            cbox = $('companybox_'+pid);
            topbox = $('results_box');
            addElementClass('companybox_'+pid,'wynik_styl_1');
            removeElementClass('companybox_'+pid,'wynik_styl_2');
            if(!isIE()){
                search_results_list_animator.makeVisibleYPart(cbox.offsetTop-185,cbox.offsetHeight+6);
            } else {
                search_results_list_animator.makeVisibleYPart(cbox.offsetTop+210,cbox.offsetHeight+6);
            }
        }
    } else if (type=='poi-i' && !is_mouse_over_simulated && (page_name == 'Zaplanuj swoją trasę')) {
        cbox = $('route_hint_'+pid);
        topbox = $('route_itenary');
        addElementClass('route_hint_'+pid,'tr_wynik_styl_1');
        removeElementClass('route_hint_'+pid,'tr_wynik_styl_2');
        if(!isIE()){
            trace_route_results_list_animator.makeVisibleYPart(cbox.offsetTop-185,cbox.offsetHeight+6);
        } else {
            trace_route_results_list_animator.makeVisibleYPart(cbox.offsetTop-3,cbox.offsetHeight+6);
        }

    }
}

function onPOIMouseOut(type,pid) {
    if (type=='poi-s') {
        if (page_name == "Szukaj w pobliżu") {
            if (vcard_visible!=true) {
                removeElementClass('companybox_'+pid,'wynik_styl_1');
                addElementClass('companybox_'+pid,'wynik_styl_2');
            }
        }
    }
    if (type=="poi-i") {
        if (page_name == "Zaplanuj swoją trasę") {
            if ($('route_hint_'+pid)) {
                removeElementClass('route_hint_'+pid,'tr_wynik_styl_1');
                addElementClass('route_hint_'+pid,'tr_wynik_styl_2');
            }
        }
    }
}

function maintainSession() {
    _def = loadJSONDoc(JSON_REQUESTS_PATH,
    {
        method: "MaintainSession"
    });
    _def.addCallbacks(onSessionStateResponse,onSessionStateResponseFail);
}

function onSessionStateResponse(response) {
    if (response.token && response.token.value) {
        user_session = response.token.value;
        setTimeout(maintainSession,30000);
    } else {
        user_session = '';
    }
}

function onSessionStateResponseFail() {
}

function onContactsAdd(company,category) {
    _def = loadJSONDoc(JSON_REQUESTS_PATH,
    {
        method: "ContactsAdd",
        companyId: company,
        categoryId: category
    });
    _def.addCallbacks(onContactsAddResponse,onContactsAddResponseFail);
    setMessage("Proszę czekać.");
    $('status_messages').style.color= '#0000ff';
}

function onContactsAddResponse(response) {
    setMessage(response.msg,msg_delay);
    $('status_messages').style.color= '#0000ff';
}

function onContactsAddResponseFail() {
    setMessage("Przepraszamy, błąd serwera. Nie udało się zapamiętać kontaktu.",msg_delay);
    $('status_messages').style.color= '#0000ff';
}

function onLinkOpen(href, target) {
    if(target=='' || target==undefined){
        target='_self';
    }
    document.forms['exturl'].action = href;
    document.forms['exturl'].submit();
}

function configureSWF() {
    if (!swf_initialized) {
        setTimeout(function() {
            //mvfa.pois_request_updates('poi-b',5.0,0.4,onFetchPOIsRegionDemultiplexer);
            mvfa.pois_request_updates('poi-1',5.0,0.4,onFetchPOIsRegionDemultiplexer); // interface needs rebuild
            mvfa.pois_request_updates('poi-2',5.0,0.4,makeTourInfo);
            mvfa.set_cb("pm_mouse_over",onPOIMouseOver);
            mvfa.set_cb("pm_mouse_out",onPOIMouseOut);
            mvfa.set_cb("pm_poi_move",onPOIMoved);
            mvfa.set_cb("pm_poi_renumber",onUpdateVisibleAds);
            mvfa.set_cb("mv_scale",onScaleChange);
            mvfa.set_cb("ext_linkopen",onLinkOpen);
            mvfa.set_cb("mva_center", onCenterMapAction);
            mvfa.set_cb("link_here_open", onLinkHere);
            mvfa.set_cb("link_here_submit", onLinkHereSubmit);
            mvfa.set_cb("full_screen", onFullScreen);
            mvfa.set_cb("print_event", onPrint);
            mvfa.set_cb("get_hash", getHash);
            //mvfa.set_cb("switch_agregate_route_pois")
            //mvfa.set_cb("get_vector_route_data", makeVectorRequest);
            menu_route.start = [mvfa.pois_menu_add("poi-r",false,"Zaznacz początek trasy",trace_route.onRouteMarkStart),false,true];
            menu_route.via_add = [mvfa.pois_menu_add("poi-r",false,"Zaznacz punkt pośredni",trace_route.onRouteMarkVia),false,true];
            menu_route.via_remove = [mvfa.pois_menu_add("poi-r",false,"Usuń punkt pośredni",trace_route.onRemoveRouteMarkVia),false,false];
            menu_route.end = [mvfa.pois_menu_add("poi-r",false,"Zaznacz koniec trasy",trace_route.onRouteMarkStop),false,true];
            menu_route.find = [mvfa.pois_menu_add("poi-r",false,"Znajdź trasę",trace_route.onSubmitTraceRoute),false,true];
            menu_route.remove = [mvfa.pois_menu_add("poi-r",true,"Usuń punkt trasy",trace_route.onRouteMarkRemove),true,true];
            menu_search.select = [mvfa.pois_menu_add("poi-s",false,"Wybierz lokalizację",onPlaceOnMapSelected),false,true];
            SetMenuState(menu_route,false);
            SetMenuState(menu_search,false);
            mvfa.pois_enable('poi-r',true);
            swf_initialized = true;
        },100);
    }
}

function SetMenuState(menulist,state) {
    if (state) {
        for(key in menulist) {
            mvfa.pois_menu_enable('poi-r', menulist[key][1], menulist[key][0], menulist[key][2]);
        }
    } else {
        for(key in menulist) {
            mvfa.pois_menu_enable('poi-r', menulist[key][1], menulist[key][0], false);
        }
    }
}

function onGetAddressFromPointResponse(response) {
    var val = response.location.address_full;
    var listener = eventMapper.getListener(['mv-pois',response.action,response.poi_type,response.poi_id].join('.'));
    if (listener != undefined) {
        listener(response.location,response.poi_type,response.poi_id);
    }
    if(page_name == "Szukaj w pobli\u017cu"){
        $('nearest_submit').focus();
    } else {
        $('trace_route_submit').focus();
    }
}

function onCenterMapAction() {
    setTimeout(function () {
        var listener = eventMapper.getListener('mv-pois.map-center-action');
        if (listener != undefined) {
            listener();
        }
    },100);
}


function onGetAddressFromPointResponseFail() {
}


// !!! do przeniesienia do SearchNearestControl
function onPlaceOnMapSelected(poi_type, ref_coords) {
    var _def = loadJSONDoc(JSON_REQUESTS_PATH,
    {
        method: "GetAddressFromPoint",
        action: "update",
        poi_type: 'poi-r',
        poi_id: 'search-nearest-center',
        x92: ref_coords[0],
        y92: ref_coords[1]
    });
    _def.addCallbacks(onGetAddressFromPointResponse,onGetAddressFromPointResponseFail);
}


function onPOIMoved(poi_type, poi_id) {
    setTimeout(function() {
        poi_data = mvfa.pois_s_get(poi_type, poi_id);

        _def = loadJSONDoc(JSON_REQUESTS_PATH,
        {
            method: "GetAddressFromPoint",
            poi_type: poi_type,
            poi_id: poi_id,
            action: 'update',
            x92: poi_data[0],
            y92: poi_data[1]
        });
        _def.addCallbacks(onGetAddressFromPointResponse,onGetAddressFromPointResponseFail);
    },100);
}

function onScaleChange(oldscale,newscale) {
    if (page_name == "Zaplanuj swoją trasę") {
        if ((oldscale>=ROUTE_DETAILS_MAX_SCALE_LEVEL) && (newscale<ROUTE_DETAILS_MAX_SCALE_LEVEL)) {
            if (dir_pois.length>0) {
                mvfa.pois_clear('poi-i');
                mvfa.pois_set('poi-i',dir_pois);
            }
        } else if ((oldscale<ROUTE_DETAILS_MAX_SCALE_LEVEL) && (newscale>=ROUTE_DETAILS_MAX_SCALE_LEVEL)) {
            if (dir_detailed_pois.length>0) {
                mvfa.pois_clear('poi-i');
                mvfa.pois_set('poi-i',dir_detailed_pois);
            }
        }
    }
}


function onUpdateVisibleAds(poi_type,plist) {
    if (poi_type=='poi-1') {
        setTimeout( function() {
            adverts_body = "";
            var ie6Prefix = isIE6() ? 's_' : '';
            for (pid in plist) {
                poi = plist[pid][0];
                nr = plist[pid][1];
                adverts_body += '<div style="float: left; padding-top: 15px; text-align: center; width: 120px;"><img class="ads_nr_points" style="float: left; padding: 15px 5px;" src="_gfx/geo3/'+ie6Prefix+'o'+nr+'.png" alt="'+nr+'" />';
                if (adsListById[poi] && adsListById[poi].adUrl) {
                    adverts_body += '<img style="margin: 0px 5px 20px 0px;" src="_geo3logo/'+escape(adsListById[poi].adUrl)+'" alt="'+adsListById[poi].name+'" />';
                }
                adverts_body +='</div>';
            }
            if (prev_adverts_body != adverts_body) {
                $('adverts_placeholder').innerHTML = adverts_body;
                prev_adverts_body = adverts_body;
            }
            if (adverts_body=="") {
                makeInvisible('adverts_placeholder');
                makeVisible('adverts_replacement');
            } else {
                makeInvisible('adverts_replacement');
                makeVisible('adverts_placeholder');
            }
        },50);
    }
}

function onFetchPOIsRegionDemultiplexer(poi_type,s,bbox) {
    if (poi_type == 'poi-1') {
        onFetchNewAdsRegion(poi_type,s,bbox);
    } else if (poi_type == 'poi-b') {
        onFetchNewBasePOIsRegion(poi_type,s,bbox);
    }
}

function onFetchNewAdsRegion(poi_type,s,bbox) {
    if ((s!=14) && (s!=13)) {
        setTimeout(partial(function(s,bbox) {
            mvfa.pois_clear('poi-1');
            mvfa.pois_set('poi-1',[],s,bbox);
        },s,bbox), 50);
    } else {
        _def = loadJSONDoc(JSON_REQUESTS_PATH,
        {
            method: "FetchAds",
            left: bbox[0],
            top: bbox[1],
            right: bbox[2],
            bottom: bbox[3],
            scale: s
        }
        );
        _def.addCallbacks(onFetchNewAdsResponse,onFetchNewAdsResponseFail);
    }
}

function onFetchNewAdsResponse(response) {
    adsList = response.ads;
    for  (adsCnt in adsList) {
        adsListById[adsList[adsCnt].adId] = adsList[adsCnt];
    }
    clearMessage();
    clearMessage('route_status_messages');
    mvfa.pois_clear('poi-1');
    mvfa.pois_set('poi-1',response.mapdata,response.scale,response.bbox);
}

function onFetchNewAdsResponseFail() {
    mvfa.pois_clear('poi-1');
    mvfa.pois_set('poi-1',[],1,[]);
}

function onFetchNewBasePOIsRegion(poi_type,s,bbox) {
    if ((s!=14) && (s!=13)) {
        setTimeout(partial(function(s,bbox) {
            mvfa.pois_clear('poi-b');
            mvfa.pois_set('poi-b',[],s,bbox);
        },s,bbox), 50);
    } else {
        _def = loadJSONDoc(JSON_REQUESTS_PATH,
        {
            method: "FetchBasePOIs",
            left: bbox[0],
            top: bbox[1],
            right: bbox[2],
            bottom: bbox[3],
            scale: s
        });
        _def.addCallbacks(onFetchBasePOIsResponse,onFetchBasePOIsResponseFail);
    }
}

function onFetchBasePOIsResponse(response) {
    mvfa.pois_clear('poi-b');
    mvfa.pois_set('poi-b',response.mapdata,response.scale,response.bbox);
}

function onFetchBasePOIsResponseFail(response) {
    mvfa.pois_clear('poi-b');
    mvfa.pois_set('poi-b',[],1,[]);
}

function onSearchNearestPanel() {
    linkHereDB.type = page_name = "Szukaj w pobliżu";
    switchtopage('search_nearest');
    makeInvisible('route_options');
    makeInvisible('trace_route_form');
    makeInvisible('route_itenary');
    makeInvisible('route_header');
    makeInvisible('route_status_messages');
    makeInvisible('route_status_msg_border');
    makeInvisible('route_footer');
    //mvfa.pois_cancel_updates('poi-2');
    mvfa.pois_clear('poi-2');
    mvfa.pois_set('poi-2',[],mvfa.get_scale(),[0,0,0,0]);
    mvfa.pois_clear('poi-1');
    mvfa.pois_set('poi-1',[],mvfa.get_scale(),[0,0,0,0]);
    mvfa.route_off();
    mvfa.pois_clear("poi-i");
    mvfa.pois_enable('poi-i',false);
    mvfa.enable_vector_route(false);
    SetMenuState(menu_route,false);

    search_nearest.setPanelVisible(true);
    if (vcard_show && vcard_flash_data[0]) {
        makeVisible('vcard_box');
        vcard_visible = true;
        mvfa.pois_clear("poi-s");
        mvfa.pois_enable("poi-s", true);
        mvfa.pois_set("poi-s", vcard_flash_data);
        var route_target = new Location();
        route_target.update(vcard_flash_data[0][5][4][0][2]);
        mvfa.set_coords(vcard_flash_data[0][0], vcard_flash_data[0][1], 13);
    }
    onResize();

    return false;
}

function onTraceRoutePanel() {
    linkHereDB.type = page_name = "Zaplanuj swoją trasę";
    if (vcard_visible && vcard_flash_data[0]) {
        var tmp = vcard_flash_data[0][5][4][0][2].address_struct;
        var ad = tmp.city;
        if (tmp.street) {
            ad += ', ul. '+tmp.street;
            if (tmp.houseno) {
                ad += ' '+tmp.houseno;
            }
        }
        $('trace_route_to_where').value = ad;
    }
    //mvfa.pois_cancel_updates('poi-2');
    switchtopage('trace_route');
    mvfa.pois_clear('poi-2');
    mvfa.pois_set('poi-2',[],mvfa.get_scale(),[0,0,0,0]);
    mvfa.pois_clear('poi-1');
    mvfa.pois_set('poi-1',[],mvfa.get_scale(),[0,0,0,0]);
    search_nearest.setPanelVisible(false);
    trace_route.setPanelVisible(true, search_nearest.getSearchLocation(), $('search_nearest_where').value );
    makeInvisible('search_form');
    mvfa.enable_vector_route(true);
    clearVCardData(true);
    onResize();
    //mvfa.pois_request_updates('poi-2',5.0,0.4,makeTrafficIssues);
    return false;
}

function onPrint() {
    setTimeout( function() {
        coords = mvfa.get_coords();
        scale = mvfa.get_scale();
        url = 'wydruk.php?s='+scale+'&x='+coords[0]+'&y='+coords[1];
        pwnd = window.open(url, "", 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,fullscreen=no,channelmode=no,width=608,height=610,top=10,left=20');
    },100);
    return false;
}

function clearVCardData(onlyVisible) {
    makeInvisible('vcard_box');
    vcard_visible = false;
    if (!onlyVisible) {
        vcard_show = false;
    }
}

function onFullScreen() {
    if (isVisible('header')) {
        sidebar_state = isVisible('sidebar');

        if (sidebar_state) {
            onSwitchSidepanel();
        }

        makeInvisible('header');
        makeInvisible('nav');
        makeInvisible('btn_switch_sidepanel_a');
        $('mva').style.marginTop = '2px';
    } else {
        makeVisible('header');
        makeVisible('nav');
        if (!isVisible('sidebar') && sidebar_state) {
            onSwitchSidepanel();
        }
        makeVisible('btn_switch_sidepanel_a');
        $('mva').style.marginTop = '0px' ;
    }
    onResize();
}

function onSwitchSidepanel() {
    if (isVisible('sidebar')) {
        makeInvisible('sidebar');
        makeInvisible('menu_right');
        $('flash').style.margin = '0px';
        $('bottom_panel').style.margin = '0px 0px 0px 0px';
        $('btn_switch_sidepanel').style.left = '3px';
        $('btn_switch_bottom_panel').style.left = '20px';
        $('btn_switch_sidepanel').style.background = "url(_gfx/button-left-hide.gif) no-repeat left top";
    } else {
        makeVisible('sidebar');
        makeVisible('menu_right');
        if (isIE6()) {
            $('flash').style.margin = '0px 0px 0px  296px';
            $('bottom_panel').style.margin = '0px 0px 0px 296px';
            $('mva_flash_placeholder').style.width ='99%';

        } else {
            $('flash').style.margin = '0px 0px 0px 296px';
            $('bottom_panel').style.margin = '0px 0px 0px 296px';
        }
        $('btn_switch_sidepanel').style.left = '293px';
        $('btn_switch_bottom_panel').style.left = '320px';
        $('btn_switch_sidepanel').style.background = "url(_gfx/button-left-show.gif) no-repeat left top";
    }
    onResize();
}

function onSwitchBottompanel() {
    if (isVisible('bottom_panel')) {
        makeInvisible('bottom_panel');
        $('btn_switch_bottom_panel').style.background = "url(_gfx/button-bottom-hide.gif) no-repeat left top";
        //$('btn_switch_bottom_panel').style.height = "14px";
        $('btn_switch_bottom_panel').style.marginTop = "3px";

    } else {
        makeVisible('bottom_panel');
        $('btn_switch_bottom_panel').style.background = "url(_gfx/button-bottom-show.gif) no-repeat left top";
        //$('btn_switch_bottom_panel').style.height = "18px";
        $('btn_switch_bottom_panel').style.marginTop = "0px";
    }
    onResize();
}

function onResize() {
    var winSize;
    var hborders = 9;
    if (isVisible('header')){
        hborders = hborders + elementDimensions('header').h;
    //hborders = hborders + elementDimensions('menu').h;
    }
    if (isVisible('nav')) {
        hborders = hborders + elementDimensions('nav').h;
    //hborders = hborders + elementDimensions('menu').h;
    }
    winSize = getViewportDimensions();

    if(isIE()){
        var flash_bottom_margin
        = page_bottom_margin+(isVisible('bottom_panel') ? elementDimensions('bottom_panel_lframe').h: 0);
    } else {
        var flash_bottom_margin
        = page_bottom_margin+(isVisible('bottom_panel') ? elementDimensions('bottom_panel').h: 0);
    }

    if(isVisible('bottom_panel') && !isIE()){
        $('mva').style.height = Math.max(250,(winSize.h - hborders - flash_bottom_margin + 7))+'px';
    } else {
        $('mva').style.height = Math.max(250,(winSize.h - hborders - flash_bottom_margin - 12))+'px';
    }
    //$('btn_switch_bottom_panel').style.width = elementDimensions('flash').w-30+'px';

    if (isVisible('sidebar')) {
        var header_size;
        if (isVisible('nav')){
            hborders = hborders - elementDimensions('nav').h;
        }
        $('sidebar').style.height = Math.max(342,(winSize.h - hborders - page_bottom_margin + 13))+'px';

        if (isVisible('results_box')) {
            header_size = elementDimensions('header-logo').h+10; //10 - margin-bottom size
            $('sidebar_inner').style.height = (elementDimensions('sidebar').h
                - header_size
                -3)+'px';
        }
        if (isVisible('route_itenary')) {
            header_size = elementDimensions('header-logo').h+10; //10 - margin-bottom size
            $('sidebar_inner').style.height = (elementDimensions('sidebar').h
                - header_size
                -3)+'px';
        }
        if (isIE6()) {
            $('flash').style.margin = '0px 0px 0px 296px';
            $('bottom_panel').style.margin = '0px 0px 0px 296px';
            $('mva_flash_placeholder').style.width ='99%';

            removeElementClass('stop_trace_route_form', 'label');
            removeElementClass('start_trace_route_form', 'label');
            addElementClass('stop_trace_route_form', 'labelie6');
            addElementClass('start_trace_route_form', 'labelie6');

            removeElementClass('dynM1', 'dynM1other');
            addElementClass('dynM1', 'dynM1ie6');
        } else {
            $('flash').style.margin = '0px 0px 0px 296px';
            $('bottom_panel').style.margin = '0px 0px 0px 296px';
        }
    }
}

function setCallbacks() {
    var panels = new Array();

    window.onresize = onResize;

    $("search_nearest_a").onclick = onSearchNearestPanel;

    search_nearest = new SearchNearestControl("nearest_submit");
    trace_route = new TraceRouteControl();


    search_results_list_animator = new ResultsBoxScroller('sidebar_inner');
    trace_route_results_list_animator = new ResultsBoxScroller('sidebar_inner', 120);

    $("btn_switch_sidepanel_a").onclick = onSwitchSidepanel;
    $("btn_switch_bottom_panel_a").onclick = onSwitchBottompanel;

    $('search_nearest_where').onfocus = function () {
        this.select();
    };
    $('search_nearest_what').onfocus = function () {
        this.select();
    };

    if (Cookies.get('TOKEN_COOKIE')) {
        maintainSession();
    }

    onResize();
}

function setMessage(msg, timeout, message_place) {
    makeInvisible('advert_box');
    if (message_place == undefined) {
        message_place = 'status_messages';
        message_place_border = 'status_msg_border';
    } else if (message_place=='route_status_messages') {
        message_place_border = 'route_status_msg_border';
    }

    if (msg == 'Proszę czekać.') {
        makeInvisible('advert_box');
        makeInvisible('search_filter_list_box');
        makeInvisible('search_nearest_results_box_header');
        makeInvisible('status_messages');
        makeInvisible('status_msg_border');
        makeVisible('please_wait_box');
    } else {
        makeInvisible('please_wait_box');
        makeVisible(message_place_border);
        makeVisible(message_place);

        if (last_msg_timeout!=undefined) {
            clearTimeout(last_msg_timeout);
            last_msg_timeout = undefined;
        }
        $(message_place).innerHTML = msg;
        if ((timeout!=undefined) && (timeout>0)) {
            last_msg_timeout = setTimeout(clearMessage,timeout*1000, message_place);
        }
    }
    onResize();
}

function clearMessage(message_place) {
    if (message_place == undefined) {
        message_place = 'status_messages';
    }
    $(message_place).innerHTML = '';

    //makeInvisible('route_status_msg_border');

    clearTimeout(last_msg_timeout);
    makeInvisible('please_wait_box');
    onResize();
}

function initSetCallbacks() {
    if ($("mva")!=undefined) {
        mvfa = new mv.MVA("mva");
        mvfa.set_init_cb(configureSWF);
    } else {
        setTimeout(initSetCallbacks,100);
    }
}

function afterInit() {
    if (swf_initialized==true) {
        if ($('init_run_trace_route') && getNodeAttribute('init_run_trace_route','value')) {
            setTimeout(trace_route.onSubmitTraceRoute,200);
        }
        if ($('init_run_search_nearest') && getNodeAttribute('init_run_search_nearest','value')) {
            setTimeout(search_nearest.onSubmitNearestNewSearch,200);
        }
        if ($('init_trace_route_to') && getNodeAttribute('init_trace_route_to','value')) {
            trace_route.routeToPointAction(new Location(evalJSON($('init_trace_route_to').value)));
        }
        if ($('init_trace_route_from') && getNodeAttribute('init_trace_route_from','value')) {
            trace_route.routeFromPointAction(new Location(evalJSON($('init_trace_route_from').value)));
        }

        var def_panel = getNodeAttribute('init_def_panel','value');
        if (def_panel == 'TraceRoute') {
            onTraceRoutePanel();
        } else {
            var showCity = '';
            onSearchNearestPanel();
            showCity = /(.*)#miasto:(.+)/.exec(document.URL);
            if (showCity==null) {
                showCity = /(.*)\/miasto-(.+)\.html/.exec(document.URL);
            }
            if (showCity != null) {
                showCity = showCity[2].replace(/\+/gi," ");
                try {
                    $('search_nearest_where').value = decodeURIComponent(showCity);
                } catch (error) {
                    $('search_nearest_where').value = unescape(showCity);
                }
                search_nearest.onSubmitNearestNewSearch();
            }
        }
        $('status_messages').innerHTML = '';
        $('init_status_messages').innerHTML = '';
        makeInvisible('border_init_status_messages');
        if(linkHereDB.isFromLink()){
            linkHereDB.performStep();
        }
    } else {
        setTimeout(afterInit,100);
    }
}

function turnOffSidepanel() {
    sidepanel_state_before_MOP = isVisible('sidebar');
    if(sidepanel_state_before_MOP==true){
        makeInvisible('menu_right');
        makeInvisible('sidebar');
        $('flash').style.margin = '0px';
        $('bottom_panel').style.margin = '0px 0px 0px 0px';
        //$('btn_switch_sidepanel_img').src = "_gfx/zwin_panel_l.png";
        $('btn_switch_sidepanel').style.right = '1px';
        $('btn_switch_bottom_panel').style.left = '20px';
    }
    onResize();
}

function recallSidepanelState() {
    makeVisible('menu_right');
    makeVisible('sidebar');
    $('flash').style.margin = '0px 0px 0px 296px';
    $('bottom_panel').style.margin = '0px 0px 0px 296px';
    //$('btn_switch_sidepanel_img').src = "_gfx/zwin_panel_r.png";
    $('btn_switch_sidepanel').style.right = '296px';
    $('btn_switch_bottom_panel').style.left = '320px';
    onResize();
}

function getPageName() {
    return page_name;
}

function onLinkHere(scale, rect) {
    linkHereDB.setLocation(rect[0], rect[1], scale);
    linkHereDB.updatelink();
}

function onLinkHereSubmit(emailto, emailfrom, comment, link) {
    var sendMailService = new SendMailService();
    var sub = "Link do strony mapa.pf.pl";
    var content = "Drogi Internauto,\n";
    content += "użytkownik serwisu mapa.pf.pl "+emailfrom + " przesyła Ci link:\n";
    content += link +"\n\n";
    if(comment!="" && comment!=null && comment != 'null'){
        content += "Komentarz:"+ comment +"\n\n";
    }
    content +="Zapraszamy do korzystania z Mapy Panoramy Firm - www.mapa.pf.pl\n";
    content +=" --\n";
    content +="Eniro Polska Sp. z o.o. (właściciel Panoramy Firm)";
    sendMailService.sendMail(emailto, emailfrom, content, sub);
}

function getHash(sc, p) {
    if(sc!=""&& sc!=undefined){
        linkHereDB.setLocation(p[0], p[1], sc);
    }
    return linkHereDB.createAfterHash();
}

addLoadEvent(setCallbacks);
addLoadEvent(initSetCallbacks);

afterInit();
