var countdown_date = '';
var city_countdown = '';

// ------------------------------------------------------------------------

// Countdown
function Countdown(then) {
 	this.then = then;
 	
 	function setElement(id, value, title) { 	  
 		if (value.toString().length < 2) { 		 
 	    	value = "0" + value;
 		} 	
 		window.document.getElementById(id).innerHTML = value+title;
 	}
 	
 	function countdown() {
 		now  		  = new Date();
 	  	diff		  = new Date(this.then - now); 	  	
 		seconds_left  = Math.floor(diff.valueOf() / 1000); 	
        if (seconds_left < 0) {
         seconds  = 0;
 		 minutes  = 0;
 		 hours    = 0;
 		 days     = 0;
        } else {
 		 seconds  = Math.floor(seconds_left / 1) % 60;
 		 minutes  = Math.floor(seconds_left / 60) % 60;
 		 hours    = Math.floor(seconds_left / 3600) % 24;
 		 days     = Math.floor(seconds_left / 86400) % 86400;
        } 		
 		setElement('countdown-days', days, '<br /><em>Днів</em>');
 		setElement('countdown-hours', hours, '<br /><em>Годин</em>');
 		setElement('countdown-minutes', minutes, '<br /><em>Хвилин</em>');
 		setElement('countdown-seconds', seconds, '<br /><em>Секунд</em>'); 		
 		countdown.timer = setTimeout(countdown, 1000);
 	} 	
 		
 	function start() {
 		this.timer = setTimeout(countdown, 1000);
 	}
 	
 	start(then);	
}
 
// ------------------------------------------------------------------------
// Vkontakte
 
function vk_login() {    
    VK.Auth.login(null, 1 | 2);    
}

function login_event() {	
	getInitData();		
}

function vk_logout() {
	VK.Auth.logout(function() {	});
}

function logout_event() { }

function getInitData() {
	var code;
	code = 'return {';
	code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
	code += ',info: API.getGroupsFull({gids:1})[0]';	
	code += '};';
	VK.Api.call('execute', {'code': code}, onGetInitData);
}

function onGetInitData(data) {
	var r, i, j, html;
	if (data.response) {	   
		r = data.response;		
		if (r.me) {                                    
		    save_user_data(r.me.uid, r.me.first_name, r.me.last_name, r.me.photo);
            $('#vk_id').val(r.me.uid);	
            $('#vk_name').html(r.me.first_name+' '+r.me.last_name);
            $('.vkontakte_info').show();				
		}
	} else {
		//
	}
}

function save_user_data(vk_id, first_name, last_name, photo) {    
    $.ajax({		
		type: 'POST',
		url: base_url + 'home/save_vk',
		data: 'vk_id='+vk_id+'&first_name='+first_name+'&last_name='+last_name+'&photo='+photo,        		
		success: function(data) {}
	});
}

// ------------------------------------------------------------------------
// Feedback form
var is_active_feedback = false;
function feedback_form() {    
    if ($('.feedback_wrapper').css('left') == '-500px' ) {        
        is_active_feedback = true;
        $('.change_wrapper').stop();
        $('.change_wrapper').css('left', '-530px');
        $('.feedback_btn').css('background-position', '0px 0px');
        $('.feedback_wrapper').animate( { left:"0px" }, 1000);                
    } else {
        is_active_feedback = false;
        $('.feedback_btn').css('background-position', '-25px 0px');
        $('.feedback_wrapper').animate( { left:"-500px" }, 1000, null, function() {
            $('.change_wrapper').css('left', '-500px');            
        });
        
    }
}

// Mr. Change form
var is_over = false;
function mr_change_form() {
    if ($('.change_wrapper').css('left') == '0px' ) {        
        $('.change_wrapper').animate( { left:"-500px" }, 1000);                        
    } else { 
        if (!is_active_feedback) {
            $('.change_wrapper').animate( 
                { left:"0px" }, 
                1000, 
                null, 
                function() { 
                    if (!is_over) mr_change_form(); 
                }
            );
        }
    }
}

function is_valid_email(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
    return email.match(re) 
}

function feedback() {
    var name = $('#feedback_name').val();
    var email = $('#feedback_email').val();
    var msg = $('#feedback_msg').val();
    
    // validation
    if (name.length == 0 || email.length == 0 || msg.length == 0) {
        $('#feedback_form_msg').html('Заповніть всі поля форми');
        return;
    }
    if (!is_valid_email(email)) {
        $('#feedback_form_msg').html('Введіть коректну E-mail адресу');
        return;
    }
    
    // sending
    $.ajax({		
		type: 'POST',
		url: base_url + 'home/feedback',
		data: 'name='+name+'&email='+email+'&msg='+msg,        		
		success: function(data) {
		    if (data == 'success') {
                $('#feedback_form_msg').html('Ваше повідомлення відправлено. Дякуємо.');
                $('#feedback_name').val('');
                $('#feedback_email').val('');
                $('#feedback_msg').val('');
                feedback_form();  
		    } else {
                $('#feedback_form_msg').html('Виникла помилка, повідомлення не було відправлено.');
		    }            
		}
	});
}

// ------------------------------------------------------------------------
// Girls images

function load_img(img_name) 
{    
  img_name = base_url + 'upload/girls/mid/' + img_name;
  var img = new Image();    
  $(img)  
    .load(function () {      
      $(this).hide();    
      $('#girl_photo')        
        .removeClass('loading')
        .empty()        
        .append(this);          
      //$(this).fadeIn();
      $(this).show();
    })        
    .error(function () {    
    })
    .attr('width', 400)        
    .attr('src', img_name);
    window.scrollTo(0,250);
}
 
// ------------------------------------------------------------------------
// Dialogs
function close_dialog() {
    $('#mask').hide();
    $('#msg_dialog').hide();
}
function close_promo_dialog() {
    $('#mask').hide();
    $('#promo_dialog').hide();
}

// ------------------------------------------------------------------------
// Presents accordion
function presents(el) {
    $('.winners').removeClass('active');
    $('.winner_title').removeClass('active');    
    $('#'+el+' .winners').addClass('active');
    $('#'+el+' .winner_title').addClass('active');
}

// ------------------------------------------------------------------------
function show_city(city_wrapper) {
    $('.city_videos').hide();
    $('#'+city_wrapper).show();    
}

// ------------------------------------------------------------------------
 
$(document).ready(function() {
    
    // Start countdown
    if (countdown_date != '') Countdown(new Date(countdown_date));
    if (city_countdown != '') Countdown(new Date(city_countdown));
   
    // Vote for girl
    $('.pr-vote, .pr-vote-disabled').mouseover(function() {        
        if ($('#vk_id').val() == '') {
            $('.vkontakte_btn').show();
            $('.voting_info').css('border', '1px solid #A9CF41')
                             .css('-moz-box-shadow', '0 0 6px #A9CF41')
                             .css('box-shadow', '0 0 6px #A9CF41')
                             .css('-webkit-box-shadow', '0 0 6px #A9CF41');
        }
    });
    $('.vkontakte_btn').mouseout(function() {               
        $('.vkontakte_btn').hide(); 
        $('.voting_info').css('border', '1px solid transparent')
                             .css('-moz-box-shadow', 'none')
                             .css('box-shadow', 'none')
                             .css('-webkit-box-shadow', 'none');   
    });
    
    $('#like_girl').click(function() {
        var vk_id = $('#vk_id').val();        
        // login with vkontakte
        if (vk_id == '') {
            vk_login();
            return;
        }
        // vote
        $('#vote_type').val('1');
        $('#vote_form').submit();
    });
    
    $('#next_girl').click(function() {
        var vk_id = $('#vk_id').val();
        if (vk_id == '') {
            // login with vkontakte
            vk_login();
            return;
            // Redirect to next girl
            //window.location.replace($('#vote_form').attr('action'));
        } else {
            // vote
            $('#vote_type').val('0');
            $('#vote_form').submit();
        }
    });
    
    // Comment
    $('#comment_btn').click(function() {
        var vk_id = $('#vk_id').val();        
        // login with vkontakte
        if (vk_id == '') {
            vk_login();
            return;
        }
        // submit comment        
        $('#comment_form').submit();
    });
    
    // Vote for video
    $('.vote-video').mouseover(function() {        
        if ($('#vk_id').val() == '') {
            $('.vkontakte_btn').show();
        }
    });
    $('.vkontakte_btn').mouseout(function() {               
        $('.vkontakte_btn').hide();    
    });
    
    $('#cool_video').click(function() {
        var vk_id = $('#vk_id').val();        
        // login with vkontakte
        if (vk_id == '') {
            vk_login();
            return;
        }
        // vote        
        $('#vote_form').submit();
    });
    
    $('#shift_video').click(function() {
        var vk_id = $('#vk_id').val();                
        if (vk_id == '') {
            vk_login();
            return;
        }
        // vote
        $('#mask').show();
        $('#promo_dialog').show();        
    });
    
    // Click share input 
    $('#share_input').click(function() {
        $('#share_input').select();    
    });  
    
    // Hiding girl rating
    setTimeout(function() { $('.girls_place').fadeOut('slow'); }, 2000);
    $('.main-photo').mouseover(function() {       
        $('.girls_place').show();
    });    
    $('.main-photo').mouseout(function() {
        $('.girls_place').hide();        
    });
    
    // Feedback
    $('.send_btn').click(function() {
        feedback();
    });    
    
    // Show number of comments on video mouse over
    $('.video_item').mousemove(function () {            
       $(this).find('.comments_num').show(); 
    });
    $('.video_item').mouseout(function () {
       $(this).find('.comments_num').hide(); 
    });          
    
    // Forms
    $('#auth_fake_pass input').focus(function() {        
        $('#auth_fake_pass').hide();        
        $('#auth_real_pass').show();
        $('#auth_real_pass input').focus();    
    });
    
    $('#auth_real_pass input').blur(function() {
        if ($(this).val() == '') {
            $('#auth_real_pass').hide();
            $('#auth_fake_pass').show();
        }                            
    });
    
    $('#reg_fake_pass input').focus(function() {        
        $('#reg_fake_pass').hide();        
        $('#reg_real_pass').show();
        $('#reg_real_pass input').focus();    
    });
    
    $('#reg_real_pass input').blur(function() {
        if ($(this).val() == '') {
            $('#reg_real_pass').hide()
            $('#reg_fake_pass').show();
        }                    
    });
    
    $('#reg_fake_pass_conf input').focus(function() {        
        $('#reg_fake_pass_conf').hide();        
        $('#reg_real_pass_conf').show();
        $('#reg_real_pass_conf input').focus();    
    });
    
    $('#reg_real_pass_conf input').blur(function() {
        if ($(this).val() == '') {
            $('#reg_real_pass_conf').hide();
            $('#reg_fake_pass_conf').show();
        }                            
    });
    
    $('.small_input input, .big_input input, .code_box input, .phone_box input').focus(function() {
        var alt = $(this).attr('alt');
        if ($(this).val() == alt) $(this).val('');
    });
    
    $('.small_input input, .big_input input, .code_box input, .phone_box input').blur(function() {
        var alt = $(this).attr('alt');
        if ($(this).val() == '') $(this).val(alt); 
    });
            
    $('.big_text textarea').focus(function() {       
       if ($(this).val() == 'Про себе') $(this).val(''); 
    });
    
    $('.big_text textarea').blur(function() {       
       if ($(this).val() == '') $(this).val('Про себе'); 
    });      
    
    var t;
    
    $('.change_wrapper').mouseover(function() {
        is_over = true;     
        if (t) clearTimeout(t);
    });
    
    $('.change_wrapper').mouseout(function() {
        is_over = false;
        if ($('.change_wrapper').css('left') == '0px') {
            t = setTimeout(function() { 
                mr_change_form();         
            }, 500);    
        }
    });     
    $('.change_btn').mouseover(function() {
        if ($('.change_wrapper').css('left') == '-500px') {
            mr_change_form();    
        }
    });
      
});