$(document).ready(function () {
    setupCookie();
    $('.quick-login-form-holder').hide();
    $('a.log-in').click(loginPopup);
    $('a.trigger_login_popup').click(loginPopup);
    $('a[rel="external"]').click(function (event) {
        window.open($(this).attr('href'));
        event.preventDefault();
    });
    if ($('body').attr('id') == 'home') {
        bookingSlider();
        testimonialRotator();
    }
    $('form').submit(function () {
        $(this).find('input[type=submit]').css('opacity', 0.3).attr('disabled', 'disabled');
        $(this).find('input,select,textarea').attr('readonly', true);
        document.body.style.cursor = "wait";
    });
    if ($('body').attr('id') == 'features') {
        featuresScroller();
    }
    $('#tothetop').click(function (event) {
        $("html:not(:animated),body:not(:animated)").animate({
            scrollTop: 0
        });
        event.preventDefault();
    });
    $('#footer_login').click(function (event) {
        $("html:not(:animated),body:not(:animated)").animate({
            scrollTop: 0
        }, 700);
        setTimeout(loginPopup, 700);
        event.preventDefault();
    });
    var appname = window.document.location.hostname.match(/pc\.no\.genbook\.com/) ? "/bookmgr" : "/manager";
    $('.quick-login-form').attr('action','https://' + window.document.location.hostname + appname + '/login');
//    $('.quick-login-form, #login-form').submit(function() {
//        setAutologinCookie(this);
//    });
    $('.tryMobile').click(function() {
        window.location = iPhoneOS() ? 'https://m.'+window.location.host.replace('www.','') : 'https://m.'+window.location.host.replace('www.','')+'/master';
        return false;
    });
});

function iPhoneOS() {
    var version = navigator.userAgent.match('iPod') || navigator.userAgent.match('iPhone') ? 1.0 : false;
    if ((match = /iPhone OS (.*) like Mac OS X/.exec(navigator.userAgent))) {
        version = parseInt(match[1].replace('_', ''), 10) / 100;
        if (version < 1) {
            version *= 10;
        }
    }

    return version;
}

function androidOS() {
    var regex = /android.*mobile/gi;
    return regex.test(navigator.userAgent);
}

function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}
function getCookie(c_name){
    var i,x,y,cookies=document.cookie.split(";");
    for (i=0;i<cookies.length;i++) {
        x=cookies[i].substr(0,cookies[i].indexOf("="));
        y=cookies[i].substr(cookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {return unescape(y);}
    }
}

//function setAutologinCookie(form) {
//    if (form.os_cookie.checked) {
//        SetCookie('loggedin', 'true', 365, "/", ".genbook.com");
//        SetCookie('loggedin', 'true', 365, "/");
//    } else if (GetCookie('loggedin')!=null) {
//        SetCookie('loggedin', 'false', 365, "/", ".genbook.com");
//        SetCookie('loggedin', 'false', 365, "/");
//    }
//}

function initCufon(){
    Cufon.replace('#nav li a',{
        fontFamily:'Futura Book',
        hover:true
    });
    Cufon.replace('.main-other-background h3',{
        fontFamily:'Futura Book',
        hover:true
    });
    Cufon.replace('.block-visual-holder ul li span',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('.main-frame h2',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('.block-blockquote blockquote .quote',{
        fontFamily:'Gentium Basic',
        hover:true
    });
    Cufon.replace('.sponsor-block ul li span',{
        fontFamily:'Gentium Basic',
        hover:true
    });
    Cufon.replace('.block-sidebar span.heading',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('.slogan',{
        fontFamily:'futura',
        hover:true
    });
    Cufon.replace('.block-sidebar-blue .holder span.heading',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('#content .title h1, #content .title h2',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('.box-blockquote blockquote .quote',{
        fontFamily:'Gentium Basic',
        hover:true
    });
    Cufon.replace('.sideinfo h3',{
        fontFamily:'futura',
        hover:true
    });
    Cufon.replace('.block-logos .slogans',{
        fontFamily:'Futura Book',
        hover:true
    });
    Cufon.replace('.block-logos .slogans strong',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('.main-frames h2',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('.block-heading h4',{
        fontFamily:'Futura Bold',
        hover:true
    });
    Cufon.replace('#content .description',{
        fontFamily:'Futura'
    });
    Cufon.replace('.intro h2',{
        fontFamily:'Futura Bold'
    });
    Cufon.replace('.testimonial-wrapper .testimonial-block blockquote p.quote, .sideinfo .pane.quotes blockquote',{
        fontFamily:'Gentium Basic'
    });
}
initCufon();

function randomSort(a, b) {
    return (parseInt(Math.random() * 10) % 2);
}
function bookingSlider() {
    var $bookings = $('ul.bookings');
    if (bookings && bookings.length && $bookings.length) {
        var bookingItemHTML = function (i) {
            return '<li><span class="about">' + bookings[i][0] + '</span> <span class="address"><span><em>' + bookings[i][1] + '</em><br />' + bookings[i][2] + '</span></span><strong>' + bookings[i][3] + '</strong></li>';
        };
        $bookings.each(function () {
            var $bookings = $(this),
            pos = 6;
            $bookings.empty();
            for (var i = 0; i < pos; i++) {
                var $item = $(bookingItemHTML(i)).prependTo($bookings);
            }
            var showItem = function () {
                var $item = $(bookingItemHTML(pos)).addClass('showing').prependTo($bookings);
                $item.hide().slideDown('slow', function () {
                    $(this).effect('highlight', {
                        color: '#f9f9f9'
                    }, 2500);
                    $bookings.children().last().remove();
                });
                pos++;
                if (pos >= bookings.length) pos = 0;
            };
            setInterval(showItem, 1500);
            showItem();
        });
    }
}
function testimonialRotator() {
    if (testimonials && testimonials.length) {
        testimonials.sort(randomSort);
        $('div.testimonials').each(function () {
            var $testimonials = $(this),
            pos = 3,
            screenPos = 0;
            $testimonials.empty();
            for (var i = 0; i < pos; i++) {
                var html = '<div class="block-blockquote"><blockquote>';
                html = html + '<p class="quote">&quot;' + testimonials[i]['quote'] + '&quot;</p>';
                html = html + '<p><cite>' + testimonials[i]['author'] + '</cite></p>';
                html = html + '</blockquote></div>';
                $testimonials.append(html);
                Cufon.refresh();
            }
            var showItem = function () {
                var html = '<div class="block-blockquote"><blockquote>';
                html = html + '<p class="quote">&quot;' + testimonials[pos]['quote'] + '&quot;</p>';
                html = html + '<p><cite>' + testimonials[pos]['author'] + '</cite></p>';
                html = html + '</blockquote></div>';
                $testimonials.children().eq(screenPos).hide().html(html).fadeIn('slow');
                Cufon.refresh();
                pos++;
                pos %= testimonials.length;
                screenPos++;
                screenPos %= 3;
            };
            setInterval(function () {
                $testimonials.children().eq(screenPos).fadeOut('normal', showItem)
            }, 7016);
        });
    }
}
function iPhoneOS() {
    var version = navigator.userAgent.match('iPod') || navigator.userAgent.match('iPhone') ? 1.0 : false;
    if ((match = /iPhone OS (.*) like Mac OS X/.exec(navigator.userAgent))) {
        version = parseInt(match[1].replace('_', ''), 10) / 100;
        if (version < 1) {
            version *= 10;
        }
    }
    return version;
}
function androidOS() {
    var regex = /android.*mobile/gi;
    return regex.test(navigator.userAgent);
}
function loginPopup() {
    if (iPhoneOS() && GetCookie('iPhone-prefer-desktop')!=='true') {
        window.location = 'https://m.'+window.location.host.replace('www.','');
        return false;
    }
    if (androidOS() && GetCookie('iPhone-prefer-desktop')!=='true') {
        window.location = 'https://m.'+window.location.host.replace('www.','')+'/master';
        return false;
    }
    if (GetCookie('seraph.os.cookie')!=null || navigator.appVersion.indexOf('MSIE 7.') != -1 || document.documentMode == 7) {
        window.location = '/manager/';
        return false;
    }
    var closePopup = function () {
        $('#loginoverlay').fadeOut(function () {
            $(this).remove();
        });
        $('.quick-login-form-holder').fadeOut('fast');
        $('#header .add-nav .log-in').toggleClass('open');
    }
    if ($('.quick-login-form-holder').is(':visible') == true) {
        closePopup();
    } else {
        $('#loginoverlay').remove();
        if ($('.quick-login-form-holder.mobile').length>0) { //page has the mobile quick login form
            if (iPhoneOS() || androidOS()) {
                $('.quick-login-form-holder.mobile').css('z-index', '996').fadeIn('fast');
            } else {
                $('.quick-login-form-holder.standard').css('z-index', '996').fadeIn('fast');
            }
        } else { //fallback to old quick login
            $('.quick-login-form-holder').css('z-index', '996').fadeIn('fast');
        }
        $('#header .add-nav .log-in').toggleClass('open');
        $('.quick-login-form input[value=]:first').focus().select();
        $('<div id="loginoverlay"></div>').css({
            'position': 'fixed',
            'top': 0,
            'left': 0,
            'width': '100%',
            'height': '100%',
            'z-index': '995',
            'background': '#222'
        }).fadeTo('slow', 0.5).click(closePopup).prependTo(document.body);
    }
}
function featuresScroller() {
    var testimonials = [
    [{
        quote: 'Genbook has really made client scheduling hassle-free!',
        author: 'Jennifer Jackson, Esthetician'
    }, {
        quote: 'An easy-to-use interface and a BookNow! button on my website. My patients love Genbook!',
        author: 'Donald Sloane, Dentist'
    }, {
        quote: 'Convenience for my customers to book appointments online in real time, 24x7.',
        author: 'Cheryl Crist-Besson, Skin Care Salon'
    }, {
        quote: '2 Thumbs up and 5 Stars!',
        author: 'Athena Elliott, Nail Salon'
    }],
    [{
        quote: 'Genbook has transformed my business and my client base has grown exponentially.',
        author: 'Brian Edwards, Chiropractor'
    }, {
        quote: 'I love the automatic email reminders sent to customers before their appointments.',
        author: 'Amber Kime, Counselor'
    }, {
        quote: 'I love Genbook! I have tried the others but Genbook is the best.',
        author: 'Michelle DeVries, Massage Therapist'
    }, {
        quote: 'You don\'t miss out on new clients; they schedule online instead of calling someone else!',
        author: 'Jody Campeau, Therapeutic Massage'
    }],
    [{
        quote: 'My clients love being able to schedule at their convenience without phone tag.',
        author: 'Sherry Carpenter, Counselor'
    }, {
        quote: 'Genbook rocks! I have a ton of amazing Reviews and I rarely have no-shows.',
        author: 'John Stiller, Acupuncturist'
    }, {
        quote: 'My clients prefer booking online from my website.',
        author: 'Chris Morrison, Chiropractor'
    }, {
        quote: 'Customers love submitting Reviews after their appointments.',
        author: 'Merrill Bastion, Massage Therapist'
    }],
    [{
        quote: 'Genbook has helped me expand my business.',
        author: 'Noah Wolf, Photographer'
    }, {
        quote: 'The best scheduling app! Genbook is better than the competition.',
        author: 'Nourhy Chi, Alternative Medicine'
    }, {
        quote: 'I can be with a patient while Genbook is busy filling my schedule',
        author: 'Kathleen Halloran, Naturopath'
    }, {
        quote: 'Genbook is a Godsend! Clients self-schedule their Groupons online via Genbook.',
        author: 'Cathy Green, Maid Service'
    }],
    [{
        quote: 'Genbook provides a level of security and peace of mind that usually requires a receptionist.',
        author: 'Ken Lyons, Attorney'
    }, {
        quote: 'Best business decision I ever made!',
        author: 'Ashley Tablot, Esthetician'
    }, {
        quote: 'I sleep well at night, knowing Genbook is filling up my Calendar and backing up my data!',
        author: 'Simone Walsh, Beauty Salon'
    }, {
        quote: 'Genbook\'s Customer Support is so helpful.',
        author: 'Kim Tomlin, Day Spa'
    }]
    ];
    $('.gallery-container').scrollable({
        mousewheel: false,
        circular: true,
        keyboard: true,
        speed: 600,
        items: '.cont-list',
        onBeforeSeek: function(event) {
            $(window).scrollTop(0);
        },
        onSeek: function (event, i) {
            $(window).scrollTop(0);
            var current = $('.gallery-page ul.cont-list li:eq(' + (i+1) + ')');
            document.title = current.attr('title');
            $('.box-blockquote').fadeOut('fast', function() {
                $('#content .gallery-container').animate({
                    height: current.height()
                }, 750, 'swing', function() {
                    $('.box-blockquote').show();
                });
                for (var j = 0; j < 4; j++) {
                    if (i == -1) {
                        i = 4;
                    }
                    var testimonial = testimonials[i][j];
                    var quoteString = '<p class="quote">&quot;' + testimonial.quote + '&quot;</p>';
                    quoteString += '<p><cite>' + testimonial.author + '</cite></p>';
                    $('#quote_' + (j+1)).html(quoteString);
                }
                Cufon.refresh();
            });
        }
    }).navigator({
        navi: "#sidebar #sidebar_features_nav",
        activeClass: 'active',
        naviItem: 'a',
        history: true,
        indexed: true,
        idPrefix: 'tab-'
    }).navigator({
        navi: "#features-footermap",
        activeClass: 'active',
        naviItem: 'a',
        history: true,
        indexed: true,
        idPrefix: 'tab-'
    });
}
