function cat(link) {
    var el = link.parentNode.parentNode.getElementsByTagName('UL')[0];
    el.style.display = el.style.display == '' ? 'none':'';
    return false;
}

function func_delete()
{
    $('.link-delete').click(function(){
        var link = $(this);
	var ajaxMsg = $('<div>сохраняю...</div>').appendTo(link.parent());
	$.getJSON(this.href, function(result){
		ajaxMsg.remove();
		if (result.success) {
                    link.parent().parent().remove();
		}
	 });
         return false;
    });
}
function func_delete_tmp()
{
    $('.upload-container').delegate('.link-delete-tmp', 'click', function(){
        var link = this;
        $.get(this.href, function(data){
            if (data == 'success') {
                $(link).parent().remove();
            } else {
                // more safe then jq append?
                link.parentNode.innerHTML+=data;
            }
        });
        return false;
    });
}

function func_delete_image()
{
    $('.gallery-container').delegate('.link-delete-image', 'click', function(){
        var link = this;
        $.get(this.href, function(data){
            if (data == 'success') {
                $(link).parent().remove();
            } else {
                // more safe then jq append?
                link.parentNode.innerHTML+=data;
            }
        });
        return false;
    });
}

function func_rating() {
    $('.link-rating').click(function() {
        //var rate = this.className.match(/star(\d+)/)[0];
        var ratingList = $(this).parent().parent(); // OL
        ratingList.hide();

        var wait = $('<div class="wait">сохраняю...</div>');
        var ratingDiv = ratingList.parent();
        ratingDiv.append(wait);
        $.ajax({url: this.href, dataType:'json',
            success: function (data) {
                wait.remove();
                if (data.success) {
                    ratingDiv.html(data.ratingHTML);
                    ratingDiv.append('<div class="thanks">Спасибо за оценку!</div>');
                } else {
                    ratingList.hide();
                }
            }
        });
        return false;
    });
}

function func_recaptcha()
{
    $('#recaptcha').click(function(){
        $('#captcha').load(this.href);
        return false;
    });
}

function func_status()
{
    $('.link-status').live('click', function(){
	var ajaxMsg = $('<div>сохраняю...</div>').appendTo($(this).parent());
        var link = $(this);
	$.getJSON(this.href, function(result){
		ajaxMsg.remove();
		if (result.success) {
			link.replaceWith(result.newlink);
		}
	 });
         return false;
    });
}

function func_check_all()
{
    $('#link-check-all').click(function(){
        var items = document.getElementsByName('items[]');
        if (items) {
            for (var i = 0; i < items.length; i++) {
                items[i].checked = this.checked;
            }
        }
    });
}

function regions(country_el)
{
    var region_el = country_el.form.region_id;
    region_el.options.length = 1;
    country_el.form.city_id.options.length = 1;
    if (country_el.value.length) {
        region_el.disabled = true;
        $.post(location.href, {'country' : country_el.value}, function (data) {
            if (data.length) $(region_el).replaceWith(data);
        });
    }
}

function cities(region_el)
{
    var country_el = region_el.form.country_id;
    var city_el = region_el.form.city_id;
    city_el.options.length = 1;
    if (region_el.value.length) {
        country_el.disabled = true;
        city_el.disabled = true;
        $.post(location.href, {'region' : region_el.value}, function (data) {
            if (data.length) $(city_el).replaceWith(data);
            country_el.disabled = false;
        });
    }
}

function checkLength(item)
{
	var maxlength = parseInt(item.getAttribute('rel'));
	if (item.value.length >= maxlength) {
		item.value = item.value.substr(0, maxlength);
	}
	document.getElementById(item.name + '-count').innerHTML = item.value.length;
}

function func_placeholder()
{
    $('.placeholder')
        .focus(function(){ if (this.val() == this.attr('title')) this.val(''); })
        .blur(function(){ if (this.val() == '') this.val(this.attr('title')); });
}

function mapPlacemark(map, center, prefix)
{
    
    if (map['cp_placemark']) {
        map['cp_placemark'].setCoordPoint(center);
    } else {
        map['cp_placemark'] = new YMaps.Placemark(center);
        map.addOverlay(map['cp_placemark']);
        if (prefix) {
            var obs = YMaps.Events.observe(map['cp_placemark'], map['cp_placemark'].Events.Click, function () {
                    map.removeOverlay(map['cp_placemark']);
                    obs.cleanup();
                    map['cp_placemark'] = null;
                    document.getElementById(prefix+'lat').value = '0';
                    document.getElementById(prefix+'lng').value = '0';
                });
        }
    }
    
}

function func_map(lat, lng, zoom, prefix, address)
{
    $(document).ready(function() {
        var mapEl = $('#'+(prefix || '') +'map');
        var map = new YMaps.Map(mapEl[0]);

        var geocoder = null;
        if (!lat) lat = 0;
        if (!lng) lng = 0;
        if (!zoom) zoom = 10;
        var noCoord = lat==0 && lng==0;
        if (noCoord && address) {
            lng = 37.64;
            lat = 55.76;
            geocoder = new YMaps.Geocoder(address);            
        }
        var center = new YMaps.GeoPoint(lng, lat);

        map.addControl(new YMaps.ToolBar());
        map.addControl(new YMaps.Zoom());
        map.setCenter(center, zoom, YMaps.MapType.PMAP);// YMaps.MapType.MAP
        map.addControl(new YMaps.TypeControl([YMaps.MapType.PMAP, YMaps.MapType.MAP]));
        if (geocoder) {
            YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
                if (this.length()) {
                    center = this.get(0).getGeoPoint();
                    //map.setZoom(14);
                    map.setCenter(center);
                }
            });
            YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (error) {
                if (YMaps.location) {
                    map.setCenter(new YMaps.GeoPoint(YMaps.location.longitude, YMaps.location.latitude));
                    if (YMaps.location.zoom) {
                        map.setZoom(YMaps.location.zoom);
                    }
                } 
            });
        } else {
            mapPlacemark(map, center, prefix);
        }
        
        if (prefix) {
            YMaps.Events.observe(map, map.Events.SmoothZoomEnd, function (map, mEvent) {
                document.getElementById(prefix+'zoom').value = map.getZoom();
            });
            YMaps.Events.observe(map, map.Events.Click, function (map, mEvent) {
                center = mEvent.getGeoPoint();
                mapPlacemark(map, center, prefix);
                if (prefix) {
                    document.getElementById(prefix+'lat').value = center.getLat();
                    document.getElementById(prefix+'lng').value = center.getLng();
                }
            }, this);

            $('a.map-link').click(function() {
                mapEl.toggle();
                return false;

            });
        } else if(noCoord) {
            var selected = null;
            $('a.map-link').click(function() {
                var parent = mapEl.parent();
                if (selected == this) {
                    parent.css('visibility', parent.css('visibility') == 'visible'?'hidden':'visible');
                } else {
                    var src = $(this);
                    var offs = src.offset();
                    
                    selected = this;
                    var point = new YMaps.GeoPoint(src.data('lng'), src.data('lat'));
                    mapPlacemark(map, point);
                    map.setCenter(point);
                    map.setZoom(src.data('zoom'));
                    parent.css({'left': offs.left, 'top': offs.top+16, 'visibility':'visible'});
                }
                
                return false;

            });
        }
    });
}
    
String.prototype.eco = function(){
    return this.replace(/[a-zA-Z]/g, function(c){
        return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
    }).replace(/%/i, '&#64;');
};

$(document).ready(function(){
    if (typeof hs != 'undefined') {
        hs.graphicsDir = '/js/highslide/graphics/';
        hs.showCredits = false;
        hs.lang = {
            cssDirection: 'ltr',
            loadingText: 'загрузка...',
            loadingTitle : 'Click to cancel',
            focusTitle : 'Click to bring to front',
            fullExpandTitle : 'Развернуть в полный размер (f)',
            creditsText : 'Powered by <i>Highslide JS</i>',
            creditsTitle : 'Go to the Highslide JS homepage',
            previousText : 'предыдущая',
            nextText : 'следущая',
            moveText: 'переместить',
            closeText: 'закрыть',
            closeTitle: 'закрыть окно',
            resizeTitle : 'Resize',
            playText : 'Play',
            playTitle: 'слайдшоу',
            pauseText : 'Pause',
            pauseTitle : 'Pause slideshow (spacebar)',
            previousTitle: 'предыдущая',
            nextTitle: 'следущая',
            moveTitle: 'переместить окно',
            fullExpandText : '1:1',
            number: 'Image %1 of %2',
            restoreTitle : 'Нажмите чтобы закрыть, нажмите и тащите чтобы переместить'
        }
    }
    /*if (hs.addSlideshow) hs.addSlideshow({
        interval: 5000,
        repeat: false,
        useControls: true,
        fixedControls: 'fit',
        overlayOptions: {
            opacity: .6,
            position: 'bottom center',
            hideOnMouseOut: true
        }
    });*/
 
    function go(e){
        if (!e) e=window.event;
        location.href='mailto:'+(e.target ? e.target:e.srcElement).innerHTML;
        if (e.preventDefault) e.preventDefault();
        return false;
    }

    var els,i;
    if (document.querySelectorAll) {
        els = document.querySelectorAll('a.em');
        for (i=0;i<els.length;i++) {
            if (els[i].addEventListener) els[i].addEventListener('click', go, false);
            else els[i].attachEvent('onclick', go);
        }
    } else {
        var els = document.getElementsByTagName('A');
        for (i=0;i<els.length;i++) {
            if (els[i].className=='em') {
                if (els[i].addEventListener) els[i].addEventListener('click', go, false);
                else els[i].attachEvent('onclick', go);
            }
        }
    }
});

