var apiServer = 'api.tarot.com';
var signs_reverse = { aries: 1, taurus: 2, gemini: 3, cancer: 4, leo: 5, virgo: 6, libra: 7, scorpio: 8, sagittarius: 9, capricorn: 10, aquarius: 11, pisces: 12 };
var signs = "general aries taurus gemini cancer leo virgo libra scorpio sagittarius capricorn aquarius pisces".split(' ');

function unsubcallback(data, twittauser) {
    if(data['fail']) {
        alert("That user is not subscribed");
    }
    else if(data['success']) {
        $("#twittascope-signup-start").hide();
        $("#twittascope-signup-manage").hide();
        $("#twittascope-signup-unsub-deets").hide();
        $("#twittascope-signup-unsub-complete .the-username").text( twittauser );
        $("#twittascope-signup-unsub-complete").show();
    }
}

function modal_unsubcallback(data, twittauser) {
    if(data['fail']) {
        $('#twittascope-modal-unsub-window .unsub-error .username').text( twittauser );
        $('#twittascope-modal-unsub-window .unsub-error').show();
    }
    else if(data['success']) {
        $("#twittascope-modal-unsub-window > div").hide();
        $("#twittascope-modal-unsub-window .unsub-success .username").text( twittauser );
        $("#twittascope-modal-unsub-window .unsub-success").show();
    }
}

function twittaunsub(twittauser, callback) {
    $("#manage-account-main .ajax-response").hide();
    $.ajaxProxy({
        url: 'http://'+apiServer+'/api/twittascope_oauth.php',
        dataType: 'json',
        data: {
            'function': 'unsub',
            'username': twittauser
        },
        success: function(feedData) { callback(feedData, twittauser) }
    });
}

function twittasubscribe(sign, email, bday, callback) {
    $("#manage-account-main .ajax-response").hide();
    $.ajaxProxy({
        url: 'http://'+apiServer+'/api/twittascope_oauth.php',
        dataType: 'json',
        data: {
            'function': 'subscribe',
            username: twittauser,
            token: twittatoken,
            sign: sign,
            tokensecret: twittatokens,
            birthdate: bday,
            email: email
        },
        success: function(feedData) { callback(feedData, twittauser) }
    });
}

function lovecompat_verify() {
    var compat_box = $("#romantic-compatibility"),
        a = $(".compatSign1", compat_box).val(),
        b = $(".compatSign2", compat_box).val();
    if (a == -1 || b == -1) {
        var error_msg = (a == -1 && b == -1) ? 'Please select two signs.' : 
                        (b == -1 ? 'Please select his/her sign.' : 'Please select your sign.' );
        $("p.error").css('display','block').html(error_msg);
        return false;
    }
    return true;
}

function lovecompat_clear_error() {
    var compat_box = $("#romantic-compatibility"),
        a = $(".compatSign1", compat_box).val(),
        b = $(".compatSign2", compat_box).val();
    if (a != -1 && b != -1) {
        $("p.error").html('').css('display','none');
    }
}

function lovescope_go() {
    var which_url = $("#dhCopy select").val(),
        matches   = which_url.match(/sign=(\d+)/),
        sign      = signs[ matches[1] ];
    window.location = "/" + sign + "/" + sign + "-lovescopes.php";
}

$( function(){
    $("a.twittascope-unsubscribe").click( function(e){ 
        // todo: scroll screen so this is visible if its not visible
        var offset = $("#twit-container .content .right-column .signup").offset();
        var min = $(window).scrollTop();
        var max = min + $(window).height();
        if ( offset.top < min || offset.top > max) {
            $(window).scrollTop( offset.top );
        }
        
        $("#twittascope-signup-start").hide();
        $("#twittascope-signup-manage").hide();
        $("#twittascope-signup-unsub-deets").show();
        $("#twittascope-signup-unsub-complete").hide();
        e.preventDefault();
    } );

    $("#twittascope-unsub-cancel").click( function(e){ 
        $("#twittascope-signup-start").show();
        $("#twittascope-signup-manage").show();
        $("#twittascope-signup-unsub-deets").hide();
        $("#twittascope-signup-unsub-complete").hide();
        e.preventDefault();
    } );
    
    $("#twittascope-unsub-go").click( function(e){ 
        var twittauser = $("#twitta_usernameunsub").val();
        twittaunsub(twittauser, unsubcallback);
        e.preventDefault();
    } );
    
    $("#twittascope-managepage-unsub-go").click( function(e){ 
        var twittauser = $("#twitta-username-managepage-unsub").val();
        twittaunsub(twittauser, function(data, user) {
            if(data.fail) {
                $('#manage-account-main .unsub-error .username').text( twittauser );
                $('#manage-account-main .unsub-error').show();
            }
            else if(data.success) {
                twittauser   = undefined;
                twittatoken  = undefined;
                twittatokens = undefined;
                twittaemail  = undefined;
                $("#acctmanage").hide();
                $("#login").show();
                $("#manage-account-main .unsub-success .username").text();
                $("#manage-account-main .unsub-success").show();
            }
        } );
        e.preventDefault();
    } );
    
    $("#twittascope-unsub-complete-ok").click( function(e){
        $("#twittascope-signup-start").show();
        $("#twittascope-signup-manage").show();
        $("#twittascope-signup-unsub-deets").hide();
        $("#twittascope-signup-unsub-complete").hide();
        e.preventDefault();
    } );

    $("a.twittascope-unsubscribe-bottom").click( function(e){ 
        $("#twittascope-modal-unsub-window").show();
        $("#twittascope-modal-unsub-backing").show();
        $("#twittascope-modal-unsub-window > div").hide();
        $("#twittascope-modal-unsub-window .unsub-deets").show();
        e.preventDefault();
    } );

    $(".twittascope-modal-unsub-cancel").click( function(e){
        $("#twittascope-modal-unsub-window").hide();
        $("#twittascope-modal-unsub-backing").hide();
        e.preventDefault();
    } );
    
    $("#twittascope-modal-unsub-go").click( function(e){
        var twittauser = $("#twittascope-modal-unsub-window .twitta_usernameunsub").val();
        twittaunsub(twittauser, modal_unsubcallback);
        e.preventDefault();
    } );

    $("#twittascope-sub-go").click( function(e){
        var form  = $("#twittascope-subscribe-form"),
            sign  = $(".sign", form).val(),
            email = $(".email", form).val(),
            _y    = $(".birthday-year", form).val(),
            _m    = $(".birthday-month", form).val(),
            _d    = $(".birthday-day", form).val(),
            bday  = _y + '-' + _m + '-' + _d;

        if (sign == 0) {
            alert('Please select your sign');
            return false;
        }
        if (_m=='Month' || _d=='Day' || _y=='Year') {
            alert('Please select your birth date');
            return false;
        }
        twittasubscribe(sign, email, bday, function(data, user) {
            if (data.fail) {
                var reason = data.fail[1];
                var msg = (reason == 'manage') ?
                          "Twitter user '" + user + "' is already up to date." :
                          "Twitter user '" + user + "' had difficulty with sign-up. Please try again or contact our support";
                alert(msg);
            } else {
                var action = data.success[1];
                if (action =='manage') {
                    $('#manage-account-main .sub-updated .username').text( user );
                    $('#manage-account-main .sub-updated').show();
                } else {
                    $('#manage-account-main .sub-success .username').text( user );
                    $('#manage-account-main .sub-success').show();
                }
                var expire = new Date();
                expire.setDate( expire.getDate() + 30 );
                document.cookie = 'twittascope_default_bday='+escape(bday)+';path=/;expires='+expire.toUTCString();
            }
        });
        e.preventDefault();
    } );

    if ( typeof twittatoken != 'undefined' && twittatoken.length > 0){
        var sub_form = $("#twittascope-subscribe-form");
        if (sub_form.length) {
            $.ajaxProxy({
                url: 'http://'+apiServer+'/api/twittascope_oauth.php',
                dataType: 'json',
                data: {
                    'function': 'user_info',
                    username: twittauser,
                    token: twittatoken,
                    tokensecret: twittatokens
                },
                success: function(data) {
                    if (data.success) {
                        var select_y   = $("select.birthday-year",  sub_form),
                            select_m   = $("select.birthday-month", sub_form),
                            select_d   = $("select.birthday-day",   sub_form),
                            select_s   = $("select.sign",           sub_form),
                            input_e    = $("input.email",           sub_form),
                            info_sign  = data.success[1],
                            info_bday  = data.success[2],
                            info_email = data.success[3],
                            info_year  = info_bday.substr(0,4),
                            info_month = info_bday.substr(5,2), 
                            info_day   = info_bday.substr(8,2); 
                        select_y.val( info_year  );
                        select_m.val( info_month );
                        select_d.val( info_day   );
                        select_s.val( signs_reverse[ info_sign.toLowerCase() ] );
                        input_e.val(  info_email );
                        if (info_bday) {
                            var expire = new Date();
                            expire.setDate( expire.getDate() + 30 );
                            document.cookie = 'twittascope_default_bday='+escape(info_bday)+';path=/;expires='+expire.toUTCString();
                        }
                    }
                }
            });
        }
    }

} );
