var active_star = null;
var i = 1;
var left_pos = null;
var slide_nr = 1;
var play = 1;
var slide_speed = 7000;
var slide_timeout_id = null;
var play_slideshow = true;

jQuery.fn.exists = function(){return jQuery(this).length>0;}

$(function(){
	$('.confirm').click(function(){
		var answer = confirm('Oled sa kindel, et tahad kustutada?');
  		return answer // answer is a boolean
	});
	
	$('.slide-numbers a').click(function(){
		clearTimeout(slide_timeout_id);
		if(slide_nr != $(this).attr('rel')){
			slide_nr = $(this).attr('rel'); 
			slide_nr = parseInt(slide_nr);
			$('.slide-numbers a').removeClass('active');
			$('.slide-numbers a[rel="'+slide_nr+'"]').addClass('active');		
			left_pos = (slide_nr-1)*540;
			$('.slide-info').fadeOut(400, function(){
				$('.slide-images').animate({
					'left' : '-'+left_pos+'px'
				}, 300, '', function(){
					var new_meta = $('.img-container[rel="'+slide_nr+'"] .slide-meta').html();	
					$('.slide-info').html(new_meta);
					$('.slide-info').fadeIn(400);
				});
			});			
		}
		if(play == 1){
			slide_timeout_id = setTimeout('changeSlide()', slide_speed);
		}
		return false;
	});
	var controls_height = $('.controls').height();
	
	$('.controls a.play').click(function(){
		clearTimeout(slide_timeout_id);
		$('.play').toggle();
		play = (play == 1 ? 0 : 1);
		if(play == 1){
			slide_timeout_id = setTimeout('changeSlide()', slide_speed);
		}
		return false;
	});
	
	if(play == 1){
		slide_timeout_id = setTimeout('changeSlide()', slide_speed);
	}
	
    /*$('a[title="Kustuta"]').click(function(){
        doDelete(this);
        return false;
    });*/
	if($(".datepicker").length > 0){
		$(".datepicker").datepicker();
	}

	$('a[class="loadimg"]').click(function(){
		loadImage(this);
		return false;
	});

	$('#login_username').focus(function(){
		$(this).val('');
		$(this).unbind('focus');
	});
	$('#login_password').focus(function(){
		$(this).val('');
		$(this).unbind('focus');
	});
    if($('.global_message').exists()){
    	setTimeout(function(){
    		jQuery('.global_message').slideUp(700, function(){
    			jQuery('.global_message').remove();
    		});
    	}, 2000);
    }
    
    $('ul.star-rating li a').live('click', function(){
    	saveRate(this);
    	return false;
    });
    
    $('ul.menu li').mouseover(function(){
    	submenu_nr = $(this).attr('rel');
    	$('#submenu'+submenu_nr).show();
    });
    $('ul.menu li').mouseout(function(){
    	submenu_nr = $(this).attr('rel');
    	$('#submenu'+submenu_nr).hide();
    });
    
    $('a.add_favorite').click(function(){
    	addFavorite(this);
    	return false;
    });
    $('ul.star-rating').live('mouseover',function(){
    	$('ul.star-rating li a').each(function(){
    		if($(this).hasClass('active'+i)){
    			active_star = 'active'+i;
    		}
    		$(this).removeClass('active1').removeClass('active2').removeClass('active3').removeClass('active4').removeClass('active5');
    		i++;
    	});
    	   	
    });
    $('ul.star-rating').live('mouseout', function(){
    	if(active_star != null){
			var nr = active_star.substring(active_star.length - 1);
    		if(nr == '1')  $('ul.star-rating li a.one-star').addClass('active1');
    		if(nr == '2')  $('ul.star-rating li a.two-stas').addClass('active2');
    		if(nr == '3')  $('ul.star-rating li a.three-stars').addClass('active3');
    		if(nr == '4')  $('ul.star-rating li a.four-stars').addClass('active4');
    		if(nr == '5')  $('ul.star-rating li a.five-stars').addClass('active5');
    	}
    });
    
	// create overflow elements
	var create_overflow = function() {
		$('<div id="overflow"></div><div id="overflow_content"><div id="overflow_innercontent"><div id="from_ajax"></div></div><a id="overflow_close"><strong>X</strong></a></div>').appendTo('body');
		$('#overflow').height($(document).height()).width($(document).width()).click(overflow_close);
		$('#overflow_close').click(overflow_close);
	}();
    
	// enable overflow helpers
	$('#page-content a.overflow').click(function(e) {
		var overflow_width = '0';
		if($(this).attr('rel') == 'small'){
			$('#overflow_content').css('width', '600px');
			var overflow_width = '600';
		}
		overflow_open($(this).attr('href')+' #slaid-page > *', '#from_ajax', $(this), e.pageX, e.pageY, overflow_width); return false; })
	$(window).resize(function() {
		overflow_set();
	});
	$('#overflow_innercontent').show().css('overflow','hidden');
    
	$('#old-upload').live('change', function(){
		ajaxFileUpload();
		return false;
	});
    
    
	// create helper elements for tooltips
	$('<div id="tTip"><div class="pointer"><div class="tip"></div></div></div>').appendTo('body');
	$('#tTip').animate({ opacity: 0 }, 0);
	
	$('#video_url').blur(function(){
		if($(this).val() != ''){
			$.post('/videoinfo', {video_url : $(this).val()}, function(response){
				if(response.error){
					alert(response.error);
				} else {
					$("#video_title").val(response.video_title);
					$("#video_description").val(response.video_description);
				}
			}, 'json');
		}
	});
	
	initTTips();
	
	initSlaidShow();
    
    $('#search').focus(function(){
    	if($(this).attr('value') == 'Otsi...'){
    		$(this).attr('value', '');
    	}
    	//alert('focus');
    }).blur(function(){
    	if($(this).attr('value') == ''){
    		$(this).attr('value', 'Otsi...');
    	}
    	//alert('blur');
    });
    
    $('#search').next('input[type="image"]').click(function(){
    	if($('#search').attr('value') == 'Otsi...' || $('#search').attr('value') == ''){
    		return false;
    	}
    });
    
    $('.status-content .show-more').click(function(){
    	$('.user-status .status').slideToggle();
    	return false;
    });
    
	$('.tbl_emails tbody:first input[type="text"]:last').live('keyup', function(){
		var rel = parseInt($(this).attr('rel'))+1;
    	var el = $(this).parents('tr:last').clone();
    	
    	el.children('td').children('input').attr('rel', rel);
    	el.children('td').children('input').attr('id', 'email-box'+rel);
    	el.children('td').children('input').attr('value', '');
    	el.children('th').children('label').attr('for', 'email-box'+rel);
    	
    	el.appendTo('.tbl_emails tbody:first');
    });
    
    $('#add_new_group_form').fadeOut(200);
    $('#add_new_group_form_link').fadeIn(200);
    $('#add_new_group_form_link').click(function(){
    	$('#add_new_group_form_link').hide();
    	$('#add_new_group_form').fadeIn(200);
    	
    	return false;
    });
	
	$('#chk-private').live('change', function(){
		if($('#chk-private').attr('checked')){
			$('#show_private_info').fadeIn();
		}
		else{
			$('#show_private_info').fadeOut();
		}
	});
});


// enable nice and simple tooltips (<a class="tooltip" title="Something"...)
var initTTips = function() {
	$('.tooltip').each(function() {
		$(this).unbind('mouseover mouseout');
		var text = $(this).attr('title');
		var pos = $(this).offset();
		$(this).bind('mouseover', function() {
			$('#tTip .tip').html($(this).attr('title')).parents('#tTip').stop().css('top', pos.top+$(this).height()).css('left', pos.left-15).animate({ top: pos.top+$(this).height()+5, opacity: 1 }, 'fast');
			$(this).attr('title','');
		}).bind('mouseout', function() {
			$('#tTip').animate({ opacity: 0, top: pos.top+$(this).height()-5 }, 'fast', function() { $(this).css({top: -100, left: -100}); });
			$(this).attr('title',text);
		});
	});
}

var changeSlide = function()
{
	if(play == 1){
		slide_nr = slide_nr + 1;

		if(slide_nr > $('.slide-images .img-container').length){
			slide_nr = 1;
			$('.slide-images').fadeOut(200, function(){
				$('.slide-images').css('left', '0px').fadeIn(200);
			});
		}
		$('.slide-numbers a').removeClass('active');
		$('.slide-numbers a[rel="'+slide_nr+'"]').addClass('active');		
		left_pos = (slide_nr-1)*540;
		$('.slide-info').fadeOut(400, function(){
			$('.slide-images').animate({
				'left' : '-'+left_pos+'px'
			}, 300, '', function(){
				var new_meta = $('.img-container[rel="'+slide_nr+'"] .slide-meta').html();	
				$('.slide-info').html(new_meta);
				$('.slide-info').fadeIn(400);
			});
		});
		slide_timeout_id = setTimeout('changeSlide()', slide_speed);
	}
}

var doDelete = function(link)
{
    var el = $(link).parents('div.thumb100');
    $.get($(link).attr('href') + '/ajax', 0, function(response){
        $(el).fadeOut('fast', function(){
            if($(this).parent().attr('id') == 'profile_pic_container'){
                $('#upload_functions').fadeIn();
            }
            $(this).remove();
        });
    });
}

var loadImage = function(link)
{
	var dat = $(link).attr('rel');
	$('#loader').fadeIn('fast');
	$.post('/ajax/getNextPic', {data : dat}, function(response){
		if(!response.error) {
			$('#loader').fadeOut('fast');
			
			$('#teler554').css('background', '#000000 url(\'/photos/pic554x364/'+response.pic_name+'\') center center no-repeat');
			 $(link).attr('rel', response.rel);
		}
	}, 'json');
}

var saveRate = function(link)
{
	var rate = $(link).attr('rel');
	var item = $(link).parents('ul').attr('rel');
	$.post('/ajax/save_rate', {item : item, rate: rate}, function(response){
		if(response != 'false'){
			active_star = null;
			//$('#rate'+item).html(response).fadeIn();
			$('ul.star-rating li a').each(function(){
				$(this).removeClass('active1').removeClass('active2').removeClass('active3').removeClass('active4').removeClass('active5');
			});
			if(response == '1') $('a.one-star').addClass('active1');
			else if(response == '2') $('a.two-stars').addClass('active2');
			else if(response == '3') $('a.three-stars').addClass('active3');
			else if(response == '4') $('a.four-stars').addClass('active4');
			else if(response == '5') $('a.five-stars').addClass('active5');
		} else {
			alert('Pead olema sisse logitud, et hinnata');
		}
	});
}

var addFavorite = function(link){
	$.post('/ajax/add_favorite', {profile : $(link).attr('rel')}, function(response){
		if(response == 'add'){
			$(link).removeClass('favorite_star').addClass('favorite_star_active');
		} else if(response == 'remove') {
			$(link).removeClass('favorite_star_active').addClass('favorite_star');
		} else if(response == 'login'){
			alert('Lemmikuks märkimiseks pead olema sisse loginud.');
		}
	});
}

// loads data into the overflow element
var overflow_open = function(uri, element, link, cX, cY, overflow_width) {
	if (element == '' || typeof(element)=='undefined') { element = '#from_ajax'; }
	if (typeof(link)=='undefined') { link = null; }
	$('select, .flashbanner_innercontent').hide();
	overflow_set(false, overflow_width);
	$('#overflow').stop().css({opacity: 1}).fadeIn('fast', function() { });
	$('#overflow_content').stop().fadeIn('fast');
	$('#overflow_innercontent').stop().css('height','40px').animate({height: '250px'},'fast').addClass('loading');
	$(element).load(uri, '', function (responseText) {
		
		var script = $(responseText).find('script').html();
		
		if(play_slideshow){
			ss.play();
		}
		//eval(script); // Execute javascript
 		var myFucn12345 = new Function(script);
 		myFucn12345();
		
		$(element+' a.overflow').each(function() {
			$(this).click(function(ev) {
				overflow_set(overflow_open($(this).attr('href')+' #content-inner > *', '#from_ajax', ev.pageX, ev.pageY));
				return false;
				ev.preventDefault();
			});
		});

		overflow_reveal(link, cX, cY);
	});
}

// prepares overflow to be shown (makes sure the background filler is large enough)
var overflow_set = function() {
	var callback = (arguments[0] ? arguments[0] : '');
	var overflow_width = (arguments[1] ? arguments[1] : '0');
	if(overflow_width > 0){
		$('#overflow').height($(document).height()).width(overflow_width).click(overflow_close); // sets the size of the overflow background filler
		normalX = overflow_width/2 - 0;
		normalY = $(window).scrollTop() + 100;
	} else {
		$('#overflow').height($(document).height()).width($(window).width()).click(overflow_close); // sets the size of the overflow background filler
		normalX = $(window).width()/2 - 600;
		normalY = $(window).scrollTop() + 5;
	}
	
	
	$('#overflow_content').css('left', normalX).css('top', normalY); // position the overflow content box
	if (typeof(callback) == 'function') { callback(); }
}

// closes the overflow and clears its contents.
var overflow_close = function() {
	var callback = (arguments[0] ? arguments[0] : '');
	$('#overflow_innercontent').animate({height: '40px'},'fast');
	$('#overflow').fadeOut('fast', function() {
		$('select, .flashbanner_innercontent').show();
		$('#from_ajax').html(''); // clear the overflow box content
		$('#overflow_content').fadeOut('fast', function() { // hide the overflow background filler and the box
			$('#overflow_content, #overflow').hide();
			if (typeof(callback) == 'function') { callback(); }
		});
	});
}

// displays the overflow background filler and the overflow content box
var overflow_reveal = function(link, cX, cY) {
	totalH = $('#overflow_innercontent').css('height', 'auto').height(); // fetch the overall height of overflow contents
	$('#overflow_innercontent').css('height', '250px'); // set the height back to minimal
	$('#overflow_innercontent').animate({height: totalH},'fast', function() {
		$(this).css({height: ''});
	}).removeClass('loading'); // ...and then animate the sliding down of the box. nice and juicy!
}

var ajaxFileUpload = function()
{
	$('#upload_functions').fadeOut('fast', function(){
		$('#profile_pic_container').fadeIn('fast', function(){
			$('#profile_pic_container').removeClass('hidden');
			$('#profile_pic_container .thumb100').addClass('loading');
			
		})
	});
    
    $.ajaxFileUpload
    (
        {
            url:'/convert/'+$('#old-upload').attr('rel'), 
            secureuri:false,
            fileElementId:'old-upload',
            dataType: 'json',
            success: function (data, status)
            {
            	if(data.error){
            		$('<div class="global">'+data.error+'</div>').appendTo('#upload_functions');
            		$('#profile_pic_container').fadeOut('fast', function(){
            			$('#profile_pic_container').addClass('hidden');
						$('#profile_pic_container .thumb100').removeClass('loading');
            			
						$('#upload_functions').fadeIn('fast');
					});
            	}
            	else{
            		$('<img src="'+data.img_url+'" alt="" />').appendTo('#profile_pic_container .thumb100');
            	}
            },
            error: function (data, status, e)
            {
                alert(e);
            }
        }
    )
    
    return false;

}

var initSlaidShow = function()
{
	var pausebtn = $('#pause-btn'); //pause_btn
	var bbtn = $('#back_btn'); //back_btn
	var fbtn = $('#forward_btn'); //forward_btn
	
	ss = new slideshow();
	if(play_slideshow){
		ss.play();
	}
	
	$(pausebtn).live('click', function(){
		if($(this).attr('rel') == 'pause'){
			$(this).html('<img src="/i/260909/play.png" alt="Mängi" />');
			$(this).attr('rel', 'play');
			ss.pause();
		}
		else{
			$(this).html('<img src="/i/260909/pause-button.png" alt="Paus" />');
			$(this).attr('rel', 'pause');
			ss.play();
		}
		return false;
	});
	
	$(bbtn).live('click', function(){
		picsLineUpdate('back', $(this).attr('rel'), $('#slaid-page-content').attr('rel'));
		picItmeUpdate($(this).attr('rel'), $('#slaid-page-content').attr('rel'));
		return false;
	});
	
	$(fbtn).live('click', function(){
		picsLineUpdate('forward', $(this).attr('rel'), $('#slaid-page-content').attr('rel'));
		picItmeUpdate($(this).attr('rel'), $('#slaid-page-content').attr('rel'));
		return false;
	});
	
	$('.slaid-pics-area a').live('click', function(){
		picsLineUpdate('forward', $(this).attr('rel'), $('#slaid-page-content').attr('rel'));
		picItmeUpdate($(this).attr('rel'), $('#slaid-page-content').attr('rel'));
		return false;
	});
}

function slideshow(){
	this.repeat = true;
	this.timeout = 3000;
	this.direction = 'right';
	
	this.play = function(timeout){
		this.pause();
		
		if(timeout){
			this.timeout = timeout;
		}
		
		this.timeoutid = setTimeout("ss.loop()", timeout);
	}
	
	this.pause = function(){
		if(this.timeoutid != 0){
			clearTimeout(this.timeoutid);
			this.timeoutid = 0;
		}
	}
	
	this.loop = function(){
		if(this.direction == 'right'){
			if($('.slaid-pics-area a.active').next('a').exists()){
				var next_a = $('.slaid-pics-area a.active').next('a');
			}
			else if($('.slaid-pics-area a.active').prev('a').exists()){
				var next_a = $('.slaid-pics-area a.active').prev('a');
				this.direction = 'left';
			}
			else{
				var next_a = $('.slaid-pics-area a.active');
				ss.pause();
			}
		}
		else{
			if($('.slaid-pics-area a.active').prev('a').exists()){
				var next_a = $('.slaid-pics-area a.active').prev('a');
			}
			else if($('.slaid-pics-area a.active').next('a').exists()){
				var next_a = $('.slaid-pics-area a.active').next('a');
				this.direction = 'right';
			}
			else{
				var next_a = $('.slaid-pics-area a.active');
				ss.pause();
			}
		}
		//Järgmise pildi jaoks vaja teha ajax päring, mis annab jada esimese pildi id
		//var next_a = $('.slaid-pics-area a:first');
		
		picsLineUpdate('forward', $(next_a).attr('rel'), $('#slaid-page-content').attr('rel'));
		picItmeUpdate($(next_a).attr('rel'), $('#slaid-page-content').attr('rel'));
		if(this.timeoutid != 0){
			this.timeoutid = setTimeout("ss.loop()", this.timeout);
		}
	}
}

var picsLineUpdate = function(where, item_info, gal_type)
{
	$.post('/gallery/pics_line', {where_to : where, item_info_string : item_info, type : gal_type}, function(response){
		$('.slaid-pics-line-pics').hide();
		$('.slaid-pics-line-pics').html(response);
		$('.slaid-pics-line-pics').fadeIn("slow");
	});
}

var picItmeUpdate = function(item_info, gal_type)
{
	$.post('/gallery/big_item', {item_info_string : item_info, type : gal_type}, function(response){
		$('.slaid-main-item').hide();
		$('.slaid-main-item-info').hide();
		$('.slaid-main-item').html(response.src);
		$('.slaid-main-item-info').html(response.info);
		$('.slaid-main-item').fadeIn("slow");
		$('.slaid-main-item-info').fadeIn("slow");
	}, 'json');
}
