var imgpath = '/images/passportrehab/';
var bgimages = new Array('slideshow1.jpg', 'slideshow2.jpg', 'slideshow3.jpg', 'slideshow4.jpg');
var bgpreload = new Array();
var currentimg = 1;
var timer = null;


$(document).ready(function () {
    //preload bg images
    for (i = 0; i < bgimages.length; i++) {
        bgpreload[i] = new Image();
        bgpreload[i].src = imgpath + bgimages[i];
    }
    
    

    //start bg rotator
    timer = setInterval(changeImg, 6000);

    //map rollover
    $('#map ul li a').mouseenter(function () {
        imgheight = 170;
        currentIndex = $(this).parent().prevAll().length;
        xpos = (imgheight * currentIndex * -1) + 'px';
        $('#map').css({ 'background-position': 'left ' + xpos });
    }).mouseleave(function () {
        $('#map').css({ 'background-position': 'left -681px' });
    });

    //adjust column heights on secondary pages
    if ($('#innercontainer .right').height() > $('#homecontent2').height()) {
        $('#homecontent2').css({ 'min-height': $('#innercontainer .right').height() + 'px' });
    }

    /************************
    * Facebook JS SDK Init
    *************************/
    window.fbAsyncInit = function () {
        FB.init({ appId: '115633595190964', status: true, cookie: true,
            xfbml: 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);
    } ());

    $("#sonetdiv").dialog({
        autoOpen: false,
        modal: true,
        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();
    });

    $('#shtw').click(function () {
        twstatus();
    });

    //COMMENT FROM SUBMIT ROLLOVER
    $('#submit').mouseenter(function () {
        $(this).css({ 'background-position': 'left -22px' });
    }).mouseleave(function () {
        $(this).css({ 'background-position': 'left top' });
    });

    $('#submit').mousedown(function () {
        $(this).css({ 'background-position': 'left -44px' });
    }).mouseup(function () {
        $(this).css({ 'background-position': 'left top' });
    });

    //Share rollovers
    $('#shfb').mouseenter(function () {
        $(this).css({ 'background-position': 'left -42px' });
    }).mouseleave(function () {
        $(this).css({ 'background-position': 'left top' });
    });

    $('#shtw').mouseenter(function () {
        $(this).css({ 'background-position': '-87px -42px' });
    }).mouseleave(function () {
        $(this).css({ 'background-position': '-87px top' });
    });

    //hide tour tab on tour page
    if (document.location.pathname == '/schedule-a-tour') {
        $('#tour').hide();
    }



});

var __ajaxurl = '/ajax/passportrehab/__sonetshare_passportrehab.aspx'
var overlayData = null;

function fbstatus() {
    if (typeof (listItemId) == 'undefined') {
        //        return false;
    }
    if (FB == 'undefined') {
        return false;
    }
    FB.getLoginStatus(function (response) {
        if (response.session) {
            // logged in and connected user, someone you know
            /*
            $.get(__ajaxurl, { action: 'fblike', listItemId: listItemId, rewritePath: rewritePath, fbuid: response.session.uid }, function (data) {
            overlayData = getIframe(data.url);
            $("#sonetdiv").dialog({ height: 460 });
            $('#sonetdiv').dialog("open")
            // $('#sonetdiv').data('overlay').load();
            });
            */
            getfbinfo(response);
        } else {
            // no user session 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: response.session.uid, fbname: fbname, fblink: fblink, fbemail: fbemail },
            success: function (data) {

                overlayData = getIframe(data.url);
                $("#sonetdiv").dialog({ height: 460 });
                $('#sonetdiv').dialog("open")
                // jq('#sonetdiv').data('overlay').load();
            },
            async: false
        });

    });
}

function fblogin() {
    FB.login(function (response) {
        if (response.session) {
            if (response.perms) {
                // user is logged in and granted some permissions.
                // perms is a comma separated list of granted permissions
                getfbinfo(response);
                /*
                $.get(__ajaxurl, { action: 'fblike', listItemId: listItemId, rewritePath: rewritePath, fbuid: response.session.uid }, function (data) {
                overlayData = getIframe(data.url);
                $("#sonetdiv").dialog({ height: 460 });
                $('#sonetdiv').dialog("open")
                // $('#sonetdiv').data('overlay').load();
                });
                */
            } else {
                // user is logged in, but did not grant any permissions
            }
        } else {
            // user is not logged in
        }
    }, { perms: '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') {
            overlayData = getIframe(data.url);
            $("#sonetdiv").dialog({ height: 460 });
            $('#sonetdiv').dialog("open")
            //   $('#sonetdiv').data('overlay').load();
        }
    });
}

function sendfb() {
    var fblink = "http://passportrehab.com/?dtrk=482";
    var fbdescription = "At National HealthCare's Passport Rehabilitation, we understand that after a hospital stay or surgical procedure, every patient is eager to return home quickly and resume an active lifestyle. As an outstanding community healthcare resource for more than 27 years, we exceed expectations in meeting the needs of individuals who require short-term rehabilitative care following hospitalization.";
    var fbname = "Passport Rehabilitation";
    var fbpicture = "http://passport.jbchicago.com/images/passportrehab/Passport-FB.jpg";
    var fbcaption = "Passport Rehab believes in the highest level of quality care, a focus on customer service and providing a nurturing environment for both patients and families!"

    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 {
            $.get(__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
                    confirmation = getIframe('/share-confirmation');
                    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
            confirmation = getIframe('/share-confirmation');
            window.parent.$("#sonetdiv").html(confirmation);
            //window.parent.closeOverlay();
        } else {
            alert('Twitter seems to be experiencing problems. Please try again later.');
            window.parent.closeOverlay();
        }
    });
}

function closeOverlay() {
    $('.ui-dialog-titlebar-close').click();
}

function closeOverlayAndThen(action) {
    $('.ui-dialog-titlebar-close').click();
    if (action == 'tw') {
        twstatus();
    }
    if (action == 'fb') {
        fbstatus();
    }
}

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 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="590px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function hideShareButton() {
    $('.sharebtn').html('Please wait while your message is shared...');
}

function changeImg() {
    $('#mainimg').stop( true, true ).animate({ opacity: 0 }, 250, function () {
        $(this).css('background', 'url(' + bgpreload[currentimg++ % bgpreload.length].src + ') left top no-repeat');
    }).animate({ opacity: 1 }, 250);
}
