$(init);

function init()
{
	var countResPerPage = 20;
	var collection = $("#text-comments .comment-block");
	if(countResPerPage > collection.size())
	{
		$(".gallery").hide();
	}
	else
	{	
		CollectionNav("#comments-pager-1, #comments-pager-2", collection, 1, countResPerPage, 5);
	}
	initBookmarks();
	initMapWidget();
	initColorbox();
	initDialogUploadTelecast();
}

function initDialogUploadTelecast()
{
	var formCont;
	var dialogForm;
	var form;
	
	construct();
	function construct()
	{
		formCont = $('#custom-telecast-upload');
		if(formCont.size())
		{
			form = $('form', formCont);
			initUploadForm();
			initClickOnLink();
			checkSaveStatus();
		}
	}

	function checkSaveStatus()
	{
		switch (location.hash) 
		{
			case '#custom-telecast-video-saved':
			{
				showAlert("Ваш файл загружен", "Спасибо, ваш файл успешно загружен. Он появится на сайте после проверки администратором.");
			}
			break;
			case '#custom-telecast-video-error':
			{
				showAlert("Ошибка загрузки файла", "Попробуйте повторно загрузить ролик или свяжитесь с нашими менеджерами");
			}
			break;
		}			
	}
	
	function initClickOnLink()
	{
		$('#custom-telecast-upload-link').click(function(){
			dialogForm.dialog('open');
			return false;
		});
	}
	
	function initUploadForm()
	{
		dialogForm = formCont.dialog({
			buttons: {
				'Отменить': function(){$(this).dialog('close');},
				'Отправить': function(){
					if(checkRequired())
					{
						form.get(0).submit();
					}
					else
					{
						showAlert('Заполнены не все обязательные поля', 'Пожалуйста, заполните все обязательные поля');
					}
				}
			},
			title: 'Загрузка видео-роликов и фотографий',
			modal: true,
			autoOpen: false,
			resizable: false,
			close: function(){$('label', form).removeClass('wrong');form.get(0).reset()},
			height:	500,
			width:	450
		});
	}
	
	function checkRequired()
	{
		var isOk = true;

		$('.required input, .required textarea', form).each(
			function(){
				var label = $('label', $(this).parent());
				label.removeClass('wrong');
				if( !$.trim($(this).val()) )
				{
					label.addClass('wrong');
					isOk = false;
				}
		});
		return isOk;
	}
}

function initColorbox()
{
	$("#company-scheme a").colorbox();	
}

function initBookmarks()
{
	var menuItems = $(".menu-item");
	$(".menu-item").click(onBookmarkClick);

    $("#company-promo-block .promo_title").click(showPromoBlock);
    $("#company-promo-block .promo-details-link").click(showPromoBlock);

	if(menuItems.size() > 0)
	{
        if( /.+#promo$/.test(window.location))
        {
            $.scrollTo('#header');
            showPromoBlock();
        }
        else
        {
              $(menuItems.get(0)).click();
        }      

	};

    function showPromoBlock()
    {
        promoBlock = $("#b-promo");
        if(promoBlock.length)
        {
            promoBlock.click();
            $.scrollTo('#anchor-promo',{ duration:1500, axis:'y', offset:-20 });
        }
    }

	function onBookmarkClick()
	{
		var blockToHide = menuItems.filter(".active");
		if(blockToHide)
		{
			blockToHide = blockToHide.data('assignedBlockId');
			if(blockToHide)
			{
				$(blockToHide).hide();
			}
		}
		menuItems.removeClass("active");
		$(this).addClass("active");
		var assignedBlockId = $(this).data('assignedBlockId');
		if(assignedBlockId)
		{
			$(assignedBlockId).show();
		}
	}
}

function initCompanyGallery( id, gallery_type, gallery, images_per_page )
{
    var images_count = gallery.length;
    var imageLoaded = true;
    var gallery_cont = $('#'+id);
    if ( !(gallery_cont.length && images_count > 0) )
    {
        return;
    }

    var items_cont  = $('.items', gallery_cont);
    var gallery_nav = $('.nav', gallery_cont);
    var left_arrow  = $('.nav-left-arrow', gallery_nav);
    var right_arrow = $('.nav-right-arrow', gallery_nav);

    var last_page = Math.ceil(images_count/images_per_page);

    if ( images_count > images_per_page )
    {
        gallery_nav.show();
    }

    left_arrow.click( function() {showPage( curPage = Math.max(0, curPage-1) );return false;} );
    right_arrow.click( function() {showPage( curPage = Math.min(last_page-1, curPage+1) );return false;} );

    generateContent();
    var curPage = 0;	
    showPage(curPage);

    function showPage( pageNo )
    {
        left_arrow.css('visibility', pageNo == 0 ? 'hidden' : 'visible');
        right_arrow.css('visibility', pageNo == last_page - 1 ? 'hidden' : 'visible');

        var offset = pageNo * images_per_page;
        $('.pages', gallery_nav).text($.sprintf("%d/%d", pageNo+1, last_page));
        items_cont.fadeOut(500, function()
        {
        		imageLoaded = true;
        		$('.item_cont', gallery_cont).hide();
        		var curPage = $('.page_' + pageNo, gallery_cont);
        		$('img.loader', curPage).each( function(i){
        			loadImage( $(this) );
        		});
        		curPage.show()
            items_cont.fadeIn(500);        	
        });
    }    
    
    function generateContent( )
    {
        for (var i = 0; i < images_count; i++)
        {
            items_cont.append('<div class="item_cont page_'+Math.floor(i/images_per_page)+'"><div class="image_cont"></div></div>');
        }

        $('> div:even', items_cont).addClass('left');
        $('> div:odd', items_cont).addClass('right');

        $('> div .image_cont', items_cont).each( function(i)
        {
            var imageInfo = gallery[i];
            var a = $('<a href="'+imageInfo.url+'" class="item" rel="gallery-'+gallery_type+'" title="'+imageInfo.title+'"> \
               <img class="loader" src="/images/loader.gif" title="'+imageInfo.title+'" /> \
             </a>');
            $('img', a).data('id', i);
        		a.colorbox({'href':imageInfo.url, initialWidth: 300, initialHeight: 100, onComplete: onCompleteColorboxControlSize, transition: 'none'});
            $(this).append(a);
        });
    }

    function onCompleteColorboxControlSize()
    {
			var cboxLoadedContent = $("#cboxLoadedContent");
			
			var height = cboxLoadedContent.height();
			if(height <= 2)
			{
				colorboxControlSize();
			}    	
    }
    
    function colorboxControlSize()
    {
			var cboxPhoto = $("#cboxPhoto");
			var height = cboxPhoto.height();
			var width = cboxPhoto.width();
			if(height > 2)
			{
				$.fn.colorbox.resize({innerHeight: height, innerWidth: width});				
			}
			else
			{
				setTimeout(colorboxControlSize, 500);
			}
    }
    
    function loadImage( sourceImg )
    {
    		var imageId = sourceImg.data('id');
    		var imageInfo = gallery[imageId];
        var img = new Image();
        img.onload = $.bind(img, onloadCallback, imageInfo, sourceImg);
        img.onerror = $.bind(img, onerrorCallback, imageInfo, sourceImg);
        img.src = imageInfo.thumbnail;
        if ( img.width )
        {
            $.bind(img, onloadCallback)(imageInfo, sourceImg);
        }
    }
    
    function controlGalleryImageSize()
    {
    	var isOk = true;
			$("#company-gallery-"+gallery_type+" .items .page_"+ curPage +" img").each(function(){
				var self = $(this);
				var height = self.height();
				if(height > 2)
				{
  				self.css({'margin-top': (110-height)/2});						
				}
				else
				{
					if( isOk )
					{
						setTimeout(controlGalleryImageSize, 1000);
						isOk = false;
					}
				}
			});    	
    }
    
    function onloadCallback( imageInfo, img )
    {
    		if ( this.__displayed )
        {
            return;
        }
        this.__displayed = true;

        var a = img.parent();
        a.empty();
        img = $(this);
        img.attr({
        	'title': imageInfo.title,
        	'alt': imageInfo.title
        });

        a.append(img);
        var cont = a.parent();
        a.css({'display':'block', 'font-size': '0px', 'line-height': '0px'});

        if(this.height > 2)
        {
        	img.css({'margin-top': (110-this.height)/2});
        }
        else
        {
        	if( imageLoaded )
        	{
						imageLoaded = false;
						setTimeout(controlGalleryImageSize, 1000);
        	}
        }

        if ( gallery_type == 'video' )
        {
            cont.append('<a href="'+imageInfo.url+'" class="btn-play" title="'+imageInfo.title+'"></a>');
            var btnPlay = $('.btn-play', cont);
            var f = function() {a.click();return false;};
            btnPlay.click(f);
            var p = cont.parent('div');
            p.addClass('item_cont_video');

            var info = null;
            p.append( info = $('<div class="info"></div>') );
            info.append( $('<a href="'+imageInfo.url+'">'+imageInfo.title+'</a>').click(f) );
            if (imageInfo.date)
            {
                info.append('<div class="date">'+imageInfo.date+'</div>');
            }
        }
    }

    function onerrorCallback( imageInfo, img )
    {
    		var cont = img.parent().parent();
        cont.html('<div class="error"><br/>Ошибка при загрузке изображения</div>');
    }
}

function showMistakeDialog()
{
    var form = $("#dialog").clone();
    form.dialog(
    {
        position:     'center',
        width:        500,
        height:       360,
        resizable:    false,
        modal:        true,

        close: function() {$(this).dialog('destroy').remove();},

        overlay:
        {
            backgroundColor: '#000',
            opacity: 0.5
        },

        buttons:
        {
            'Отправить сообщение': function()
            {
                var type = $('#m-type', form);
                if ( type.get(0).selectedIndex == 0 )
                {
                    showAlert('', 'Выберите тип неточности.');
                }
                else
                {
                    $(this).dialog('destroy').remove();

                    type = encodeURIComponent(type.val());
                    var url = encodeURIComponent(document.location);
                    var comment = encodeURIComponent($('#m-comment', form).val());

                    $.ajax({
                        type:     "POST",
                        url:      "/ajax/error/",
                        cache:    false,
                        data:     $.sprintf("url=%s&type=%s&comment=%s", url, type, comment),
                        success:  function(msg)
                        {
                            showAlert('', 'Спасибо. Ваше замечание принято.');
                        },
                        error: function()
                        {
                            showAlert('', 'Извините произошла ошибка при отправлении. Попробуйте позже.');
                        }
                    });
                }
            },

            'Отмена': function() {$(this).dialog('destroy').remove();}
        }
    });
    form.show();
}

function showResponseDialog()
{
    var form = $("#response-dialog").clone();
    $("form", form).submit(function(){return false;});
    
    form.dialog(
    {
        position:     'center',
        width:        500,
        height:       360,
        resizable:    false,
        modal:        true,

        close: function() {$(this).dialog('destroy').remove();},

        overlay:
        {
            backgroundColor: '#000',
            opacity: 0.5
        },

        buttons:
        {
            'Отправить сообщение': function()
            {
                var message = $('#m-message', form).val();
                var email = $('#m-email', form).val();
                var name = $('#m-name', form).val();
                var business_id = $('#m-business-id', form).val(); 
                
                if ( !message || !/\S/.test(message) )
                {
                    showAlert('Ошибка', 'Поле "Сообщение" должно быть заполнено.');
                } 
                else
                {
                		if( !( /^\w[\w\.\-]*@\w[\w\-]*\.\w+$/.test( email ) ) && email )
                		{
                			showAlert('Ошибка', 'Неверный формат для Email.');
                		}
                		else	
                		{
		                    $(this).dialog('destroy').remove();
		
		                    var url = encodeURI(document.location);
		
		                    $.ajax({
		                        type:     "POST",
		                        url:      "/ajax/comments/",
		                        cache:    false,
		                        data:     {business_id: business_id, url: url, message: message, email: email, name: name},
		                    
		                        success:  function(msg)
		                        {
		                            showAlert('', 'Спасибо. Ваше сообщение будет опубликовано в течение 5 рабочих дней.');
		                        },
		                        error: function()
		                        {
		                            showAlert('', 'Извините произошла ошибка при отправлении. Попробуйте позже.');
		                        }
		                    });
                		}
                }
            },

            'Отмена': function() {$(this).dialog('destroy').remove();}
        }
    });
    form.show();
}


function initMapWidget( )
{
    var address = $("#ymap-address").val();
    var description = $("#ymap-description").val();
    
    $(function() {
				if(window.YMaps)
				{
	        YMaps.load(function(){
	            var contElem = $("#ymap-scheme").get(0);
	            if (contElem)
	            {
	                var map = new YMaps.Map(contElem);
									var zoom = 14;
	                
	                _loadPoint(function(point) {
	                    map.setCenter(point, zoom);
						map.openBalloon(point, description);
	                });
	            }
	
			        $(".ymap-open").click(_initBigMap);
	        });
				}
    });

    function _initBigMap()
    {
        var cont = $("#ymap-big-container");
        cont.html("");
        cont.css({
            'width': $(window).width() - 300,
            'height': $(window).height() - 300
        });
        
        var ymap_big = null;
				ymap_big = new YMaps.Map(cont.get(0), {'ignoreResize': false});
				
				var objManager = new YMaps.ObjectManager();
				
				objManager.removeAll();
				
				ymap_big.enableScrollZoom();
				ymap_big.addControl(new YMaps.SmallZoom());
				ymap_big.addControl(new YMaps.MiniMap());

				var zoom = 14;
				
				_loadPoint(function(point) {
				    ymap_big.setCenter(point, zoom);
					ymap_big.openBalloon(point, description);
				});
				
				var openBtn = $(".ymap-open"); 
				openBtn.unbind("click", _initBigMap);
			  openBtn.colorbox({
			  	inline: true, 
			  	href:"#ymap-big-container",
			  	onComplete: function(){ymap_big.redraw();}
		  	});
			  openBtn.click();
			  return false;
    }

    function _loadPoint( cb )
    {
        var geocoder = new YMaps.Geocoder(address, {results: 1});

        YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
            if (this.length()) {
                var point = this.get(0).getGeoPoint();
                cb(point);
            }
        });

        YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (error) {
            alert("Ошибка поиска адреса на карте");
            return false;
        });
    }
}
