$(document).ready(function(){
    window.loginWindow = new Window('loginWindow');
	window.photoWindow = new WindowPhoto('photoWindow');
    window.addPostWindow = new WindowAddPost('addPostWindow');
    window.addClubPostWindow = new WindowAddClubPost('addClubPostWindow');
    window.addClubPostWindowOk = new WindowAddClubPostOk('addClubPostWindowOk');
    window.questionWindow = new WindowQuestion('questionWindow');
	window.changeMoodWindow = new WindowChangeMood('changeMoodWindow');
	window.messageWindow = new WindowMessage('message');
	window.confirmWindow = new WindowConfirm('confirm');
	window.chooseWindow  = new WindowChoose('choose');
    
    /*if ($('.b-preloader').size() > 0){
    	window.preloader = new Window('preloader')
        window.preloader.show();
        $('#windowBack').unbind('click', removeWindows);
    	
    	$(window).bind('load', function(){
	    	window.preloader.hide();
	    	$('#windowBack').bind('click', removeWindows);
    	})
    }*/
	
	if ($('#promoWindow').size() > 0){
		window.promo = new Window('promoWindow');
		
		// Не показывать если пришли с promo.clubfei.ru
		var re = /promo\.clubfei\.ru/;
		//var re = /kalina-00-promo-true/;
		if (!re.test(document.referrer)) {
			window.promo.show();
			
			$('#windowBack').unbind('click', removeWindows);
	    	$('#promoWindow').find('.close-button, .close-button-tip').click(function(){
		    	$('#windowBack').bind('click', removeWindows);
		    	window.promo.hide();
	    	});
		}
	}
    
    $("#login a[href=''], #fairyland-door a[href=''], #fairyland-door-link a[href='']").click(function(){
        loginWindow.show();
        return false;    
    });
    
    $(".participate").click(function(){
    	confirmWindow.show(
			'Ты уже в Волшебной стране Маленькой Феи?<br /><br /><br />',
			function() {
				setTimeout(function() {
					loginWindow.show();
				}, 100);
			},
			'1',
			function() {
				location.href = '/registratsija';
			},
			'2',
			'Да',
			'Нет'
		);
    	return false;    
    });
    
    $('#addPostForm').ajaxForm(function(data){
        eval("data = "+data);
        if (data.result == 'error') {
            $('#addPostWindowError').text(data.message);
        } else if (data.result == 'ok') {
            location.assign(data.link);
        }
    });
    $('#addClubPostForm').ajaxForm(function(data){
        eval("data = "+data);
        if (data.result == 'error') {
            $('#addClubPostWindowError').text(data.message);
        } else if (data.result == 'ok') {
        	if ((data.moderation != null) && (data.moderation == 'none')) {
        		$('#addClubPostFormOkText').text('Ваш комментарий успешно добавлен. Пожалуйста, обновите страницу.');
        	} else {
        		$('#addClubPostFormOkText').text('Ваш комментарий успешно добавлен. Он будет опубликован после одобрения.');
        	}
        	addClubPostWindow.hide();
        	addClubPostWindowOk.show();
        }
    });
    $('#choosePostForm').ajaxForm(function(data){
        eval("data = "+data);
        if (data.result == 'error') {
            $('#choosePostWindowError').text(data.message);
        } else if (data.result == 'ok') {
        	chooseWindow.showSuccess(data);
        }
    });
    $('#loginForm').ajaxForm(function(data){
        eval("data = "+data);
        if (data.result == 'error') {
            $('#loginWindowError').text(data.message);
        } else if (data.result == 'ok') {
            location.assign(data.link);
        }
    });
    
    $('a.show-popup-photo').live('click', function(){
		photoWindow.show($(this).attr('href'), $(this).find('img').attr('alt'));
    	return false;
    });
    
    $('#windowBack').bind('click', removeWindows);
    
    function removeWindows() {
    	for (var i=0; i<Window.windows.length; i++) {
            if (Window.windows[i].visible) Window.windows[i].hide();
        }
    }
    
    window.onresize = function() {
        for (var i=0; i<Window.windows.length; i++) {
            if (Window.windows[i].visible) Window.windows[i].position();
        }
        $('#windowBack').css({'width' : (document.documentElement && document.documentElement.clientHeight?document.documentElement.clientWidth:document.body.clientWidth) + "px", 'height' : (document.documentElement && document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight) + "px", 'position' : 'absolute'});
    };
    
    /* MSIE 6 doen't support position fixed */
    if ($.browser.msie && $.browser.version < 8) {
    	var wb = $('#windowBack').css({'width' : (document.documentElement && document.documentElement.clientHeight?document.documentElement.clientWidth:document.body.clientWidth) + "px", 'height' : (document.documentElement && document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight) + "px", 'position' : 'absolute'});
    	
    	$(window).bind('scroll', function(){
    		wb.css('top', getBodyScrollTop()+"px");
	        for (var i=0; i<Window.windows.length; i++) {
	            if (Window.windows[i].visible) Window.windows[i].position();
	        }
    	}).scroll();
    }
});


function getBodyScrollTop()
{
  	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

/* Window class */
var Window = Base.extend({
    constructor: function(id) {
        this.element = $('#'+id).get();
        $(this.element).css( { height: $(this.element).height() + 'px' } );
        if (!Window.windows) {
            Window.windows = [];
        }
        Window.windows.push(this);
        
        if ($.browser.msie && $.browser.version < 7) {
            $(this.element).css('position', 'absolute');
        }
        
        var el = this;
        $(this.element).find('.close-button').click(function(){
            el.hide();
        });
    },
    
    show: function() {
        $('#windowBack').show();
        this.position();
        $(this.element).show();
        this.visible = true;
    },
    
    position: function() {
        var windowSize = this.getWindowSize();
        $(this.element).css({
            left: (windowSize.width - $(this.element).width())/2,
            top: (windowSize.height - $(this.element).height())/2
        })
        
        if ($.browser.msie && $.browser.version < 7) {
	        $(this.element).css({
	            top: (((windowSize.height - $(this.element).height())/2)+getBodyScrollTop())
	        })	
        }
    },
    
    hide: function() {
        $('#windowBack').hide();
        $(this.element).hide();
        this.visible = false;
    },
    
    getWindowSize: function() {
        var myWidth = 0, myHeight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return {width: myWidth, height: myHeight};
    }   
});

/* WindowAddPost class */
var WindowAddPost = Window.extend({
    show: function(editMode, postId) {
        if (editMode) {
            $(this.element).find('form').hide().attr('action', profileBlogUrl+'/'+postId);
            $(this.element).find('.indicator').show();
            $('#addPostWindowAction').val('update');
            $('#addPostWindowSubmit').val('Исправить');
            $.get(profileBlogUrl+'/'+postId, {'ajax': 1}, function(data, status){
                eval('data = '+data);
                $('#addPostWindowTitle').val(data.title);
                $('#addPostWindowText').val(data.text.replace(/\\n/g, '\n'));
                $(this.element).find('.indicator').hide();
                $(this.element).find('form').show();
            });
        } else {
            $(this.element).find('form:hidden').show().attr('action', profileBlogUrl+'/'+'add');
            $(this.element).find('.indicator').hide();
            $('#addPostWindowAction').val('insert');
            $('#addPostWindowSubmit').val('Добавить');
            $('#addPostWindowTitle').val('');
            $('#addPostWindowText').val('');
        }
        this.base();
    }
});

/* WindowAddClubPost class */
var WindowAddClubPost = Window.extend({
    show: function(editMode, postId) {
	    if (editMode == 'comment') {
            $(this.element).find('form:hidden').show().attr('action', profileBlogUrl+'/'+'action');
            $(this.element).find('.indicator').hide();
            $('#addClubPostWindowAction').val('comment');
            $('#addClubPostWindowPostId').val( postId );
            $('#addClubPostWindowSubmit').val('Комментировать');
            $('#addClubPostFormHeading').text('Добавление комментария');
            $('#addClubPostWindowTitle').val('');
            $('#addClubPostWindowText').val('');
	    } else if (editMode == 'edit') {
            $(this.element).find('form').hide().attr('action', profileBlogUrl+'/'+'action');
            $(this.element).find('.indicator').show();
            $('#addClubPostWindowAction').val('update');
            $('#addClubPostWindowPostId').val( postId );
            $('#addClubPostWindowSubmit').val('Исправить');
            $('#addClubPostFormHeading').text('Редактирование комментария');
            $.get(profileBlogUrl+'/'+'action', {'get_post': 1, 'post_id': postId}, function(data, status){
                eval('data = '+data);
                if (data.result == 'error') {
                	alert(data.message);
                } else {
                    $('#addClubPostWindowTitle').val(data.post.title);
                    $('#addClubPostWindowText').val(data.post.text.replace(/\\n/g, '\n'));
                    $(this.element).find('.indicator').hide();
                    $(this.element).find('form').show();
                }
            });
        } else {
            $(this.element).find('form:hidden').show().attr('action', profileBlogUrl+'/'+'action');
            $(this.element).find('.indicator').hide();
            $('#addClubPostWindowAction').val('insert');
            $('#addClubPostWindowSubmit').val('Добавить');
            $('#addClubPostFormHeading').text('Добавление записи');
            $('#addClubPostWindowTitle').val('');
            $('#addClubPostWindowText').val('');
        }
        this.base();
    }
});

var WindowAddClubPostOk = Window.extend({
    show: function() {
        this.base();
    }
});

/* WindowQuestion class */
var WindowQuestion = Window.extend({
    constructor: function(id) {
        this.base(id);
        var self = this;
        $(this.element).find('form').ajaxForm(function(data){
            eval("data = "+data);
            if (data.result == 'error') {
                $('#questionWindowError').text(data.message);
            } else if (data.result == 'ok') {
                $('#questionForm').hide();
                $('#questionWindowSuccess').show().find('p').text(data.message);
                self.closeTimeout = setTimeout(function(){
                    questionWindow.hide();    
                }, 5000);
            }
        });
    },
    
    show: function() {
        $(this.element).find('form').show();
        $('#questionWindowSuccess').hide();
        $(this.element).find("input[type='text'], textarea").val('');
        this.base();
    },
    
    hide: function() {
        clearTimeout(this.closeTimeout);
        this.base();
    }
});

/* WindowChangeMood class */
var WindowChangeMood = Window.extend({
	constructor: function(id) {
		var self = this;
		$('#changeMoodForm').ajaxForm(function(data){
			eval("data = "+data);
			if (data.result == 'error') {
				$('#changeMoodWindowError').text(data.message);
			} else if (data.result == 'ok') {
				$('.mood-phrase a').text($('#changeMoodWindowMood').val());
				self.hide();
			}
		});
		this.base(id);
	},
	
    show: function() {
        $('#changeMoodWindowMood').val($('.mood-phrase a').text());
		this.base();
    }
});

/* WindowMessage class */
var WindowMessage = Window.extend({
	constructor: function(id) {
		var self = this;
		$('#messageWindowButton').click(function(){
			self.hide();
		});
		this.base(id);
	},
	
    show: function(text) {
		$('#messageWindowText').html(text);
		this.base();
    }
});


/* WindowConfirm class */
var WindowConfirm = Window.extend({
	constructor: function(id) {
		var self = this;
		this.base(id);
	},
	
    show: function(text, okCallback, scope, noCallback, noscope, okText, cancelText) {
		$('#confirmWindowText').html(text);
		if (okText) {
			$('#confirmWindowButtonOk').val(okText);
		}
		if (cancelText) {
			$('#confirmWindowButtonCancel').val(cancelText);
		}
		
		var self = this;
		var clickCallback = function(){
			okCallback.call(scope);
			$('#confirmWindowButtonOk').unbind('click', clickCallback);
			self.hide();
		};
		$('#confirmWindowButtonOk').bind('click', clickCallback);
		
		if (noCallback) {
			var noclickCallback = function(){
				noCallback.call(noscope);
				$('#confirmWindowButtonCancel').unbind('click', noclickCallback);
				self.hide();
			};
			$('#confirmWindowButtonCancel').bind('click', noclickCallback);
		}
		else {
			$('#confirmWindowButtonCancel').click(function(){
				self.hide();
			});
		}
		
		this.base();
    }
});

/* WindowChoose class */
var WindowChoose = Window.extend({
	constructor: function(id) {
		var self = this;
		$('#chooseWindowButtonCancel').click(function(){
			self.hide();
		});
		this.base(id);
	},
	
    show: function(param, okCallback, scope) {
		$('#choosePreloader').show();
		$('#choosePostFormDiv').hide();
		$('#chooseWindowText').html(param.title);
		$('#choosePostWindowError').html('');
		
		//$('#chooseListContests')
        $.post(profileUrl, {'get_contests': 1, 'type': param.type}, function(data, status){
            eval('data = '+data);
            if (data.result == 'error') {
            	alert(data.message);
            } else if (data.result == 'empty') {
            	alert('В данный момент конкурсы не проводятся');
            } else if (data.result == 'ok') {
            	$('#chooseListContests').empty();
            	for (var i in data.items) {
            		var item = data.items[i];
            		
            		$('#chooseListContests').append(
            		    '<div>'+
            		      '<input type="radio" name="contest_id" value="'+item.id+'" id="i_contest_'+item.id+'" /> '+
            		      '<label for="i_contest_'+item.id+'">'+item.title+'</label>'+
            		    '</div>'
            	    );
            	}
            	$('#chooseListContests input:first').attr('checked', 'checked');
            	$('#choosePostFormDiv').show().find('form').attr('action', contestUrl+'/nominate/'+param.type+'/'+param.item_id);
            	$('#chooseOkCancelBlock').show();
            }
        });
		this.base();
    },
    
    showSuccess: function(data) {
        if (data.type == 'photo') {
        	$('#photo_'+data.item_id).remove();
            if (!$('#photosNominated h2').get(0)) $('#photosNominated').append('<h2>На конкурс</h2>')
            $('#photosNominated h2').after(data.item);
            alignPhotosByHeight();
            this.hide();
            messageWindow.show('Эта фотография отправлена на конкурс от Маленькой феи. Удачи!');
        } else {
        	$('#post_'+data.item_id).replaceWith(data.item);
        	this.hide();
        }
    }
	/*
    show: function(text, okCallback, scope) {
		$('#chooseOkCancelBlock').hide();
		$('#chooseWindowText').html(text);
		var self = this;
		var clickCallback = function(){
			okCallback.call(scope);
			$('#chooseWindowButtonOk').unbind('click', clickCallback);
			self.hide();
		};
		$('#chooseWindowButtonOk').bind('click', clickCallback);
		this.base();
    }
    */
});

/* WindowPhoto class */
var WindowPhoto = Window.extend({
	constructor: function(id) {
		this.base(id);
		//$(this.element).find('.annotation').css('height', 0);
		var self = this;
		$(this.element).find('.picture img').hide();//.bind('load', this.fitSize);
	},
	
	fitSize: function(){
		var sizes = photoWindow.getWindowSize();
		var imgWidth, imgHeight;
		var titleHeight = $(photoWindow.element).find('.annotation').outerHeight(true);
		if (sizes.width / sizes.height < ($(this).attr('width')+92+20) / ($(this).attr('height')+80+20))
		{
			if ($(this).attr('width')+92+20 > sizes.width) {
				imgWidth = sizes.width-92-20;
				imgHeight = $(this).attr('height') * (imgWidth / $(this).attr('width'));
			}	
		} else {
			if ($(this).attr('height')+80+20+titleHeight > sizes.height	) {
				imgHeight = sizes.height-80-20-titleHeight;
				imgWidth = $(this).attr('width') * (imgHeight / $(this).attr('height'));
			}	
		}
		if (!imgWidth && !imgHeight) {
			imgWidth = $(this).attr('width');
			imgHeight = $(this).attr('height');
		}
		$(photoWindow.element).find('.picture img, .picture').attr({
			'width': imgWidth,
			'height': imgHeight
		}).show();
		$(photoWindow.element).css({
			'width': (imgWidth+98)+"px",
			'height': (imgHeight+80+titleHeight)+"px"
		});
		$(this).show();
		photoWindow.position();
	},
	
    show: function(imgSrc, text) {
		if (text) {
			$(this.element).find('.annotation').html(text);
		} else {
			$(this.element).find('.annotation').html('');
		}
		$(photoWindow.element).css({
			width: '300px',
			height: '300px'
		});
		var img = $(photoWindow.element).find('.picture img');
    	img.attr('src', imgSrc);
		this.base();
		var tempImage = new Image();
		tempImage.src = imgSrc;
		var self = this;
		var interval = null;
		var checkImageLoaded = function(){
			if (tempImage.complete) {
				if (interval) clearInterval(interval);
				self.fitSize.apply(tempImage);
			}
		}
		checkImageLoaded();
		if (!tempImage.complete) interval = setInterval(checkImageLoaded, 100);
    },
	
	hide: function() {
		var img = $(this.element).find('.picture img').hide().get(0);
		img.src = undefined;
		img.setAttribute('width', null);
		img.setAttribute('height', null);
        this.base();
    }
});

