// select your location
$(function(){
    var _location = $('#header .location');
    var _lHolder = $('#header .location .holder');
    var _lClose = _location.find('a.close');
    var _locD = 800;
    var _lWidth = _location.find('.selected span').width()+40;

    // reset
    _lClose.hide();
    _location.css('width',_lWidth);
    _lHolder.css('height',0);

    // hover
    _location.hover(function(){
        $(this).addClass('hovered-location');
    },function(){
        $(this).removeClass('hovered-location');
    });

    // open
    _location.find('.selected').click(function(){
        if(_lHolder.is(':not(:animated)') && _location.is(':not(:animated)')) {
            if(_location.hasClass('active-location')) {
                closeLocation();
            }else{
                _location.addClass('active-location');
                // pgn
                _lHolder.show();
                var _lHeight = _location.find('.wrap').height();
                _location.animate({'width':'575px'},_locD/2)
                setTimeout(function(){
                    _lHolder.animate({'height':_lHeight},_locD/2);
                },_locD/2);
                setTimeout(function(){
                    _lClose.show();
                },_locD);
            }
        }
        return false;
    });

    // click 'close' link
    _lClose.click(function(){
        closeLocation();
        return false;
    });

    // mouseleave / enter
    var _lMouseFlag;
    _location.mouseenter(function(){
        clearTimeout(_lMouseFlag);
    });
    _location.mouseleave(function(){
        _lMouseFlag = setTimeout(function(){
            closeLocation();
        },2000);
    });

    // select city
    _location.find('ul a').click(function(){
        if($(this).text()!=_location.find('.selected a').text()) {
            _location.find('.selected a').text($(this).text());
            _lWidth = _location.find('.selected span').width()+40;
        }
        closeLocation();
        // pgn
        $.post('/reference/select_city/',
            {'city': $(this).attr('id')},
            function(json){
                eval('data = ' + json + ';');
                if (data['success'])
                    window.location.reload();
            });
        return false;
    });

    // close sliding box
    function closeLocation(){
        _lClose.hide();
        _lHolder.animate({'height':0},_locD/2)
        setTimeout(function(){
            _location.animate({'width':_lWidth},_locD/2);
        },_locD/2);
        setTimeout(function(){
            _location.removeClass('active-location');
        },_locD);
    }
});
