readCity = function() {
    var default_city = {};
    var selected_city = {};

    default_city.slug = "novosibirsk";
    default_city.lat = 55.0456;
    default_city.lng = 82.9160;
    selected_city.slug = false;

    if (readCookie("city_slug")!==null){
        selected_city.slug = readCookie("city_slug");
        selected_city.lat = readCookie("city_lat");
        selected_city.lng = readCookie("city_lng");
    }
    else{
        createCookie("city_slug", default_city.slug, 365);
        createCookie("city_lng", default_city.lng, 365);
        createCookie("city_lat", default_city.lat, 365);
        selected_city = default_city;
    }
    return selected_city;
}


//****** Класс поиска
function Search() {
    this.form = $("#search_form");
    this.loader = $("div#loading_wait");
    this.sbmit = $("#search_button");
    this.query = $("#id_q");
    this.city = false;

    if (LOCAL_SEARCH) {
        // поиск по кабинету
        this.local = true;
    } else {
        this.city = readCity();
        // this.type = $("#id_type option:selected");
        this.type = document.current_selected_choice === true ? 'org' : 'art';
        this.local = false;
        if (this.city.slug != undefined) SEARCHING_URL = SEARCHING_URL.replace('novosibirsk', this.city.slug);
    }
}

// autoload
Search.autoload = function(change_city) {
    if (document.search == undefined) {
        initHashController();
        document.search = new Search();
        document.search.init();
    }
    var search = document.search;
    var param = HashController.getHashParams(window.location.href);
    if (change_city) {
        try {
            delete param.swx;
            delete param.swy;
            delete param.nex;
            delete param.ney;
        }
        catch (err) {}
    }

    city = 'novosibirsk';
    if (window.location.hash.match(/\/city\/[\-\w]+\/search/)) {
        city = window.location.hash.split('/')[2];
        SEARCHING_URL = '/city/' + city + '/search/';
    }
    city = city_list[city];

    if ('art' == param['type']) {
        search.load(SEARCHING_URL, param, "search.set_articles");
    }
    else {
        function _load(param){
            search.load(SEARCHING_URL, param, "search.set_organizations");
        }
        function wrapper(param){
            return _load
        }
        if (isMapLibsLoaded() === true){
            document._map.setMapCenter(city);
            _load(param);
        }
        else{
            loadMap(wrapper, param);
        }

    }
    search.query.val(param['q']);
    search.form.find("#id_type").val(param['type']);
    return false;
}

// инициализация
Search.prototype.init = function(){
    var search = this;

    if (!LOCAL_SEARCH) {
        search.query.focus(function() {
            if (search.query.val() == 'Уточните направление поиска') {
                search.query.val('');
                search.query.removeClass('search_content');
            }
        })

        search.query.blur(function() {
            if (search.query.val() == ''){
                search.query.val('Уточните направление поиска');
                search.query.addClass('search_content');
            }
        })
    }
    else {
        search.query.focus(function() {
            if (search.query.val() == 'Поиск товара') {
                search.query.val('');
                search.query.removeClass('search_content');
            }
        })

        search.query.blur(function() {
            if (search.query.val() == ''){
                search.query.val('Поиск товара');
                search.query.addClass('search_content');
            }
        })
    }

    search.sbmit.click(function(){
        search.searching();
        return false;
    })

    search.query.keypress(function(event){
        if (event.keyCode == 13) return search.searching();
    });
}

// валидация формы поиска
Search.prototype.validation = function() {
    var search = this;
    if (search.query.val().length < 3) {
        alert("Cтрока поиска должна содержать минимум 3 символа");
        return false;
    }
    if (search.query.val() == "Уточните направление поиска") {
        alert("Уточните направление поиска");
        return false;
    }
    return true;
}

// поиск товаров / организаций
Search.prototype.searching = function() {
    var search = this;
    search.city = readCity();
    //SEARCHING_URL = SEARCHING_URL.replace('novosibirsk', this.city.slug);
    SEARCHING_URL = '/city/' + this.city.slug + '/search/';

    if (search.validation()) {
        if (!this.local) {
                search.type = document.current_selected_choice === true ? 'org' : 'art';
                document._hashController.setParams({'type': search.type, 'q': search.query.val()});
                document._hashController.updateHash(SEARCHING_URL);
                var query = "type="+search.type+"&"+search.form.serialize();
                if ('art' === '' + search.type) {
                    search.load(SEARCHING_URL, query, "search.set_articles");
                }
                else {
                    function _search(obj){
                        obj.load(SEARCHING_URL, query, "search.set_organizations");
                        return false;
                    }
                    function wrapper(){
                        return _search;
                    }
                    if (!isMapLibsLoaded()){
                        loadMap(wrapper, search);
                    } else {
                        _search(search);
                    }
                }
                $("#menus_").find(".selected").removeClass("selected");

        } else {
            // поиск по персональному сайту
            search.form.submit();
        }
    }
    return false;
}

// подгрузка товаров / организаций
Search.prototype.load = function(url, param, func) {
    var search = this;
    search.loader.addClass('ajax_load');
    $.get(url, param, function(data) {
        eval(func + '(data)');
    }, 'json');
}

// отображение результата поиска по товарам
Search.prototype.set_articles = function(data) {
    var search = this;

    search.loader.removeClass('ajax_load');
    if (data['error']) {
        alert(data['error']);
        return false;
    }
    if (data['right']) $("div#tab-1").html(data['right']);
    $(".pagination a").bind('click', function () {
        var param = HashController.getHashParams($(this).attr('href'));
        document._hashController.setParams(param);
        document._hashController.updateHash(SEARCHING_URL);
        // don't load categories tree
        if (!param['r']) param['r'] = 1;
        search.load(SEARCHING_URL, param, "search.set_articles");
        return false;
    })
    $("div#tab-1").scrollTop(-100);
    if (data['left']){
        $("div#c-search").html(data['left']);
        Search.show_result();
    }
    return false;
}

// отображение результата поиска по организациям
Search.prototype.set_organizations = function(data) {
    var search = this;

    search.loader.removeClass('ajax_load');
    if (data['error']) {
        alert(data['error']);
        return false;
    }
    if (data['left']) {
        $("div#c-search").html(data['left']);
        Search.show_result();
    }
    $(".pagination a").bind('click', function () {
        var param = HashController.getHashParams($(this).attr('href'));
        document._hashController.setParams(param);
        document._hashController.updateHash(SEARCHING_URL);
        // don't reload map
        //if (!param['l']) param['l'] = 1;
        search.load(SEARCHING_URL, param, "search.set_organizations");
        return false;
    })
    $("div#c-search").scrollTop(-100);
    if (data['right']) {
        if (!$('#tab-1').is(":has(#map)")){
            $("div#tab-1").html('<div id="map" style="height:100%;"></div>');
            document._map = new MapClass('map', data['right']['viewport']);
            document._map.initial();
        } else {
            document._map.map.clearOverlays();
        }
        document._map.addActivePoints(data['right']['active']);
        document._map.addPoints(data['right']['inactive']);
    }
    $("span[id^='office-']").bind('click', function(){
        var id = $(this).attr('id').replace('office-', '');
        var pt = document._map.activePoints[document._map.offices[id]['id']];
        document._map.officeInfoWindow(pt._latlng, pt._link);
    })
    //set_map_obj_center(document._map.map);
    return false;
}

// показываем рубрики найденные поиском
Search.show_result = function() {
    var $block2=$("#block_2");
    $block2.animate({ 'marginLeft': -500+"px"}, 500 );
}

//********* end


//***** Класс для работы с деревом категорий
function TreeView() {
    this.tree = $("#treeview");
    this.cat = $(".s_cat");
    this.cat_item = $(".s_item");
}

TreeView.prototype.init = function(){
    var tree = this;
    search = document.search;

    tree.cat.click(function(){
        return tree.cat_toogle($(this));
    })

    // для рубрики 3-го уровня подгружаем результаты поиска по этой рубрике
    tree.cat_item.click(function(){
        var param = HashController.getHashParams($(this).attr('href'));
        document._hashController.setParams(param);
        document._hashController.updateHash(SEARCHING_URL);
        // don't load categories tree
        param['r'] = 1;
        search.load(SEARCHING_URL, param, "search.set_articles");
        return false;
    })
}

// сворачиваем / разворачиваем дерево
TreeView.prototype.cat_toogle = function(obj) {
    var id = $(obj).attr('id');
    var tgl = $('#'+id+'_ul');
    if ('none' == tgl.css('display'))
        tgl.css('display', 'block');
    else
        tgl.css('display', 'none');
}

//********* end


//************* класс карты
function MapClass(id, center) {
    if(!id) id="map";


    this.id = id;
    this.infw_isOpened = 0;
    this.setNewCity = 0;
    this.activePoints = new Array();
    this.offices = new Array();

    this.mapIcon = new GIcon(G_DEFAULT_ICON);
    this.mapIcon.iconSize = new GSize(24, 24);
    this.mapIcon.shadowSize = new GSize(36, 24);
    this.mapIcon.shadow = "/media/roxisite/img/mm_20_shadow.png";
    this.mapIcon.iconAnchor = new GPoint(6, 20);
    this.mapIcon.infoWindowAnchor = new GPoint(5, 1);
    this.icons = {
                "inactive": "/media/roxisite/img/mm_20_green.png",
                "active": "/media/roxisite/img/mm_20_red.png",
                0: "/media/roxisite/img/active_abc/active_search_a.png",
                1: "/media/roxisite/img/active_abc/active_search_b.png",
                2: "/media/roxisite/img/active_abc/active_search_c.png",
                3: "/media/roxisite/img/active_abc/active_search_d.png",
                4: "/media/roxisite/img/active_abc/active_search_e.png",
                5: "/media/roxisite/img/active_abc/active_search_f.png",
                6: "/media/roxisite/img/active_abc/active_search_g.png",
                7: "/media/roxisite/img/active_abc/active_search_h.png",
                8: "/media/roxisite/img/active_abc/active_search_i.png",
                9: "/media/roxisite/img/active_abc/active_search_j.png",
                10: "/media/roxisite/img/active_abc/active_search_k.png",
                11: "/media/roxisite/img/active_abc/active_search_l.png"
    };

    if (GBrowserIsCompatible()) {
        this.map = new GMap2(document.getElementById("map"));
        this.map.enableScrollWheelZoom();
        this.map.enableContinuousZoom();
        this.map.setUIToDefault();

        var param = center!=undefined ? center : HashController.getHashParams(window.location.hash);
        if (param['swx'] && param['swy'] && param['nex'] && param['ney']) {
            var bounds = new GLatLngBounds(new GLatLng(param['swy'], param['swx']), new GLatLng(param['ney'], param['nex']));
            zoom = this.map.getBoundsZoomLevel(bounds);
            this.map.setCenter(bounds.getCenter(), zoom);
        } else {
            city = readCity();
            this.map.setCenter(new GLatLng(parseFloat(city.lat), parseFloat(city.lng)), 11);
        }
    }
}

MapClass.prototype.initial = function(){
    mapp = this;

    GEvent.addListener(mapp.map, "moveend", function(){
        mapp.mapMoveend();
    });

    GEvent.addListener(mapp.map, "zoomend", function(){
        mapp.mapZoomend();
    });

    GEvent.addListener(mapp.map, "infowindowopen", function(){
        mapp.infw_isOpened = 1;
    })

    GEvent.addListener(mapp.map, "infowindowbeforeclose", function(){
        mapp.infw_isOpened = 0;
    })
}

MapClass.prototype.setMapCenter = function (city) {
    if (isMapLibsLoaded() === true ){
        var newcenter = new GLatLng(city.lat, city.lng);
        var zoom = 11;
        this.map.setCenter(newcenter, zoom);
        this.setNewCity = 1;
    }
}

MapClass.prototype.mapMoveend = function(){
    search = document.search;
    if (!this.infw_isOpened && !this.setNewCity) {
        this.setNewCity = 0;
        this.redraw();
    }
}

MapClass.prototype.redraw = function(){
        var viewPort = this.getViewPort();
        var param = HashController.getHashParams(window.location.hash);
        param['swx'] = viewPort['lng2'];
        param['swy'] = viewPort['lat2'];
        param['nex'] = viewPort['lng1'];
        param['ney'] = viewPort['lat1'];
        var redraw = this.activePoints.length < ACTIVE_POINTS_LIMIT ? true : false;
        var bounds = this.map.getBounds();
        for (i=0; i<this.activePoints.length; i++) {
            if (!bounds.containsLatLng(this.activePoints[i].getLatLng())) {
                redraw = true;
                break;
            }
        }
        if (redraw) {
            document._hashController.setParams(param);
            document._hashController.updateHash(SEARCHING_URL);
            //if (!param['r']) param['r'] = 1;
            search.load(SEARCHING_URL, param, "search.set_organizations");
        }
};

MapClass.prototype.mapZoomend = function(){
    search = document.search;

    var viewPort = this.getViewPort();
    var param = HashController.getHashParams(window.location.hash);
    param['swx'] = viewPort['lng2'];
    param['swy'] = viewPort['lat2'];
    param['nex'] = viewPort['lng1'];
    param['ney'] = viewPort['lat1'];

    document._hashController.setParams(param);
    document._hashController.updateHash(SEARCHING_URL);
    //if (!param['r']) param['r'] = 1;
    search.load(SEARCHING_URL, param, "search.set_organizations");
}

function getOffsetTop(obj) {
    var y=0;
    while(obj) {
        y+=obj.offsetTop;
        obj = obj.offsetParent;
    }
    return y
}

MapClass.prototype.addPoint = function(id, lat, lng, icon_name, link, org_id, office_id){
    var latlng = new GLatLng(lat, lng);
    this.mapIcon.image = this.icons[icon_name];
    var marker = new GMarker(latlng, {"icon": this.mapIcon});
    GEvent.addListener(marker, "click", function() {
        mapp.officeInfoWindow(latlng, link);
    });
    this.points[id] = marker;
    this.points[id].id = id;
    this.points[id]._latlng = latlng;
    this.points[id]._link = link;
    this.points[id].icon_name = icon_name;

    this.offices[office_id] = {'id': id, 'type': 'inactive'};
}

MapClass.prototype.addActivePoint = function(id, lat, lng, icon_name, link, org_id, office_id){
    mapp = this;

    var latlng = new GLatLng(lat, lng);
    this.mapIcon.image = this.icons[icon_name];
    var marker = new GMarker(latlng, {"icon": this.mapIcon});
    GEvent.addListener(marker, "click", function() {
        mapp.officeInfoWindow(latlng, link);
        mapp.highlight(org_id);
    });

    this.activePoints[id] = marker;
    this.activePoints[id].id = id;
    this.activePoints[id]._latlng = latlng;
    this.activePoints[id]._link = link;
    this.activePoints[id].icon_name = icon_name;

    this.offices[office_id] = {'id': id, 'type': 'active'};
    return marker;
}

MapClass.prototype.highlight = function(org_id) {
    if ($('#c_3_'+org_id).css("display")=="none") {
        $('#c_3_'+org_id).parent().find('span.file a.org').click();
    } else {
        $('.firm_search_item').removeClass('selected');
        $('#c_3_'+org_id).parent().parent().addClass('selected');
    }
    var height = getOffsetTop($('#c_3_'+org_id).parent().parent()[0])-getOffsetTop($('div#c-search')[0]);
    $("div#c-search").scrollTop(height);
}

MapClass.prototype.officeInfoWindow = function(latlng, link){
    mapp = this;

    GDownloadUrl(link, function(data) {
        var URL = "http://maps.google.com/staticmap?center="+latlng.lat()+","+latlng.lng()+"&zoom=16&size=320x170&maptype=mobile&markers="+latlng.lat()+","+latlng.lng()+",redo&key="+GMAPS_API_KEY+"&hl=ru";
        data = "<div style='width:320px;height:250px;'><img id='minimap' src='" + URL + "'  />"+data + "</div>";
        mapp.map.openInfoWindowHtml(latlng, data);
    });
}

MapClass.prototype.addPoints = function(data){
    this.points = [];
    for (var i = 0; i < data.length; ++i) {
        pt = data[i];
        this.addPoint(i, pt['lat'], pt['lng'], "inactive", pt['link'], pt['org'], pt['id']);
    }
    var mcOptions = {gridSize: 50, maxZoom: 15};
    this.cluster = new MarkerClusterer(this.map, this.points, mcOptions);
}

MapClass.prototype.addActivePoints = function(data){
    for (var i = 0; i < data.length; ++i) {
        pt = data[i];
        //marker = this.addActivePoint(i, pt['lat'], pt['lng'], "active", pt['link'], pt['org'], pt['id']);
        marker = this.addActivePoint(i, pt['lat'], pt['lng'], orgs_list.indexOf(pt['org']), pt['link'], pt['org'], pt['id']);
        this.map.addOverlay(marker);
    }
}

MapClass.prototype.getViewPort = function(){
    var bounds = this.map.getBounds();
    var northEast = bounds.getNorthEast();
    var southWest = bounds.getSouthWest();

    var viewPort = {
        lat1:northEast.lat(),
        lng1:northEast.lng(),
        lat2:southWest.lat(),
        lng2:southWest.lng()
    };

    return viewPort;
}

//*************


$(function() {
    initHashController();

    document.search = new Search();
    document.search.init();
})


