

//Document Ready!
$(document).ready(function () {

    /************************
    * Facebook JS SDK Init
    *************************/
    window.fbAsyncInit = function () {
        FB.init({
            appId: '116112695165579',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());

    if (typeof $.ui != 'undefined') {
        $("#sonetdiv").dialog({
            autoOpen: false,
            modal: true,
            title: 'Haw Dilly!',
            width: 640,
            height: 460,
            open: function (event, ui) {
                $("#sonetdiv").html(overlayData);
            }
        }).bind('clickoutside', function (e) {
            if ($(this).dialog('isOpen')) {
                $(this).dialog('close');
            }
        });
    }


    //SHARE BUTTONS
    $('#shfb').click(function () {
        fbstatus();
        return false;
    });

    $('#shtw').click(function () {
        twstatus();
        return false;
    });

    $('#shem').click(function () {
        initemail();
        return false;
    });

    $('#sweepsrules').click(function () {
        showrules();
        return false;
    });

    equalHeight($('.newsblurb'));
    $('.nav a').click(function () {
        if ($(this).attr('class') != 'buy') {
            $.scrollTo('#' + $(this).attr('class'), 800, { easing: 'easeOutCirc' });
        }
        return false;
    });
    $('.back').click(function () { $.scrollTo('#home', 800, { easing: 'easeOutCirc' }); return false; });
    if ($('#gallery a').length) {
        $('#gallery a').fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'titlePosition': 'over',
            'centerOnScroll': true,
            'overlayColor': '#333333'
        });
    }

    if ($('.morenews').length) {
        $('.morenews').fancybox({
            'width': '90%',
            'height': '90%',
            'autoScale': false,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'type': 'iframe',
            'centerOnScroll': true,
            'overlayColor': '#333333'
        });
    }

    $("#li_top, #li_bot").click(function () {
        fancyDivWrapper($('#lookinside').html(), this, 740, 432);

        /*
        $.fancybox([
        '/images/default/pv_cover.jpg',
        '/images/default/pv_page1.jpg',
        '/images/default/pv_page2.jpg',
        '/images/default/pv_page3.jpg',
        '/images/default/pv_page4.jpg'
        ], {
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'image',
        'centerOnScroll': true,
        'overlayColor': '#333333',
        'orig': $(this).prev()
        });
        */
        return false;
    });

    $('.lookbookone').live('click', function () {
        $.fancybox([
        '/images/default/pv_cover.jpg',
        '/images/default/pv_page1.jpg',
        '/images/default/pv_page2.jpg',
        '/images/default/pv_page3.jpg',
        '/images/default/pv_page4.jpg'
        ], {
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'type': 'image',
            'centerOnScroll': true,
            'overlayColor': '#333333',
            'orig': $(this).prev()
        });
        return false;
    });

    $('.lookbooktwo').live('click', function () {
        $.fancybox([
        '/images/default/pv2_page1.jpg',
        '/images/default/pv2_page2.jpg',
        '/images/default/pv2_page3.jpg',
        '/images/default/pv2_page4.jpg',
        '/images/default/pv2_page5.jpg',
        '/images/default/pv2_page6.jpg',
        '/images/default/pv2_page7.jpg'
        ], {
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'type': 'image',
            'centerOnScroll': true,
            'overlayColor': '#333333',
            'orig': $(this).prev()
        });
        return false;
    });

    $("a.vid").click(function () {
        $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'title': this.title,
            'overlayColor': '#333333',
            'width': 680,
            'height': 495,
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',    // <--add a comma here
            'swf': { 'allowfullscreen': 'true' }, // <-- flashvars here
            'orig': $(this).prev().prev()
        });
        return false;
    });

    $('#buylink_top, #buylink_bot').click(function () {
        fancyFrame('/checkout', $(this), 660, 500);
        return false;
    });

    $('#navbuy_top').click(function () {
        fancyFrame('/checkout', $('#buylink_top'), 660, 500);
        return false;
    });

    $('#navbuy_bot').click(function () {
        fancyFrame('/checkout', $('#buylink_bot'), 660, 500);
        return false;
    });

});

var __ajaxurl = '/ajax/default/__sonetshare.aspx'
var overlayData = null;

function fbstatus() {
    if (typeof (listItemId) == 'undefined') {
        //        return false;
    }
    if (FB == 'undefined') {
        return false;
    }
    FB.getLoginStatus(function (response) {
        if (response.authResponse) {
            getfbinfo(response);
        } else {
            // no user authResponse available, someone you dont know
            fblogin();
        }
    });
}

function getfbinfo(response) {
    FB.api('/me', function (response2) {
        fbname = response2.name;
        fblink = response2.link;
        fbemail = response2.email;

        $.ajax({
            url: __ajaxurl,
            data: { action: 'fblike', listItemId: listItemId, rewritePath: rewritePath, fbuid: response2.id, fbname: fbname, fblink: fblink, fbemail: fbemail },
            success: function (data) {
                fancyFrame(data.url);
                //overlayData = getIframe(data.url);
                //$("#sonetdiv").dialog({ height: 460 });
                //$('#sonetdiv').dialog("open")
            },
            async: false
        });

    });
}

function fblogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            if (response.status == "connected") {
                // user is logged in and granted some permissions.
                // scope is a comma separated list of granted permissions
                getfbinfo(response);
            } else {
                // user is logged in, but did not grant any permissions
            }
        } else {
            // user is not logged in
        }
    }, { scope: 'publish_stream,email' });
}

function twstatus() {
    if (typeof (listItemId) == 'undefined') {
        //        return false;
    }
    var cookies = ReadCookie('de_hrhctw').split('&');
    if (cookies.length > 1) {
        var t = cookies[0].replace('t=', '');
        var ts = cookies[1].replace('ts=', '');
    }
    $.get(__ajaxurl, { action: 'tweet', listItemId: listItemId, rewritePath: rewritePath, t: t, ts: ts }, function (data) {
        //console.log(data.status);
        if (data.status == 'redirect') {
            window.location.href = data.url;
        }
        if (data.status == 'authed') {
            fancyFrame(data.url);
            //overlayData = getIframe(data.url);
            //$("#sonetdiv").dialog({ height: 460 });
            //$('#sonetdiv').dialog("open")
            //   $('#sonetdiv').data('overlay').load();
        }
    });
}

function sendfb() {
    var fblink = "http://www.minethatbird.com/?dtrk=600";
    var fbdescription = "Get the first book in the Mine That Bird Trilogy, 'At the Gate', about a down-on-his-luck racehorse written by Rod McCall and Price Hall. Learn more and buy the book on Mine That Bird's website!";
    var fbname = "Win - Be a Jockey for a Day!";
    var fbpicture = "http://minethatbird.disentropy.net/images/default/shareimg.jpg";
    var fbcaption = "Mine That Bird"

    hideShareButton();
    //FB.api('/me/feed', 'post', { message: shdata.fb_message }, function (response) {
    FB.api('/me/feed', 'post', { message: shdata.fb_message, link: fblink, description: fbdescription, name: fbname, picture: fbpicture, caption: fbcaption }, function (response) {
        if (!response || response.error) {
            alert('Facebook seems to be experiencing problems. Please try again later.');
            window.parent.closeOverlay();
        } else {
            $.post(__ajaxurl, { action: 'sendfb', msg: shdata.fb_message, type: shdata.type, lid: shdata.lid, uid: shdata.uid }, function (data) {
                if (data.status == "ok") {
                    //NEW CONFIRMATION MESSAGE HACK
                    window.parent.fancyFrame('/thankyou');
                    //confirmation = getIframe('/thankyou');
                    //window.parent.$("#sonetdiv").html(confirmation);
                    //window.parent.closeOverlay();
                }
            });
        }
    });
}

function sendtw() {
    hideShareButton();
    $.post(__ajaxurl, { action: 'sendtweet', msg: shdata.tw_message, type: shdata.type, lid: shdata.lid, uid: shdata.uid }, function (data) {
        if (data.status == 'ok') {
            //NEW CONFIRMATION MESSAGE HACK
            window.parent.fancyFrame('/thankyou');
            //confirmation = getIframe('/thankyou');
            //window.parent.$("#sonetdiv").html(confirmation);
            //window.parent.closeOverlay();
        } else {
            alert('Twitter seems to be experiencing problems. Please try again later.');
            window.parent.closeOverlay();
        }
    });
}

function initemail() {
    if (typeof (listItemId) == 'undefined') {
        return false;
    }
    $.get(__ajaxurl, { action: 'email', listItemId: listItemId, rewritePath: rewritePath }, function (data) {
        overlayData = getIframe(data.url);
        $("#sonetdiv").dialog({ height: 460 });
        $('#sonetdiv').dialog("open");
    });
}

function sendem() {
    var emailto = $('#emailto').val();
    var emailreply = $('#emailfrom').val();    //sender's email address

    if (emailto.length <= 5 || emailreply.length <= 5) {
        alert('You must enter a To: and From: email address!');
        return false;
    }
    hideShareButton();


    $.post(__ajaxurl, { action: 'sendemail', msg: shdata.em_message, em_subject: shdata.em_subject, em_from: shdata.em_from, em_reply: emailreply, em_to: emailto, type: shdata.type, lid: shdata.lid, uid: emailreply }, function (data) {
        if (data.status == 'ok') {
            confirmation = getIframe('/thankyou');
            window.parent.$("#sonetdiv").html(confirmation);
            //window.parent.closeOverlay();
        } else {
            alert('There was an error sending the email. Please check that the To: and From: addresses are valid email addresses');
            window.parent.closeOverlay();
        }
    });

}

function showrules() {
    overlayData = getIframe('/sweepsrules');
    $("#sonetdiv").dialog({ height: 460, modal: false });
    $('#sonetdiv').dialog("open")
}

function ReadCookie(cookieName) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}

function closeOverlay() {
    $('.ui-dialog-titlebar-close').click();
}

function closeOverlayAndThen(action) {
    $('.ui-dialog-titlebar-close').click();
    if (action == 'tw') {
        twstatus();
    }
    if (action == 'fb') {
        fbstatus();
    }
}

function getIframe(url) {
    return '<iframe src="' + url + '" width="610" height="400px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function getTallIframe(url) {
    return '<iframe src="' + url + '" width="610" height="510px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function hideShareButton() {
    $('.sharebtn').html('Please wait while your message is shared...');
}

/*******************
* FancyBox Wrapper Function - Div With Content
*******************/
function fancyDivWrapper(data, caller, w, h) {
    var width = 450, height = 450;
    if (typeof w != 'undefined') { width = w; }
    if (typeof h != 'undefined') { height = h; }
    $.fancybox(data, {
        'autoDimensions': false,
        'width': width,
        'height': height,
        'padding': 0,
        'autoScale': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'centerOnScroll': true,
        'overlayColor': '#000000',
        'overlayOpacity': 0.7,
        'orig': caller
    });
}


function fancyFrame(url, caller, w, h) {
    var width = 640,
        height = 480;

    if (typeof caller != 'undefined') {
        height = h;
    }

    if (typeof w != 'undefined') {
        width = w;
    }

    if (typeof h != 'undefined') {
        height = h;
    }

    $.fancybox(url, {
        'width': width,
        'height': height,
        'autoScale': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'iframe',
        'centerOnScroll': true,
        'overlayColor': '#333333',
        'orig': caller
    });
}




/*******************
* Equalize container heights
*******************/
function equalHeight(group) {
    var tallest = 0;
    group.each(function () {
        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/*******************
* Debouncer
*******************/
function debouncer(func, timeout) {
    var timeoutID, timeout = timeout || 100;
    return function () {
        var scope = this, args = arguments;
        clearTimeout(timeoutID);
        timeoutID = setTimeout(function () {
            func.apply(scope, Array.prototype.slice.call(args));
        }, timeout);
    }
}

/*******************
* Easing Functions
*******************/
$.extend($.easing, { def: 'easeOutQuad', easeOutCubic: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c * (t /= d) * t * t * t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, easeOutQuint: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t / d * (Math.PI / 2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t = t / d - 1) * t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b; return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
}, easeOutElastic: function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a); return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
}, easeInOutElastic: function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5); if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a); if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
}, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - $.easing.easeOutBounce(x, d - t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if (t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d / 2) return $.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b; return $.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b; }
});
