var isIE = !$.support.htmlSerialize;
var city_points_url = '/images/interface/city-on-map/';


function iewidth()
{
    document.getElementById('site-wrap').style.width = ((document.documentElement.clientWidth || document.body.clientWidth) < 980) ? '980px' : ((document.body.clientWidth > 1260) ? '1260px' : '100%');
};

/**************************
 * js <-> flash : activities
 **************************/
var current_activity = 0;
var current_activity_activated = false;

function show_activity_info(id)
{
    if($('#activity-' + id + '>.activity-info').hasClass('hidden'))
    {
        $('.activity-info').removeClass('hidden').addClass('hidden').slideUp();
         $('#activity-' + id + '>.activity-info').slideDown().removeClass('hidden');
    }
    else
    {
        $('#activity-' + id + '>.activity-info').addClass('hidden').slideUp();
    }

    flash_launch_animation(id);
};

function flash_launch_animation(id)
{
    var movie = getMovie();
    movie.launchAnimation(id);
};

function flash_show_animation(id, action)
{
    var movie = getMovie();
    movie.showAnimation(id, action);
};

function get_flash_activity(id, status) {
    //alert(id + '' + status);
};

/**************************
 * js <-> flash Bridge
 **************************/
function getMovie()
{
    var M$ =  navigator.appName.indexOf("Microsoft")!=-1
    return (M$ ? window : document)["flash-activities"]
};
/* movie name_DoFSCommand */
function BridgeMovie_DoFSCommand(command, args) {
        window[command].call(null, args)
};
// Hook for Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 &&
navigator.userAgent.indexOf("Windows") != -1) {
        document.write('<script language=\"VBScript\"\>\n');
        document.write('On Error Resume Next\n');
        document.write('Sub BridgeMovie_FSCommand(ByVal command, ByVal args)\n');
        document.write('        Call BridgeMovie_DoFSCommand(command, args)\n');
        document.write('End Sub\n');
        document.write('</script\>\n');
};


/*************************
 * projects
 *************************/

function show_city_info(id, img)
{
    if($('#city-' + id).hasClass('hidden'))
    {
        /***********
         * меняем картинку
         */
        if(!$('#city-image-' + id).hasClass('active'))
        {
            $('#city-image-' + id).attr('src', city_points_url + img + '-active.png');
        }

        /***********
         * показываем название города
         */
        var parent=$('#city-' + id).parent();
        $(parent).css('width',250);
        if(isIE)
        {
            $('#city-' + id).show().removeClass('hidden');
        }
        else
        {
            $('#city-' + id).fadeIn(function() {
                $(parent).css('width',250); // чтобы избежать бага, когда фэйд-аут заканчивается позже, чем фэйд-ин                
            }).removeClass('hidden');
        }
    }
    else
    {
        /***********
         * меняем картинку
         */
        if(!$('#city-image-' + id).hasClass('active'))
        {
            $('#city-image-' + id).attr('src', city_points_url + img + '.png');
        }

        /***********
        * прячем название города
        */
        var parent=$('#city-' + id).parent();
        if(isIE)
        {
            $('#city-' + id).hide().addClass('hidden');
            $(parent).css('width',0);
        }
        else
        {
            $('#city-' + id).fadeOut('fast', function() {
                $(parent).css('width',0);
            }).addClass('hidden');

        }

    }

}


function show_filter(id)
{
        if($('#filter-' + id).hasClass('hidden')) $('#filter-' + id).slideDown().removeClass('hidden');
        else $('#filter-' + id).slideUp().addClass('hidden');
}


function show_image(item_id, file_name)
{
    var src = '/images/modules/projects/' + item_id + '/gallery/' + file_name;
    $('#project-gallery-image').html('<img src="' + src +'"/>');
}



/**************************
 * feedback
 **************************/

function send_feedback_form()
{
    $('#feedback-form-message').html('<div style="padding-left: 115px;"><img src="/images/interface/ajax-loading.gif" width="16" height="16" border="0" alt=""/> Обработка формы...</div>');
    $('#feedback-form-message').fadeIn();
    $('#feedback-form-form').animate({opacity: 0.5}, 500);

    $.post('/contacts/feedback/', {feedback_name: $('#input-name').val(), feedback_email: $('#input-email').val(), feedback_question: $('#input-question').val()},
    function(data) {

        if (data.status == true)
        {
            if (data.event_success == true)
            {
                $('#feedback-form-form').fadeOut();
                $('#feedback-form-message').fadeOut('fast', function(){
                    $('#feedback-form-message').html(data.message);
                    $('#feedback-form-message').fadeIn();
                });
            }
            else
            {
                $('#feedback-form-message').fadeOut('fast', function(){
                    $('#feedback-form-message').html(data.message);
                    $('#feedback-form-message').fadeIn();
                });
                $('#feedback-form-form').animate({opacity: 1}, 500);
            }
        }
        else
        {
            $('#feedback-form-form').fadeOut();
            $('#feedback-form-message').html('Ошибка при обработке формы');
            $('#feedback-form-message').fadeIn();
        }
        }, "json"
    );
};
/**************************
 * создание html элемента 
 **************************/
function elem(name, attrs, style, text) {
    var e = document.createElement(name);
    if (attrs) {
        for (key in attrs) {
            if (key == 'class') {
                e.className = attrs[key];
            } else if (key == 'id') {
                e.id = attrs[key];
            } else {
                e.setAttribute(key, attrs[key]);
            }
        }
    }
    if (style) {
        for (key in style) {
            e.style[key] = style[key];
        }
    }
    if (text) {
        e.appendChild(document.createTextNode(text));
    }
    return e;
}


$(document).ready(function() {
    $("ul.light li").hover(function() {
        var thumbOver = $(this).find("img").attr("src");
        $(this).find("p.thumb").css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
        $(this).find("span").stop().fadeTo('normal', 0 , function() {
            $(this).hide()
        });
    } , function() {
        $(this).find("span").stop().fadeTo('normal', 1).show();
    });
});

function show_hide(_element_id) {
 var element = document.getElementById(_element_id);
 if (element) {
 element.style.display = element.style.display == 'none' ? '' : 'none';
 }
}

/*function fadeOut(){
	$('#allpage').fadeOut(1000);
}
function fadeIn(){
	$('#allpage').fadeIn(1000);
}

var Imtech = {};
Imtech.Pager = function() {
    this.paragraphsPerPage = 3;
    this.currentPage = 2;
    this.pagingControlsContainer = '#pagingControls';
    this.pagingContainerPath = '#paging';

    this.numPages = function() {
        var numPages = 0;
        if (this.paragraphs != null && this.paragraphsPerPage != null) {
            numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
        }
        
        return numPages;
    };

    this.showPage = function(page) {
        this.currentPage = page;
        
        var html = '<ul id="text">';
        this.paragraphs.slice((page-1) * this.paragraphsPerPage,
            ((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
            html += '<li>' + $(this).html() + '</li>';
        });
        html += '</ul>';

        $(this.pagingContainerPath).html(html);
        
        renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
    }

    var renderControls = function(container, currentPage, numPages) {
        var pagingControls = '<div class="pagen"><div>';
        for (var i = 1; i <= numPages; i++) {
            if (i != currentPage) {
                pagingControls += '<a href="#" onclick="pager.showPage(' + i + '); return false; ">' + i + '</a>';
            } else {
                pagingControls += '<span class="span">' + i + '</span>';
            }
        }

        pagingControls += '</div></div>';

        $(container).html(pagingControls);
    }
}*/

(function($){

	// Creating the sweetPages jQuery plugin:
	$.fn.sweetPages = function(opts){
		
		// If no options were passed, create an empty opts object
		if(!opts) opts = {};
		
		var resultsPerPage = opts.perPage || 3;
		
		// The plugin works best for unordered lists, althugh ols would do just as well:
		var ul = this;
		var li = ul.find('li');
		
		li.each(function(){
			// Calculating the height of each li element, and storing it with the data method:
			var el = $(this);
			el.data('height',el.outerHeight(true));
		});
		
		// Calculating the total number of pages:
		var pagesNumber = Math.ceil(li.length/resultsPerPage);
		
		// If the pages are less than two, do nothing:
		if(pagesNumber<2) return this;

		// Creating the controls div:
		var swControls = $('<div class="swControls">');
		
		for(var i=0;i<pagesNumber;i++)
		{
			// Slice a portion of the lis, and wrap it in a swPage div:
			li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />');
			
			// Adding a link to the swControls div:
			swControls.append('<a href="" class="swShowPage">'+(i+1)+'</a>');
		}

		ul.append(swControls);
		
		var maxHeight = 0;
		var totalWidth = 0;
		
		var swPage = ul.find('.swPage');
		swPage.each(function(){
			
			// Looping through all the newly created pages:
			
			var elem = $(this);

			var tmpHeight = 0;
			elem.find('li').each(function(){tmpHeight+=$(this).data('height');});

			if(tmpHeight>maxHeight)
				maxHeight = tmpHeight;

			totalWidth+=elem.outerWidth();
			
			elem.css('float','left').width(ul.width());
		});
		
		swPage.wrapAll('<div class="swSlider" />');
		
		// Setting the height of the ul to the height of the tallest page:
		ul.height(maxHeight);
		
		var swSlider = ul.find('.swSlider');
		swSlider.append('<div class="clear" />').width(totalWidth);

		var hyperLinks = ul.find('a.swShowPage');
		
		hyperLinks.click(function(e){
			
			// If one of the control links is clicked, slide the swSlider div 
			// (which contains all the pages) and mark it as active:

			$(this).addClass('active').siblings().removeClass('active');
			
			swSlider.stop().animate({'margin-left':-(parseInt($(this).text())-1)*ul.width()},'slow');
			e.preventDefault();
		});
		
		// Mark the first link as active the first time this code runs:
		hyperLinks.eq(0).addClass('active');
		
		// Center the control div:
		swControls.css({
			'left':'50%',
			'margin-left':-swControls.width()/2
		});
		
		return this;
		
	}})(jQuery);


	$(document).ready(function(){
		$('#holder').sweetPages({perPage:10});
		$('#holder_index').sweetPages({perPage:4});
		var controls = $('.swControls').detach();
		controls.appendTo('#main');
	});
	
	function diplay_hide (blockId) 
	{ 
	    if ($(blockId).css('display') == 'none') 
	        { 
	            $(blockId).animate({height: 'show'}, 500); 
	        } 
	    else 
	        {     
	            $(blockId).animate({height: 'hide'}, 500); 
	        }
	} 
	
