var zindex = 10;
var cur_promo = 1;
var promo_timer = null;
var rs_timer = null;

var map = null;
var bounds = null;
var overlay = null;
var markers = {};

var sliders = {};

function MapOverlay ( id, map )
{
    this.id_  = id;
    this.map_ = map;
    this.div_ = null;
    this.setMap ( map );
}

function InitMap ()
{
    MapOverlay.prototype = new google.maps.OverlayView ();

    MapOverlay.prototype.onAdd = function ()
    {
        var div  = '<div class="map_cloud">';
            div += '<div class="th_pic">' + $( '#sres_' + this.id_ ).find ( 'div.th_pic' ).html () + '</div>';
            div += '<div class="map_sig">';
            div += '<div class="special_head">' + $( '#sres_' + this.id_ ).find ( 'div.special_head' ).html () + '</div>';
            div += '<div class="special_price">' + $( '#sres_' + this.id_ ).find ( 'div.special_price' ).html () + '</div>';
            div += '</div>';
            div += '</div>';
            div = $( div );
    
        this.div_ = div.get ( 0 );
        
        var panes = this.getPanes ();
        panes.floatPane.appendChild ( this.div_ );
    }
    
    MapOverlay.prototype.draw = function ()
    {
        var overlayProjection = this.getProjection ();
        var coords = overlayProjection.fromLatLngToDivPixel ( markers[this.id_].position );
    
        $( this.div_ ).css ( { top: ( coords.y - 184 ) + 'px', left: ( coords.x - 90 ) + 'px' } );
    }
    
    MapOverlay.prototype.onRemove = function ()
    {
        this.div_.parentNode.removeChild ( this.div_ );
    }
    
    MapOverlay.prototype.hide = function ()
    {
        if ( this.div_ )
        {
            this.div_.style.visibility = "hidden";
        }
    }
    
    MapOverlay.prototype.show = function () {
        if ( this.div_ )
        {
            this.div_.style.visibility = "visible";
        }
    }
    
    var latlng = new google.maps.LatLng ( 43.73836, 7.217331 );
    var myOptions = {
      zoom: 9,
      center: latlng,
      scrollwheel: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    map = new google.maps.Map ( document.getElementById ( 'google_map' ), myOptions );
    
    google.maps.event.addListener ( map, 'zoom_changed', function () {
        if ( map.getZoom () > 14 )
        {
            map.setZoom ( 14 ); 
        } else {
            CheckResults();
        }
    } );
    
    google.maps.event.addListener ( map, 'dragend', function () {
        CheckResults();
    } );
}

function UpdateMarkers ( data )
{
    for ( var key in data )
    {
        if ( typeof ( markers[key] ) == 'undefined' )
        {
            var myLatLng = new google.maps.LatLng ( data[key].lat, data[key].lng );
        
            markers[key] = new google.maps.Marker ( {
                position: myLatLng, 
                map: map, 
                icon: '/images/marker.png',
                fr_id: key
            } );
            
            google.maps.event.addListener ( markers[key], 'click', function ( e, m ) {
                RemoveCloud();
                overlay = new MapOverlay ( this.fr_id, map );
                map.panTo ( this.position );
            } );
        }
    }
    
    for ( var key in markers )
    {
        if ( typeof ( data[key] ) == 'undefined' )
        {
            markers[key].setMap ( null );
            delete ( markers[key] );
            
            if ( overlay && overlay.id_ == key )
            {
                RemoveCloud();
            }
        }
    }
}

function RemoveCloud ()
{
    if ( null != overlay )
    {
    	overlay.setMap ( null );
    	overlay = null;
    }
}

function SettingsMetaInit ()
{
    $( 'div.settings_meta > img' ).toggle (
        function () {
            $( 'div.settings_meta > div' ).show ();
        },
        function () {
            $( 'div.settings_meta > div' ).hide ();
        }
    );
}

function SaveSettingsMeta ()
{
    $( 'div.settings_meta > div' ).hide ();
    
    var data = {
        title: $( '#settings_meta_title' ).val (),
        keywords: $( '#settings_meta_keywords' ).val (),
        description: $( '#settings_meta_description' ).val (),
        url: $( '#meta_url' ).val ()
    };
    
    $.post ( '/ajax/meta/save_meta/', data );
}

function AddToFav ( id, obj )
{
    $( obj ).replaceWith ( '<span style="color: green">Добавлено в избранное</span>' );
    
    var cnt = parseInt ( $( '#fav_cnt' ).text () ) + 1;
    $( '#fav_cnt' ).text ( cnt );
    
    $.getJSON ( '/ajax/cat/add_to_fav/', { id: id } );
}

function Submit ( obj )
{
    $( obj ).removeAttr ( 'onclick' );
    
    var nobj = null;
    
	for ( var parent = obj.parentNode; parent; parent = parent.parentNode )
	{
		if ( parent.nodeName == 'form' || parent.nodeName == 'FORM' )
		{
		    nobj = parent;
		    break;
		}
	}
	
	$( nobj ).submit ();
	return false;
}

function CheckResults ()
{
    if ( $( 'input[name="map_search"]' ).length == 1 )
    {
        bounds = map.getBounds ();
        var tr = bounds.getNorthEast ();
        var bl = bounds.getSouthWest ();
        
        $( 'input[name="map_at"]' ).val ( tr.lat() );
        $( 'input[name="map_ar"]' ).val ( tr.lng() );
        $( 'input[name="map_ab"]' ).val ( bl.lat() );
        $( 'input[name="map_al"]' ).val ( bl.lng() );
        
        var req = $( '#search_form' ).serialize ();
        
        $.getJSON ( '/ajax/cat/get_markers/', { str: req }, function ( data ) {
            $( '#results_cnt' ).text ( data.cnt );
            $( '#results_c' ).show ();
            
            $( '#map_html_results' ).html ( data.html );
            
            UpdateMarkers ( data.markers );
        } );
    } else {
        var req = $( '#search_form' ).serialize ();
        
        $.getJSON ( '/ajax/cat/get_results/', { str: req }, function ( data ) {
            if ( $( 'input[name="simple_search"]' ).length == 1 )
            {
                $( '#results_cnt' ).text ( data.cnt );
                $( '#results_c' ).show ();
                
                if ( data.cnt > 0 )
                {
                    $( '#show_results_submit' ).show ();
                } else {
                    $( '#show_results_submit' ).hide ();
                }
            } else {
                if ( data.cnt > 0 )
                {
                    $( '#results_nothing' ).hide ();
                    $( '#show_results_submit' ).show ();
                    $( '#results_cnt' ).text ( data.cnt );
                    $( '#results_c' ).show ();
                } else {
                    $( '#show_results_submit' ).hide ();
                    $( '#results_c' ).hide ();
                    $( '#results_nothing' ).show ();
                }
            }
        } );
    }
}

function RSBinds ()
{
    $( 'div.rs_level_1' )
        .bind ( 'mouseenter', function () {
                ShowRegionSelect ();
            } )
        .bind ( 'mouseleave', function () {
                StartRSTimeout ();
            } );
            
    $( 'div.rs_level_2' ).each (
        function () {
            $( this )
                .bind ( 'mouseenter', function () {
                        ShowRegionSelect ( $( this ).attr ( 'id' ), 2 );
                    } )
                .bind ( 'mouseleave', function () {
                        StartRSTimeout ();
                    } )
        }
    );
    
    $( 'div.rs_level_3' ).each (
        function () {
            $( this )
                .bind ( 'mouseenter', function () {
                        ShowRegionSelect ( $( this ).attr ( 'id' ), 3 );
                    } )
                .bind ( 'mouseleave', function () {
                        StartRSTimeout ();
                    } )
        }
    );
}

function ShowRegionSelect ( block, level )
{
    clearTimeout ( rs_timer );
    
    if ( !block )
    {
        $( 'div.rs_level_1' ).show ();
    } else {
        $( 'div.rs_level_' + parseInt ( level + 1 ) ).hide ();
        $( 'div.rs_level_' + level ).hide ();
        $( '#' + block ).show ();
    }
}

function StartRSTimeout ()
{
    rs_timer = setTimeout ( function () {
        $( 'div.rs_level_1' ).hide ();
        $( 'div.rs_level_2' ).hide ();
        $( 'div.rs_level_3' ).hide ();
    }, 1000 );
}

function SetST ( type )
{
    $( 'input[name="st"]' ).val ( type );
    STButtons ();
}

function STButtons ()
{
    var val = $( 'input[name="st"]' ).val();
    
    $( 'div.st_buttons a'  ).css ( { fontWeight: 'normal', backgroundPosition: '0 24px' } );
    $( 'div.sst_buttons a' ).css ( { fontWeight: 'normal', backgroundPosition: '0 24px' } );
    $( '#st_' + val ).css ( { fontWeight: 'bold', backgroundPosition: '0 0' } );
    
    ChangeType ();
}

function ChangeType ()
{
    $( '.type_props_sc' )
        .hide ()
        .find ( 'input' )
        .attr ( 'disabled', 'disabled' );
        
    $( '.prop_slider_c' ).empty ();
        
    var val = $( 'select[name="type"]' ).val ();

    $( '#type_props_' + val + '_l' )
        .show ()
        .find ( 'input' )
        .removeAttr ( 'disabled' );
        
    $( '#type_props_' + val + '_r' )
        .show ()
        .find ( 'input' )
        .removeAttr ( 'disabled' );
        
    $( '#type_props_' + val )
        .show ()
        .find ( 'input' )
        .removeAttr ( 'disabled' );
    
    var ptype = $( 'input[name="st"]' ).val();
    
    $( 'div.price_slider_c' ).hide ();
    $( '#price_slider_' + ptype + '_' + val ).show ();
        
    for ( var key in sliders )
    {
        if ( sliders[key].type == val )
        {
            if ( sliders[key].isprice )
            {
                if ( sliders[key].isprice == ptype )
                {
                    $( '#slider_container_' + key ).html ( '<input id="prop_' + key + '" type="hidden" name="prop_' + key + '" value="' + sliders[key].value + '" />' );
                    jQuery ( '#prop_' + key ).slider ( { from: parseInt ( sliders[key].from ), to: parseInt ( sliders[key].to ), limits: false, step: parseInt ( sliders[key].step ), dimension: sliders[key].dimension, callback: function () { CheckResults(); } } );
                }
            } else {
                $( '#slider_container_' + key ).html ( '<input id="prop_' + key + '" type="hidden" name="prop_' + key + '" value="' + sliders[key].value + '" />' );
                jQuery ( '#prop_' + key ).slider ( { from: parseInt ( sliders[key].from ), to: parseInt ( sliders[key].to ), limits: false, step: parseInt ( sliders[key].step ), dimension: sliders[key].dimension, callback: function () { CheckResults(); } } );
            }
        }
    }
}

function StartPromo ()
{
    promo_timer = setTimeout ( function () {
        switch ( cur_promo )
        {
            case 1: cur_promo = 2; break;
            case 2: cur_promo = 3; break;
            case 3: cur_promo = 1; break;
        }
        
        ShowDot ( cur_promo, true );
        StartPromo ();
    }, 5000 );
}

function GetStrNumEnd ( cnt, e1, e2, e3 )
{
	var end_str = '';

	end_100 = cnt % 100;
	end_10  = cnt % 10;
	
	if ( end_100 == 11 || end_100 == 12 || end_100 == 13 || end_100 == 14 )
	{
		end_str = e3;
	} else if ( end_10 == 1 ) {
		end_str = e1;
	} else if ( end_10 == 2 || end_10 == 3 || end_10 == 4 ) {
		end_str = e2;
	} else {
		end_str = e3;
	}
	
	return end_str;
}

function ShowBigPic ( file )
{
    $.facebox ( { image: file } );
}

function ShowDot ( i, do_not_stop )
{
    if ( !do_not_stop ) clearTimeout ( promo_timer );
    
    $( '.dot' ).css ( 'backgroundPosition', '0 -9px' );
    $( '#dot_' + i ).css ( 'backgroundPosition', '0 0' );
    
    $( 'div.promo_desc_c' ).hide();
    $( '#promo_desc_' + i ).show();
    
    $( 'div.promo_pics' ).prepend ( $( '#promo_pic_' + i ) );
    $( '#promo_pic_' + i )
        .css ( 'zIndex', zindex++ )
        .animate ( { opacity: 'show' }, 1000, function () {
            if ( i != 1 ) $( '#promo_pic_1' ).hide();
            if ( i != 2 ) $( '#promo_pic_2' ).hide();
            if ( i != 3 ) $( '#promo_pic_3' ).hide();
            
            $( '#promo_pic_' + i ).show();
        } );
}

function MoveLine ( to, cont, pixels )
{
    var cur = $( '#' + cont ).scrollLeft ();
    var val = cur + pixels * ( to == 'left' ? -1 : 1 );
    
    if ( $.browser.msie )
	{
	    $( '#' + cont ).scrollLeft ( val );
	} else {
	    $( '#' + cont ).animate ( { scrollLeft: val }, 600 );
	}
}