/*
Contents

1. Global
2. Homepage
3. Register Process
4. Lists
5. Secret
*/

$(document).ready(function(){    
    
    /************************/
    //1. Global - start
    /************************/
    //Vars
    var animDur = 300; //animation duration
    var $overlay = $('#overlay');
    
    //Cufon fonts
	Cufon.replace('h1, #content-box .editions-list li a', { fontFamily: 'Plantin Std' });
	
	//Forms validation and submission
	//..input text
	var canRegister = false;
	$('form.generic input, form.generic textarea, form.generic select')
	.focus(function(){
	    $(this).addClass('focus');
	    if ( $(this).val()==$(this).attr('title') ){
	        $(this).val('');
	    }
	    if ($(this).is('select')){
	        $(this).removeClass('error');
	    }
	})
	.blur(function(){
	    $(this).removeClass('focus')
	    if ( $(this).val()=='' ){
	        $(this).val($(this).attr('title'));
	    }
	})
	.keydown(function(e){
	    $(this).removeClass('error');
	});
	//...validation
	$('form.generic input[type=submit]')
	.mousedown(function(){
	    checkFields($(this).parents('form.generic'))
	})
	.mouseup(function(){
	    rollBackErrorFlashes($(this).parents('form.generic'));
	})
	//..pressing space when over submit
	.keydown(function(e){
	    if ( e.keyCode==32 ){
	        checkFields($(this).parents('form.generic'));
	    }
	})
	.keyup(function(e){
	    if ( e.keyCode==32 ){
	        rollBackErrorFlashes($(this).parents('form.generic'));
	    }
	});
	//...pressing enter in form
	$('form.generic input[type=text],, form.generic input[type=password], form.generic select')
	.keydown(function(e){
	    if ( e.keyCode==13 ){
	        checkFields($(this).parents('form.generic'));
	    }
	})
	.keyup(function(e){
	    if ( e.keyCode==13 ){
	        rollBackErrorFlashes($(this).parents('form.generic'));
	    }
	});
	function checkFields($form){
	    canRegister =  allRequiredFieldsCompleted($form);
	    if ( !canRegister ){
	        $(this).addClass('errorFlash');
	    }
	}
	function rollBackErrorFlashes($form){
	    $form.find('.errorFlash').removeClass('errorFlash');
	}
	$('form.generic').submit(function(){
	    if ( !canRegister ){
	        return false;
	    }
	});
	
	//Show log in form
	$('#register-form a.login-link').click(function(){
	    var $registerForm = $(this).parents('#register-form'),
	        $loginForm = $registerForm.siblings('#login-form');
	    $registerForm.fadeOut(animDur,function(){
	        $loginForm.fadeIn(animDur);
	    });    
	    return false;
	});
	//...hide
	$('#login-form a.back').click(function(){
	    var $loginForm = $(this).parents('#login-form'),
	        $registerForm = $loginForm.siblings('#register-form');
	    $loginForm.fadeOut(animDur,function(){
	        $registerForm.fadeIn(animDur);
	    });
    	return false;
	});
	//Replace text to password on focus
	$('#login-form input.password-dummy').focus(function(){
	    $(this).removeClass('required').hide();
	    $(this).siblings('.password').show().focus();
	})
	//Forgot password
	var canRequestMail = false;
	$('#login-form a.forgot-password:not(.sending)').mousedown(function(){
	    canRequestMail =  isValidEmailAddress(email = $('#login-form input.email').val());
	    if ( !canRequestMail ){
	        $('#login-form input.email').addClass('errorFlash').addClass('error');
	    }
	})
	.mouseup(function(){
	    $('#login-form input.email').removeClass('errorFlash');
	});
	$('#login-form a.forgot-password:not(.sending)').click(function(){
        var email = $('#login-form input.email').val(),
            $this = $(this); //keep $(this) reference
        if (canRequestMail){
            $this.addClass('sending');
    	    $.ajax({
    	        url: '/ajax/reset-password/',
                data: 'email=' + email,
                success: function(){
                    $this.fadeOut(animDur, function(){
                        $this.removeClass('sending'); 
                        $this.siblings('span.sent').fadeIn(animDur).animate({opacity:1}, 3000, function(){
                            $(this).fadeOut(animDur, function(){
                                $this.fadeIn(animDur);
                            });
                        });
                    });
    	        }
    	    });
	    }
	    return false;
	});
	
	//"Change edition" pop up
	var contentHeight = $('#content').height();
    $('#top-menu p.current a').click(function(){
        if (!$('#top-menu div.editions-list').is(':visible')){
            $('#content').animate({height: '360px'}, animDur,function(){
                $(this).fadeOut(animDur);
                $('#top-menu div.editions-list').fadeIn(animDur);
            });
        }else{
            $('#top-menu div.editions-list').fadeOut(animDur);
            $('#content').animate({height: contentHeight}, animDur,function(){
                $(this).fadeIn(animDur);
            });
        }
        return false;
    });
    //...hide
    $('#top-menu div.editions-list a.close').click(function(){
        $('#top-menu').animate({height: '30px'}, animDur);
        $('#top-menu div.editions-list').fadeOut(animDur);
        $('#content').animate({height: contentHeight}, animDur,function(){
            $(this).fadeIn(animDur);
        });
        return false;
    });
    
	//Fix typography for secret's number (can be done server side)
	$('span.secret-number').each(function(){
    	if ( parseInt($(this).text().replace('#',''))<100 ){
    	    $(this).addClass('below100');
    	} 
	});
	
	//Pop up 'share a secret by email'
	var contentContainerHeight = $('#content-container').height();
    $('#sharing-toolbar a.email').click(function(){
        $('#sharing-toolbar').slideUp();
        $('#content-container').animate({height: '410px'}, animDur,function(){
            $('#content div.visible-content').fadeOut(animDur);
            $('#content div.email-form').fadeIn(animDur);
        });
        return false;
    });
    //...hide
    $('#content div.email-form a.close').click(function(){
        $('#sharing-toolbar').slideDown();
        $('#content-container').animate({height: contentContainerHeight}, animDur,function(){
            $('#content div.visible-content').fadeIn(animDur);
            $('#content div.email-form').fadeOut(animDur);
        });
        return false;
    });
    
    //Show facebook plugins
    $('#footer a.facebook').click(function(){
        var $footer = $('#footer'),
            $socialContent = $footer.find('#social-content'),
            $fbPopUp = $('#facebook-popup');
        if ( $footer.hasClass('open') ){
            $overlay.fadeOut(animDur);
            $socialContent.slideUp(animDur);
            $footer.removeClass('open');
        }else{
            $overlay.fadeIn(animDur);
            $socialContent.slideDown(animDur);
            $footer.addClass('open');
            $fbPopUp.hide();
            //cookie call for pop up
            if ( $('#facebook-popup').length>0 ){
        	    $.ajax({
        	        url: '/ajax/hide-facebook-box/'
        	    });
    	    }
        }
    });
    $('#footer #social-content a.close, #overlay').click(function(){
        var $footer = $('#footer'),
            $socialContent = $footer.find('#social-content');
        $overlay.fadeOut(animDur);
        $socialContent.slideUp(animDur);
        $footer.removeClass('open');
    });
    
    //Position the popup over the facebook button in the footer
    if ( $('#facebook-popup').length>0 ){
    	var $fbPopUp = $('#facebook-popup'),
    	    $fbLink = $('#footer  a.facebook');
    	$fbPopUp.css({ left: $fbLink.offset().left}).fadeIn(animDur);
    	$(window).resize(function(){
        	$fbPopUp = $('#facebook-popup');
        	$fbLink = $('#footer  a.facebook');
        	$fbPopUp.css({ left: $fbLink.offset().left});
        	$('#footer').css('bottom', '0px')
    	});
    }
    //Close it
    $('#facebook-popup a.close').click(function(){
        $(this).parent().fadeOut(animDur);
	    $.ajax({
	        url: '/ajax/hide-facebook-box/'
	    });
	    return false;
    });
	
	/************************/
	//1. Global - end
	/************************/
	
	
	
	/************************/
	//2. Homepage - start
	/************************/
	//Map secrets, scrollbar
    if (navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
        showScrollAid($('#homepage-map .secrets-list')); 
    }else{
        $('#homepage-map .secrets-list').jScrollPane({ scrollbarWidth: 4, showArrows: true, animateStep: 1, dragMaxHeight: 50});
    }
	
	/************************/
	//2. Homepage - end
	/************************/
	
	
	
	/************************/
    //3. Register Process - start
	/************************/
	//Personal info submission form
	/*$('#signedin-confirm-email #content-container input').focus(function(){
	    if ( $(this).attr('title') == $(this).val() ){
	        $(this).val('');
	    }
	}).blur(function(){
	    $(this).siblings('img.loading.' + $(this).attr('class')).show(); //show loading img
	    if ( $(this).val() == '' ){
	        $(this).val($(this).attr('title'));
	    }
	    //ajax submit the info
	    var $this = $(this); //keep $(this) reference
	    $.ajax({
	        url: 'someAjax.url',
            data: $this.attr('name') + '=' + $this.val(),
            success: function(){
	            $this.siblings('img.loading.' + $this.attr('class')).hide(); //hide loading img
    	        $this.siblings('img.success.' + $this.attr('class')).show().animate({opacity:1}, 700).fadeOut(animDur); //success
	        },
            error: function(){
	            $this.siblings('img.loading.' + $this.attr('class')).hide(); //hide loading img
	            $this.siblings('img.fail.' + $this.attr('class')).show().animate({opacity:1}, 700).fadeOut(animDur); //fail
	        }
	    });
	});*/
	
	//Change label class on click
    $('#signedin-confirm-email li label').click(function(){
        var $checkbox = $('input#' + $(this).attr('for'));
        if ( $checkbox.attr('checked') ){
            $(this).addClass('selected');
        }else{
            $(this).removeClass('selected');
        }
    });
    
    //Show "Didn't receive confirmation email" pop up
    $('#signedin-confirm-email a.didnt-receive').click(function(){
        $('#signedin-confirm-email .didnt-receive-text').fadeIn(animDur).siblings('#personal-info').animate({opacity: 0.05}, animDur);
        $.ajax({url: '/ajax/resend-signup-email/'});
        return false;
    });
    //...hide
    $('#signedin-confirm-email .didnt-receive-text a.close').click(function(){
        $(this).parents('.didnt-receive-text').fadeOut(animDur).siblings('#personal-info').animate({opacity: 1}, animDur);
    });
    
    //Datepick functionality in birthday
    $('input[name=date_of_birth]', '#personal-info').datepick({
        dateFormat: 'yyyy-mm-dd',
        yearRange: '1900:2010',
	    commandsAsDateFormat: true, 
	    prevText: '< M',
	    todayText: 'MM y',
	    nextText: 'M >'
    });
	
	/************************/
    //3. Register Process - end
	/************************/
	
	
	
	/************************/
    //4. Lists - start
	/************************/
	//Scrollbar
    if (navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
        $('.secrets-list').addClass('touch');
        showScrollAid($('#list-by-place .secrets-list, #list-by-date .secrets-list, #list-by-category .secrets-list'));
    }else{
	    $('#list-by-place .secrets-list, #list-by-date .secrets-list, #list-by-category .secrets-list').jScrollPane({ scrollbarWidth: 4, showArrows: true, animateStep: 1, dragMaxHeight: 50});
    }
	
	/************************/
    //4. Lists - end
	/************************/
	
	
	
	/************************/
    //5. Secret - start
	/************************/
    if (navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
        showScrollAid($('#secret div.secret-text'));
    }else{
	    $('#secret div.secret-text').jScrollPane({ scrollbarWidth: 4, showArrows: true, animateStep: 1, dragMaxHeight: 50});
    }
	/************************/
    //5. Secret - end
	/************************/


    
	/************************/
    //Generic Functions...
	/************************/
	
    //'All required fields completed' function
    function allRequiredFieldsCompleted($form){
        var allCompleted = true;
        $form.find('input.required, textarea.required, select.required').each(function(){
            if ( 
                ($(this).hasClass('email') && !isValidEmailAddress($(this).val())) 
                || ($(this).val()=='') 
                || ($(this).val()==$(this).attr('title'))
                || ($(this).hasClass('password') && $form.find('input.password-conf').length>0 && !passwordsMatch($(this)))
               ){
                allCompleted = false;
                $(this).addClass('errorFlash').addClass('error');                
            }
        });
        return allCompleted;
    }

     //Check if password & password validation match
    function passwordsMatch($passField) {
        return $passField.val() == $passField.parents('form.generic').find('input.password-conf').val();
    }
    

     //Email validation function
    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }
    
    
    //Add iPad/iPod/iPhone scrolling aid
    function showScrollAid($container){
        var html = '<div id="scrolling-aid"><img src="/media/images/blackTriangle.png" alt="triangle" />Σύρετε το κείμενο με τα δύο σας δάχτυλα για να δείτε περισσότερα</div>';
        $container.append(html);
    }
    //Hide scrolling aid on parent's touch
    $('body').bind('touchstart', function(){
        $('#scrolling-aid').fadeOut();
    });
	
});
