﻿// config.js
var BASE_URL = "/";
var MAXRATINGFILES = 1;
var MAXRATINGSPERFILE = 300;
var SITEVERSION = "0.9";
// in milliseconds. 500 = 1/2 second
var POPUP_DELAY = 1000;
var POPUP_LOADING_IMG = "assets/global/reelzLoading.gif";

var COOKIEDATE = new Date();
COOKIEDATE.setTime(COOKIEDATE.getTime() + (100 * 24 * 60 * 60 * 1000)); // 100 days
if (new String(document.location).indexOf("localhost") < 0) {
    BASE_URL = "/";
}

// common.js
function initPage(){
    initLogin();
   // preloadImages();
    // a few hooks
    checkLoggedIn();
    loadJacks();
}

//ord=Math.random()*10000000000000000;
if (typeof ord == 'undefined') { ord = getCookie("__TEMP_ADORD"); }
window.onload = initPage;
var UPDATE_RATING_IN_SWF = false;
function doNothing() { }

// in the notloggedin control
// and on coresponding pages
var checkLoggedIn = doNothing;
// used on the cablelisting and ppvlisting pages
var loadJacks = doNothing;

function playerTrack(code)
{
    try
    {
        if (getQueryStringValue("playerdebug") != "")
        {
            alert(code);
        }
        //set urchin code
        urchinTracker(code);
    } catch (e) { }

}
function getQueryStringValue(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++)
    {
        var pair = vars[i].split("=");
        if (pair[0] == variable)
        {
            return pair[1];
        }
    }
    return "";
}

function logOut()
{
    document.cookie = "";
    document.location = BASE_URL + "profile/signout.aspx";
}

function getKeyCode(e)
{
    return window.event ? e.keyCode : e.which;
}


function getElement(id)
{
    if (document.getElementById)
    {
        return document.getElementById(id);
    }

    if (document.all || document.layers)
    {
        return document.all[id];
    }

    return null;
}

function getFirstTime()
{
    if (getCookie("__REELZ_FIRST_VIEW") == null)
    {
        setCookie("__REELZ_FIRST_VIEW", "1");
        return "true";
    }
    else
    {
        return "false";
    }

}

function deleteFlashCookies()
{
    deleteCookie("__REELZ_CURRENT_WINDOWID");
    deleteCookie("__REELZ_CURRENT_CLIP");
    deleteCookie("__REELZ_CURRENT_ITEM");
}

function setChannelSelectorWindowState(windowId)
{
    //	alert('__REELZ_CURRENT_WINDOWID :: ' + windowId);
    setCookie("__REELZ_CURRENT_WINDOWID", windowId);
}

function getChannelSelectorWindowState()
{
    if (getCookie("__REELZ_CURRENT_WINDOWID") == null)
    {
        return -1;
    }
    else
    {
        return getCookie("__REELZ_CURRENT_WINDOWID");
    }
}

function setCurrentClipState(currentClip)
{
    //	alert('__REELZ_CURRENT_CLIP :: ' + currentClip);

    setCookie("__REELZ_CURRENT_CLIP", currentClip);
}

function getCurrentClipState()
{
    if (getCookie("__REELZ_CURRENT_CLIP") == null)
    {
        return -1;
    }
    else
    {
        return getCookie("__REELZ_CURRENT_CLIP");
    }
}

function setCurrentItemState(currentItem)
{
    //	alert('__REELZ_CURRENT_ITEM :: ' + currentItem);

    setCookie("__REELZ_CURRENT_ITEM", currentItem);
}

function getCurrentItemState()
{
    if (getCookie("__REELZ_CURRENT_ITEM") == null)
    {
        return -1;
    }
    else
    {
        return getCookie("__REELZ_CURRENT_ITEM");
    }
}

function setCurrentItemAndWindowState(currentItem, currentWindow)
{
    //	alert('__REELZ_CURRENT_ITEM(new) :: ' + currentItem);
    //	alert('__REELZ_CURRENT_WINDOWID(new) :: ' + currentWindow);
    setCookie("__REELZ_CURRENT_ITEM", currentItem);
    setCookie("__REELZ_CURRENT_WINDOWID", currentWindow);

}

function initLogin()
{
    if (getCookie("__REELZ_ACCOUNT_ID") == null)
    {
        showLoginDiv();
    }
    else
    {
        hideLoginDiv();
    }
}

function isLoggedIn()
{
    if (getCookie("__REELZ_ACCOUNT_ID") == null)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

function byPassFlash()
{
    if (getCookie("__REELZ_BYPASS_FLASH") != null)
    {
        return 1;
    } else
    {
        return null;
    }
}

function setByPassFlash()
{
    setCookie("__REELZ_BYPASS_FLASH", "1");
    window.location = window.location;
}

function showLoginDiv()
{
    var divLogin = window.document.getElementById("loginControls");

    if (divLogin != null)
    {
        divLogin.style.visibility = "visible";
        divLogin.style.display = "block";
    }

    var divLoggedIn = window.document.getElementById("loggedIn");

    if (divLoggedIn != null)
    {
        divLoggedIn.style.visibility = "hidden";
        divLoggedIn.style.display = "none";
    }
}

function hideLoginDiv()
{
    var divLogin = window.document.getElementById("loginControls");
    if (divLogin != null)
    {
        divLogin.style.visibility = "hidden";
        divLogin.style.display = "none";

        var divLoggedIn = window.document.getElementById("loggedIn");
        divLoggedIn.style.visibility = "visible";
        divLoggedIn.style.display = "block";

        var spanLoginName = window.document.getElementById("loginName");

        var returnURL = window.document.location;
        spanLoginName.innerHTML = getCookie("__REELZ_LOGIN_NAME") + " ";
    }


}

function hideShowObject(objectName)
{
    var object = window.document.getElementById(objectName);

    if (object.style.visibility == "hidden")
    {
        object.style.visibility = "visible";
        object.style.display = "block";
    } else
    {
        object.style.visibility = "hidden";
        object.style.display = "none";
    }
}

function goToLoginPage()
{
    var page = document;
    if (parent != null) {
        page = parent;
    }
    setCookie("__REELZ_LAST_LOGIN", page.location);
    page.location = getBaseURL() + "profile/profile.aspx";
}
function getMovieRating(movieId) {
    curRatings = getCookie("__REELZ_RATINGS1");
    if (curRatings == null || curRatings.length == 0) { return 0; }
    var ratingMoviePosition = curRatings.indexOf(movieId);
    if (ratingMoviePosition >= 0) {
        var ratingToGet = "";
        var ratingEndPosition = curRatings.indexOf(',', ratingMoviePosition);
        if (ratingEndPosition < 0) //Should mean this is the last rating in file
        {
            ratingToGet = curRatings.substring(ratingMoviePosition);
        } else
        {
            ratingToGet = curRatings.substring(ratingMoviePosition, ratingEndPosition);
        }
        var aryRating = ratingToGet.split('=');
        if (aryRating.length > 1)
        {
            if (aryRating[1] == "a")
            {
                return 10;
            } else
            {
                return aryRating[1];
            }
        }
    }
    return 0;
}
var myMovieRating, myRatedMovieId;
function setMovieRating(movieId, rating) {
    myRatedMovieId = movieId;myMovieRating = rating;
    var siteGuid = getCookie("__REELZ_ACCOUNT_ID");
    $(".commentOverlay").prepend('<div id="ratingSB"><div id="confMessage"><p>Thank You.</p><p>You have rated this movie <span class="rating rate' + rating.toString() + '">' + rating.toString() + '</span></p></div></div>')
    xmlHttp = getXmlHttpObject();
   xmlHttp.onreadystatechange = getRatingRequest;
    var url;
    if (siteGuid != null && siteGuid.length > 0) {
        url = BASE_URL + "webservices/rating.asmx/SetMovieRating?movieId=" + movieId + "&rating=" + rating + "&profileGuid=" + siteGuid;
    }
    else {
        var reelzGuid = getCookie("__REELZ_UID");
        if (reelzGuid != null && reelzGuid.length > 0) {
            url = BASE_URL + "webservices/rating.asmx/SetMovieRating?movieId=" + movieId + "&rating=" + rating + "&profileGuid=" + reelzGuid;
        }
        else {
            url = BASE_URL + "webservices/rating.asmx/SetMovieRatingNoGuid?movieId=" + movieId + "&rating=" + rating;
        }
    }
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
function getRatingRequest() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        cbstring = getReturnValue("string");
        if (cbstring == "success") {
            location.href = location.href;
        }
        else if (cbstring == "failure") {
            location.href = location.href;
        }
        else {
            setCookie("__REELZ_UID", cbstring, COOKIEDATE);
            location.href = location.href;
        }
    }
}
function setCookie(name, value, expires, domain, secure) {
    deleteCookie(name);
    document.cookie = name + "=" + value +
        ((expires) ? "; expires=" + expires.toGMTString() : "") + "; path=/" +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    //	alert(document.cookie);
}
function setCookieExpire(name, value, domain, secure) {
    deleteCookie(name);
    document.cookie = name + "=" + value +
    //        ((expires) ? "; expires=" + expires.toGMTString() : "") + "; path=/" +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getBaseURL() {
    return BASE_URL;
}
function getProfileEmail() {
    if (getCookie('__REELZ_EMAIL') == null) {
        return "";
    } else {
        return getCookie('__REELZ_EMAIL');
    }
}
function getFirstVisit() {
    if (getCookie('__REELZ_FIRST_VISIT') == null) {
        return "true";
    } else {
        return getCookie('__REELZ_FIRST_VISIT');
    }
}
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        /*document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";*/
        var d = new Date();
        document.cookie = name + "="  +
            "; expires=" + d.toGMTString() + ";" + ";";
    }
}
function makeRequest(url, eventToFire, parameters) {
    http_request = false;
    if (window.XMLHttpRequest)
    { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType)
        {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!http_request) {
        // alert('Giving up :( Cannot create an XMLHTTP instance');//
        return false;
    }
    http_request.onreadystatechange = eventToFire;
    if (parameters == null) {
        http_request.open('GET', url, true);
        http_request.send(null);
    } else {
        http_request.open('POST', url, true);
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(parameters);
    }
}
// to handle screwiness with the search submit
function disableReturn() {
    if (event && ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))) {
        return false;
    } else {
        return true;
    }
}
function disableInputBoxes(id)
{
    var div = getDiv(id);
    if (div != null) {
        var inputs = div.getElementsByTagName("INPUT");
        for (i = 0; i < inputs.length; i++) {
            if (inputs[i].className == "txt" || inputs[i].className == "zip" || inputs[i].className == "pwd") {
                inputs[i].onkeydown = disableReturn;
            }
        }
    }
}
function getTextBoxLength(object) {
    return document.getElementById(object).value.length;
}
function clearSearchText(txt) {
    if (txt != null) {
        txt.value = "";
    }
}
function submitOnReturn() {
    if (event && ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))) {
        var btn = getDiv("srchBtn");
        if (btn) {
            return btn.click();
        }
        return false;
    } else {
        return true;
    }
}
//flash external API call
function ExternalInterfaceManager() {
    this.registerMovie = function(movieName) {
        if (!window.fakeMovies) window.fakeMovies = new Array();
        window.fakeMovies[window.fakeMovies.length] = movieName;
    }
    this.initialize = function() {
        if (document.all) {
            if (window.fakeMovies) {
                for (i = 0; i < window.fakeMovies.length; i++) {
                    window[window.fakeMovies[i]] = new Object();
                }
                window.onload = initializeExternalInterface;
            }
        }
    }
}
function initializeExternalInterface()
{
    for (i = 0; i < window.fakeMovies.length; i++)
    {
        var movieName = window.fakeMovies[i];
        var fakeMovie = window[movieName];
        var realMovie = document.getElementById(movieName);

        for (var method in fakeMovie)
        {
            realMovie[method] = function() { flashFunction = "<invoke name=\"" + method.toString() + "\" returntype=\"javascript\">" + __flash__argumentsToXML(arguments, 0) + "</invoke>"; this.CallFunction(flashFunction); }
        }
        window[movieName] = realMovie;
    }
}
function PrintThisPage(divId)
{
    var sOption = "toolbar=yes,location=no,directories=yes,menubar=yes,";
    sOption += "scrollbars=yes,width=750,height=600,left=100,top=25";

    var sWinHTML = document.getElementById(divId).innerHTML;

    var winprint = window.open("printpage?print=true", "", sOption);
    winprint.document.open();
    winprint.document.write('<html><LINK href=/main.css rel=Stylesheet><body>');
    winprint.document.write(sWinHTML);
    winprint.document.write('</body></html>');
    winprint.document.close();
    winprint.focus();
}

function disableFlash()
{
    var div = getDiv(id);
    if (div != null)
    {
        var inputs = div.getElementsByTagName("INPUT");
        for (i = 0; i < inputs.length; i++)
        {
            if (inputs[i].className == "txt" || inputs[i].className == "zip" || inputs[i].className == "pwd")
            {
                inputs[i].onkeydown = disableReturn;
            }
        }
    }
}

function preloadImages()
{
    var img = new Image();
    var base = getBaseURL();
    img.src = base + "assets/global/carrot-left-up.gif";
    img.src = base + "assets/global/carrot-top-up.gif";
    img.src = base + "assets/global/carrot-right-up.gif";
    img.src = base + "assets/global/carrot- bottom-up.gif";

    img.src = base + "assets/global/popup_bkg.gif";
    img.src = base + "assets/global/now_bkg.gif";
    img.src = base + "assets/global/pointer_1.gif";
    img.src = base + "assets/global/pointer_2.gif";
    img.src = base + "assets/global/pointer_3.gif";
    img.src = base + "assets/global/pointer_4.gif";

    img.src = base + "assets/global/ratings/unset.gif";
    img.src = base + "assets/global/ratings/1.gif";
    img.src = base + "assets/global/ratings/2.gif";
    img.src = base + "assets/global/ratings/3.gif";
    img.src = base + "assets/global/ratings/4.gif";
    img.src = base + "assets/global/ratings/5.gif";
    img.src = base + "assets/global/ratings/6.gif";
    img.src = base + "assets/global/ratings/7.gif";
    img.src = base + "assets/global/ratings/8.gif";
    img.src = base + "assets/global/ratings/9.gif";
    img.src = base + "assets/global/ratings/10.gif";

    img.src = base + "assets/global/drop_bkg.gif";

    img.src = base + "assets/global/top_nav_lf.gif";
    img.src = base + "assets/global/top_nav_mid.gif";
    img.src = base + "assets/global/top_nav_rt.gif";
    img.src = base + "assets/global/top_nav_rt_on.gif";
    img.src = base + "assets/global/top_nav_mid_on.gif";
    img.src = base + "assets/global/top_nav_lf_on.gif";

    img.src = base + "assets/global/top_nav_div_lf.gif";
    img.src = base + "assets/global/top_nav_div_rt.gif";
    img.src = base + "assets/global/top_nav_div_lf_on.gif";
    img.src = base + "assets/global/top_nav_div_rt_on.gif";
}

// sets the state of list itemn to selected
function setItemSelected(id)
{
    var litags = document.getElementsByTagName("LI");
    var clipListindex = 0;
    var clipListLen = litags.length;

    for (clipListindex = 0; clipListindex < clipListLen; clipListindex++)
    {
        var li = litags[clipListindex];

        if (li.className == "clipRow" || li.className == "clipRow_active")
        {
            if (li.getAttribute("id") != id)
            {
                if (li.className == "clipRow_active") li.className = "clipRow";
            }
            else
            {
                li.className = "clipRow_active";
            }
        }
    }
    populateMovieTitleAndDetails(id);
    return false;
}
function populateMovieTitleAndDetails(id) {
    if ($("#clipDetailsPaneBody") != null && $("#clipDetailsPaneBody").html() != null) {
        $("#clipDetailsPaneBody").load("/services/GetClipDetail.aspx?format=html&clipid=" + id,
            function() {
                var movieName = $('.detail-movieTitle .content a').html();
                var movieYear = $('.detail-year .content a').html();
                $('#clipDetailsPaneHeader .viewClipDetails').html(movieName + ' (' + movieYear + ')');
            }
            );
    }
    return false;
}
// update ads in iframes
function refreshAdCalls()
{
 /*   ord = Math.random() * 10000000000000000;
    setCookie("__TEMP_ADORD", ord);
    $('iframe').each(function(i)
    {
        if (this.src != '' && this.src.indexOf('adsource.aspx') >= 0)
        {
            var index = this.src.indexOf('&adord=');
            if (index >= 0)
            {
                var iframeSrc = this.src.substring(this.src.indexOf('&adord='));
                iframeSrc = iframeSrc.substring(0, iframeSrc.indexOf(';'));
                this.src = this.src.replace(iframeSrc, '&adord=' + (Math.random() * 10000000000000000) + ';');
            }
            else
            {
                this.src = this.src + '&adord=' + (Math.random() * 10000000000000000) + ';';
            }
        }
    });
    */
    /* var adWrappers = $('div.ad');
    if (adWrappers != null) {
    for (var i = 0; i < adWrappers.length; i++) { 
    var adScript = $(adWrappers[i]).find(":contains('GA_googleFillSlot')");
    if (adScript != null) {
    $(adWrappers[i]).html('');
    var script = document.createElement('script');
    script.type = 'text/javascript';
    //var textNode = document.createTextNode('$(document).ready(function() { ' + adScript.html() + '});');
    var textNode = document.createTextNode('GA_googleAddSlot("ca-pub-1360150150472063", "reelz_home_top_728x90");GA_googleFetchAds();' + adScript.html());
    //var textNode = document.createTextNode('alert("Hey Hey");');
    script.appendChild(textNode);
    adWrappers[i].appendChild(script);          
    }
    }
    }*/
}

$(document).ready(function () {
   // var videoAdIframe = document.getElementById('videoAd'); if (videoAdIframe != null) { videoAdIframe.onload = function () { videoAdRcvd(window.frames['videoAd'].document.getElementById('google_ads_div_i_html5_preroll_ad_container')); }; }
    $('.clipListWrapper .clipList a').click(function(event) {
        event.preventDefault();
        var urlparts = $(this).attr('href').split('/');
        if (urlparts.length >= 5) {
            var movieid = urlparts[4];
            setMovieId(this, movieid);
        }
    });
    $('.clipListWrapper_2col .clipList a').click(function(event) {
        event.preventDefault();
        var urlparts = $(this).attr('href').split('/');
        if (urlparts.length >= 5) {
            var movieid = urlparts[4];
            setMovieId(this, movieid);
        }
    });
    if ($("#clipDetailsPaneBody") != null && $("#clipDetailsPaneBody").html() != null) {
        var firstClipID = $('li.clipRow_active').attr('id');
        populateMovieTitleAndDetails(firstClipID);
        $("#clipDetailsPaneBody").hide();
        $("#clipDetailsPaneHeader a").toggle(function() {
            $("#clipDetailsPaneBody").slideDown(300);
            $(".toggleIconClose").css('display', 'none');
            $(".toggleIconOpen").css('display', 'block');

        }, function() {
            $("#clipDetailsPaneBody").slideUp(300);
            $(".toggleIconOpen").css('display', 'none');
            $(".toggleIconClose").css('display', 'block');
        });
    }
});

function showCompanionAd(url)
{
    if (typeof ord == 'undefined') { ord = getCookie("__TEMP_ADORD"); }
    var iFrame = document.getElementById('companion');
    var iFrameContainer = document.getElementById('companionArea');
    if (!iFrame) { return; }
    if (iFrame.src == '' || iFrame.src.indexOf('shim.gif') >= 0) { iFrame.src = url + ";ord=" + ord; }
    else { iFrame.src = iFrame.src; }
    if (!iFrameContainer) { return; }
    $(iFrameContainer).fadeIn('normal');
}
function hideCompanionAd()
{
    var iFrame = document.getElementById('companion');
    var iFrameContainer = document.getElementById('companionArea');
    if (!iFrame) { return; }
    if (iFrameContainer) { $(iFrameContainer).fadeOut('normal'); }
    iFrame.src = "http://cache.Reelz.com/assets/content/general/shim.gif";
}
function showGoogleDfpCompanionAd(content) {
    var rightColAd = document.getElementById('rightColAd');
    if (rightColAd) { $(rightColAd).css('display', 'none'); }

    var companion = document.getElementById('companionBanner');
    if (companion) { $(companion).html(content); }

    var iFrameContainer = document.getElementById('companionBannerWrap');
    if (iFrameContainer) { $(iFrameContainer).css('display', 'block'); }
}

function hideGoogleDfpCompanionAd() {
    var iFrameContainer = document.getElementById('companionBannerWrap');
    if (iFrameContainer) { $(iFrameContainer).css('display', 'none'); }

    var rightColAd = document.getElementById('rightColAd');
    if (rightColAd) { $(rightColAd).css('display', 'block'); }
}
function displayCompanionBanners(banners, tracking) {
    tmDisplayBanner(banners, "companionBanner", 300, 250, null, tracking);
    var rightColAd = document.getElementById('rightColAd');
    if (rightColAd) { $(rightColAd).css('display', 'none'); }
    
    var iFrameContainer = document.getElementById('companionBannerWrap');
    if (iFrameContainer) { $(iFrameContainer).css('display', 'block'); }
}
function hideCompanionBanners() {
    var iFrameContainer = document.getElementById('companionBannerWrap');
    if (iFrameContainer) { $(iFrameContainer).css('display', 'none'); }

    var rightColAd = document.getElementById('rightColAd');
    if (rightColAd) { $(rightColAd).css('display', 'block'); }
}
// Reelz profilesb.js

$(document).ready(setupLogin);
function setupLogin()
{
    $('a.close').click(hideLoginForm);
    $('a.login').attr('href', 'javascript:displayLoginForm()');
    changeCss();
}
function displayLoginForm()
{
    var tail = '?r+' + Math.round(Math.random * 10000);
    $('#reelzProfile').attr('src', '/profile/profilesb.aspx' + tail);
    $('body').append('<div class="overlay"></div>');

    $('div.overlay').click(function()
    {
        hideLoginForm();
    }).fadeIn('slow');

    $('#loginBox-container').slideDown('slow');

    $('#loginBox-container').click(function()
    {
        hideLoginForm();
    }).fadeIn('slow');

    if (!pageTracker) {
        if (typeof (_gat) == 'object') {
            var pageTracker = _gat._getTracker(_uacct);
            pageTracker._trackPageview(); // seems wrong to have this, but is necessary avoid 'y is undefined error'
            pageTracker._trackEvent('Login Shadowbox', 'Login Clicked');
        }
    }    
}
function hideLoginForm()
{
    $('#loginBox-container').slideUp();
    $('div.overlay').fadeOut('slow', refreshParent).remove();
    deleteCookie("__REELZ_OPTINSTATE");
    //refreshParent();
}
function refreshParent()
{
    if (typeof isLoggedIn != 'undefined' && isLoggedIn)
    {
        if (getCookie("__REELZ_ACCOUNT_ID") != null)
        {
            top.location = location.href;
        }
    }
}
function changeCss()
{
    if ($('#loginBox-container'))
    {
        var imageHeight = $('#loginBox-container').height();
        var imageWidth = $('#loginBox-container').width();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        $('#loginBox-container').css({ "left": windowWidth / 2 - imageWidth / 2, "top": windowHeight / 2 - imageHeight / 2 });
    }
};
$(window).bind("resize", function() { changeCss(); });

// webservices.js
var xmlHttp;
function getXmlHttpObject()
{
    var objXmlHttp;
    try {
        objXmlHttp = new XMLHttpRequest();
    } 
    catch (e) {
        try {
            objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {
            objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
    return objXmlHttp;
}
function getReturnValue(dataType) {
    var value = "";
    if (xmlHttp.responseXML.getElementsByTagName(dataType)[0].text == null) {
        if (xmlHttp.responseXML.childNodes[0].childNodes[0] != null) {
            xmlHttp.responseXML.normalize();value = xmlHttp.responseXML.childNodes[0].childNodes[0].nodeValue;
        }
    } else {
        value = xmlHttp.responseXML.getElementsByTagName(dataType)[0].text;
    }
    return value;
}
function clearInput(textinput) { /*if (textinput.value == textinput.defaultValue)*/{ textinput.value = "" } }
function clearDefault(textinput) { if (textinput.value == textinput.defaultValue) { textinput.value = "" } }
function setDefault(textinput) { if (textinput.value == '') { textinput.value = textinput.defaultValue } }
function setDefaultZipWhenEmpty(textinput) {
    if (textinput.value == '') {
        var zipcode = getZipCode();
        if (zipcode != '') {
            $(textinput).val(zipcode);
        } else {
            textinput.value = textinput.defaultValue
        }
    }
}
function getZipCode() {
    var zip = "";
    var zipCookie = getCookie("__TEMP_PHDZ");
    if (zipCookie == null) {
        zipCookie = getCookie("__REELZ_PHDZ");
    }

    if (zipCookie != null) {
        var values = zipCookie.split('|');
        if (values != null && values.length >= 4)
            zip = values[3];
    }
    return zip;
}
function setZipCode(zipcode) {
    var zipCookie = getCookie("__TEMP_PHDZ");
    if (zipCookie == null) {
        zipCookie = getCookie("__REELZ_PHDZ");
    }
    var timezone = "";
    if (zipCookie != null) {
        var values = zipCookie.split('|');
        if (values != null && values.length >= 1)
            timezone = values[0];
    }
    var expiremonth = new Date();
    expiremonth.setMonth( expiremonth.getMonth() + 1);
    
    setCookie("__TEMP_PHDZ", timezone + "|" + "" + "|" + "" + "|" + zipcode, expiremonth);
}


//JS function for setting "Most Popular" list popularity meters
function setPopularityMeters() {
    $('li[popular]').each(function() {
        var x = 10 - $(this).attr("popular"); //Get the base-10 inverse of the popular attribute - these will be integers between 0-10.  A popular=10 item should give us an offset of 0, leaving all the green visible. 9->1 etc.
        x = x * 7; //the image is 140px wide, 70px each of 10 green and 10 grey squares, thus each is 7px apart... so we multiply the popular attribute by 7.
        x = x - (x * 2); // this is just to take our answer and get the negative version of it, since we're moving the image to the left by this much.
        $(this).find('.popMeter').css('background-position', x.toString() + 'px 0px');
    });
}

//Profile
function setupToolTips() {
    $('.helpLnk').hover(function() {
        var eleOffset = $(this).offset(); //get the offset (aka position) of the HOVERED element
        var windowWidth = $(window).width();
        var newLeft;
        if (windowWidth > 945) {
            var marginLeft = (windowWidth - 945) / 2;
            newLeft = (eleOffset.left - marginLeft + 16) + "px";
        }
        else {
            newLeft = (eleOffset.left) + "px";
        }

        if ($(this).parent().get(0).tagName == 'DIV') {
            //alert("foo");
            $(this).next('.helpCopy').css("left", newLeft).show();
        }
        else {
            //alert("bar");
            $(this).parent().next('.helpCopy').css("left", newLeft).show();
        }
    }, function() {
        if ($(this).parent().get(0).tagName == 'DIV') { //Again, hovered items are different if the image is nested in a label...
            $(this).next('.helpCopy').hide();
        }
        else {
            $(this).parent().siblings('.helpCopy').hide();
        }
    });
}

function setupRatings() {
    $("div.ratingsContainer ul[ratingCnt]").each(function() { //turn off all expanders on profiles with <= 6 ratings
        if ($(this).attr('ratingCnt') <= 6) {
            $(this).parent().css('height', 'auto');
            $(this).parent().next().css('display', 'none');
        }
    });
    $('a.lnkExpandRate').click(function() { //Establish click event on normal rating "See All" links
        if ($(this).prev().css('height') == 'auto') {
            $(this).prev().css('height', '140px');
            $(this).text('See All');
        } else {
            $(this).prev().css('height', 'auto');
            $(this).text('See Fewer');
        }
    });
}
function loadPage(pageNum) {
    var index = location.href.indexOf('page=', 0);
    if (index >= 0) {
        var remUrl = location.href.substring(index);
        var remQsIndex = remUrl.indexOf('&', 0);
        var url = location.href.substring(0, index) + "page=" + pageNum;
        if (remQsIndex >= 0)
            url += remUrl.substring(remQsIndex);
        location.href = url;
    }
    else {
        if (location.href.indexOf('?', 0) >= 0)
            location.href = location.href + "&page=" + pageNum;
        else if (location.href.substring(location.href.length - 5) == '.aspx')
            location.href = location.href + "?page=" + pageNum;
        else if (location.href.substring(location.href.length - 1) != '/')
            location.href = location.href + "/?page=" + pageNum;
        else
            location.href = location.href + "?page=" + pageNum;
    }
}
function changeLocation(zipLabel, locationlink, locationInput, locationInputSubmit) {
    //$(zipLabel).css("display", "inline");
    $('#top-location-wrap span#zipLabel').css("display", "inline");
    $(locationlink).css("display", "none");
    $(locationInput).css("display", "inline");
    $(locationInputSubmit).css("display", "inline");
    locationInput.value = locationInput.defaultValue;
}
function validateZipCode(elementValue) { var zipCodePattern = /^\d{5}$/; return zipCodePattern.test(elementValue); }
function onKeyUpLocationInput(zipInput, errorMsg, ajaxCall, event) {
    if (event.keyCode) {
        if (event.keyCode == 13) {
            //event.preventDefault();
            submitLocationInput(zipInput, errorMsg, ajaxCall);
        }
    }
}
function submitLocationInput(zipInput, errorMsg, ajaxCall) {
    $(errorMsg).css("display", "none");
    var zipcode = zipInput.value;
    if (zipcode.length == 5) {
        if (validateZipCode(zipcode)) {
            setZipCode(zipcode);
            if (!ajaxCall) {
                location.href = location.href;
            }
            else {
                var zipCookie = getZipCode();
                if (zipCookie != null && zipCookie != '') {
                    if (zipInput != null) zipInput.value = zipCookie;
                    findReelzResults(zipInput, 'lookup-panel', 'reelz-headends-list', document.getElementById('reelzchannel-lookup'), 'full,withicons,grey', 5);
                }
            }
        }
        else {
            $(errorMsg).html("Please enter a valid zip code.");
            $(errorMsg).css("display", "block");
        }
    }
}
function setupReelzLookup(contextName, results, resultsWrapper, outputType, maxcount) {
    var zipcode = '';
    //if (contextName == 'watch') {
    //    zipcode = getQueryStringValue('zip');
    //}    
   // if (zipcode.length == 0) {
        zipcode = getZipCode();
    //}
    if (zipcode != null && zipcode != '') {
        if (zipcode.length == 5) {
            if (validateZipCode(zipcode)) {
                headEnds.findReelzChannelHeadends(zipcode, contextName, results, outputType, maxcount);
                $(resultsWrapper).slideDown('normal');
           //     if ($('#reelzchannel-lookup-location') != null)
         //           $('#reelzchannel-lookup-location').css("display", "none");
     //           if ($('#ft-reelzchannel-lookup-location') != null)
       //             $('#ft-reelzchannel-lookup-location').css("display", "none");
            }
        }
    }
}
function findReelzResults(zipInput, contextName, results, resultsWrapper, outputType, maxcount) {
    var zipcode;
    if (zipInput != null)
        zipcode = zipInput.value;
    else
        zipcode = getZipCode();
    if (zipcode.length == 5) {
        if (validateZipCode(zipcode)) {
            headEnds.findReelzChannelHeadends(zipcode, contextName, results, outputType, maxcount);
            $(resultsWrapper).slideDown('normal');
            if ($('#reelzchannel-lookup-location') != null)
                $('#reelzchannel-lookup-location').css("display", "none");
            if ($('#ft-reelzchannel-lookup-location') != null)
                $('#ft-reelzchannel-lookup-location').css("display", "none");
            
        }
    }
}
var parentTheaterDivId;
function onKeyUpTheaterLookupZip(zipInput, parentDivId, ajaxCall, event) {
    if (event.keyCode) {
        if (event.keyCode == 13) {
            event.preventDefault();
            submitTheaterLookupZip(parentDivId, ajaxCall);
        }
    }
}
function submitTheaterLookupZip(parentDivId, ajaxCall) {
    parentTheaterDivId = parentDivId;
    $('#' + parentDivId + ' .error').css("display", "none");
    var zip = $('#' + parentDivId + ' .zip-input').val();
    if (zip.length == 5) {
        if (validateZipCode(zip)) {
            setZipCode(zip);
            if (!ajaxCall)
                location.href = location.href;
            else
                findTheaters(parentDivId, zip);
        }
        else {
            $('#' + parentDivId + ' .error').html("Please enter a valid zip code.");
            $('#' + parentDivId + ' .error').css("display", "block");
        }
    }
}
function findTheaters(parentDivId, zip) {
    parentTheaterDivId = parentDivId;
    $('#' + parentDivId + ' .location').css("display", "none");
    if (zip != "") {
        if (zip.length = 5) {
            $('#' + parentDivId + ' .location').val(zip);
            $('#' + parentDivId + ' .theater-list').css("display", "block");
            var loadPage = '/services/theater/theaterdetail.aspx?f=html&c=10&out=titleonly&keyword=' + zip;
            loadPage = loadPage.replace(/amp;/g, "");
             $('#' + parentDivId + ' .theater-list').load(loadPage, theaterListingsComplete);
            return false;
        }
    }
    $('#' + parentDivId + ' .location').css("display", "block");
    return false;
}
function theaterListingsComplete() {
    setZipCode($('#' + parentTheaterDivId + ' .location').val());
    $('#' + parentTheaterDivId + ' .more').attr('href', '/theaters/' + $('#' + parentTheaterDivId + ' .location').val());
    if ($('#' + parentTheaterDivId + ' .theater-list').html() == '') {
        $('#' + parentTheaterDivId + ' .location').css("display", "block");
        $('#' + parentTheaterDivId + ' .error').css("display", "block");
        $('#' + parentTheaterDivId + ' .error').html('No theater found in your area.');
    } else {
        $('#' + parentTheaterDivId + ' .location').css("display", "none");
        $('#' + parentTheaterDivId + ' .error').css("display", "none");
        $('#' + parentTheaterDivId + ' .error').html('No theater found in your area.');
    }
}
function getTvListingsByPerson(timezone) {
    location.href = replaceQueryString(location.href, 'timezone=', timezone)
}
function replaceQueryString(url, qsVar, qsValue) {
    var redirectUrl = url;
    if (qsValue != null && qsValue != '') {
        var index = url.indexOf(qsVar, 0);
        if (index >= 0) {
            var remUrl = url.substring(index);
            var remQsIndex = remUrl.indexOf('&', 0);
            redirectUrl = url.substring(0, index) + qsVar + qsValue;
            if (remQsIndex >= 0)
                redirectUrl += remUrl.substring(remQsIndex);
        }
        else {
            if (url.indexOf('?', 0) >= 0)
                redirectUrl = url + '&' + qsVar + qsValue;
            else if (location.href.indexOf('.aspx', 0) >= 0) {
                redirectUrl = url + '?' + qsVar + qsValue;
            }
            else if (location.href.substring(location.href.length - 1) != '/')
                redirectUrl = url + '/?' + qsVar + qsValue;
            else
                redirectUrl = url + '?' + qsVar + qsValue;

        }
    }
    return redirectUrl;
}
function locationInit(parentDivId, keepItVisible) {
    var zipCookie = getZipCode();
    if (zipCookie != null && zipCookie != '') {
        if (keepItVisible == 'True') {
            $('#' + parentDivId + ' #zipLabel').css("display", "none");
            $('#' + parentDivId + ' a').css("display", "inline");
            $('#' + parentDivId + ' a').text('Change Location ' + zipCookie);
            $('#' + parentDivId + ' input').css("display", "none");
        }
        else {
            $('#' + parentDivId).css("display", "none");
        }
    }
    else {
        $('#' + parentDivId + ' a').css("display", "none");
        $('#' + parentDivId + ' #zipLabel').css("display", "inline");
        $('#' + parentDivId + ' input').css("display", "inline");
    }
}
function reviewsHoverInit(parentDivId) {
    var toDayDate = new Date(); toDayDate.setDate(toDayDate.getDate() - 30);
    var startDate = (toDayDate.getMonth() + 1) + "/" + toDayDate.getDate() + "/" + toDayDate.getFullYear();
    var endDate = new Date(toDayDate); 
    endDate = (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
    var hoverDiv = '<div class="navD reviewsPosRight"><div class="navD-inner"><div class="navD-col"><h2>Richard Roeper Reviews</h2><div id="roeperReviews"></div></div><div class="navD-col last"><h2>Leonard Maltin Reviews</h2><div id="maltinReviews"></div></div><div class="clear"></div><a href="/reviews/" class="more">Movie Reviews</a><div class="clear"></div></div></div>';
    $('#' + parentDivId).after(hoverDiv);
    var loadPage = '/services/clips/getClips.aspx?f=html&out=norowactive&ct=moviereview,roepernew,roeperdvd&c=5&p=1&idl=s119&sort=asc&sd=' + startDate + '&ed=' + endDate;
    $('#roeperReviews').load(loadPage);
    loadPage = '/services/clips/getClips.aspx?f=html&out=norowactive&ct=maltinreview,moviereview&c=5&p=1&idl=s110&sort=asc&sd=' + startDate + '&ed=' + endDate;
    $('#maltinReviews').load(loadPage);    
}
function trailersHoverInit(parentDivId) {
    var hoverDiv = '<div class="navD"><div class="navD-inner"><div class="navD-col"><h2>BRAND NEW TRAILERS</h2><div id="newTrailersList"></div></div><div class="navD-col last"><h2>POPULAR VIDEO CLIPS</h2><div id="polularClipsList"></div></div><div class="clear"></div><a href="/trailers/" class="more">all trailers page</a><div class="clear"></div></div></div>';
    $('#' + parentDivId).after(hoverDiv);
    var loadPage = '/services/clips/getclips.aspx?f=html&out=norowactive&ct=trailer&c=5&p=1';
    $('#newTrailersList').load(loadPage);
    loadPage = '/services/clips/getclips.aspx?f=html&out=norowactive&rt=popular&c=5&p=1';
    $('#polularClipsList').load(loadPage);
}
function tvHoverInit(parentDivId) {
    var hoverDiv = '<div class="navD wide moviesOnTvPosRight"><div class="navD-inner"><div class="navD-col narrow"><h2>WATCH SOMETHING NOW</h2><div id="nowOnTvList"></div><a style="margin-top:4px;" href="/trailer-clips/list/tv-movie-review/" class="more">Now On TV - Movie Reviews</a><div class="clear"></div></div><div class="navD-col narrow"><h2>NEW ON TV</h2><div id="newOnTvList"></div><a style="margin-top:4px;" href="/tv/" class="more">All Movies on tv</a><div class="clear"></div></div><div class="navD-col narrow last"><h2>NEW ON VOD/PPV</h2><div id="newOnVodList"></div><a style="margin-top:4px;" href="/vod/" class="more">All Movies on VOD/PPV</a><div class="clear"></div></div><div class="clear"></div></div></div>';
    $('#' + parentDivId).after(hoverDiv);
    var loadPage = '/services/getmoviesbyrelease.aspx?format=html&out=nodups,postersonly,reducedtitle20&template=TVList&releaseType=cable&count=4&pageNum=1&sortOrder=ASC';
    $('#nowOnTvList').load(loadPage);
    loadPage = '/services/getmoviesbyrelease.aspx?format=html&out=nodups,postersonly,reducedtitle20,premiere&template=TVList&releaseType=cable&count=4&pageNum=1&sortOrder=ASC';
    $('#newOnTvList').load(loadPage);
    loadPage = '/services/getmoviesbyrelease.aspx?format=html&out=nodups,postersonly,reducedtitle20&template=TVList&releaseType=vod&count=4&pageNum=1&sortOrder=DESC';
    $('#newOnVodList').load(loadPage);
}
function dvdHoverInit(parentDivId) {
    var toDayDate = new Date();if (toDayDate.getDay() != 0) toDayDate.setDate(toDayDate.getDate() - toDayDate.getDay());
    var startDate = (toDayDate.getMonth() + 1) + "/" + toDayDate.getDate() + "/" + toDayDate.getFullYear();
    var endDate = new Date(toDayDate); endDate.setDate(toDayDate.getDate() + 7);
    var comingSoonStartDate = new Date(endDate);
    endDate = (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
    var comingSoonEndDate = new Date(comingSoonStartDate); comingSoonEndDate.setDate(comingSoonStartDate.getDate() + 14);
    comingSoonStartDate = (comingSoonStartDate.getMonth() + 1) + "/" + comingSoonStartDate.getDate() + "/" + comingSoonStartDate.getFullYear();
    comingSoonEndDate = (comingSoonEndDate.getMonth() + 1) + "/" + comingSoonEndDate.getDate() + "/" + comingSoonEndDate.getFullYear();
    var hoverDiv = '<div class="navD narrow dvdPosRight"><div class="navD-inner"><div class="navD-col narrow"><h2>BRAND NEW THIS WEEK</h2><div id="newOnDvdList"></div><a href="/trailer-clips/list/dvd-movie-review/" class="more">On DVD - Movie Reviews</a><div class="clear"></div></div><div class="navD-col narrow last"><h2>COMING SOON</h2><div id="comingsoonOnDvdList"></div><a href="/dvd/" class="more">All DVD releases</a><div class="clear"></div></div><div class="clear"></div></div></div>';
    $('#' + parentDivId).after(hoverDiv);
    var loadPage = '/services/getmoviesbyrelease.aspx?format=html&template=DVDList&out=postersonly,reducedtitle20&releaseType=dvd&count=4&pageNum=1&sortOrder=ASC&startDate=' + startDate + '&endDate=' + endDate;
    $('#newOnDvdList').load(loadPage);
    loadPage = '/services/getmoviesbyrelease.aspx?format=html&template=DVDList&out=postersonly,reducedtitle20&releaseType=dvd&count=4&pageNum=1&sortOrder=ASC&startDate=' + comingSoonStartDate + '&endDate=' + comingSoonEndDate;
    $('#comingsoonOnDvdList').load(loadPage);
}
function reelzchanneltvHoverInit(parentDivId) {
    var char1 = "'";
    var hoverDiv = '<div class="navD wide reelzPosRight"><div class="navD-inner"><div class="navD-col narrow"><h2>ReelzChannel TV</h2><div id="reelzChannelTv"></div></div><div class="navD-col narrow"><h2>ReelzChannel Lookup</h2><div id="reelzchannel-lookup"><div id="reelz-headends-list"><ul class="headends"><li><img alt="" src="/assets/provider-logo/dish-grey.png" /><span class="channel-number">Channel 299</span><div class="clear"></div></li><li><img alt="" src="/assets/provider-logo/directv-grey.png" /><span class="channel-number">Channel 238</span><div class="clear"></div></li></ul></div><div class="location" id="reelzchannel-lookup-location"><p>Watch ReelzChannel TV! Set your location to find our channel in your area.</p><span id="zipLabel">Set Location:</span><input id="locationInput" type="text" size="5" maxlength="5" value="ZIP" onfocus="this.value = ' + char1 + char1 + '" onkeyup="javascript:onKeyUpLocationInput(this, document.getElementById(' + char1 + 'zipValidationError' + char1 + '), 1, event);"/><input class="button" id="locationInputSubmit" type="button" value="go" onclick="javascript:submitLocationInput(document.getElementById(' + char1 + 'locationInput' + char1 + '), document.getElementById(' + char1 + 'zipValidationError' + char1 + '), 1);"/><p class="error" id="zipValidationError" style="display: none;"></p></div></div><a href="/watch" class="more">Full Listing</a><div class="clear"></div></div><div class="navD-col wide last"><h2>COMPLETE SHOW LISTING</h2><div id="reelzShowList"> </div><a class="more" href="/watch2/">All Shows</a><div class="clear"></div></div><div class="clear"></div></div></div>';
    $('#' + parentDivId).after(hoverDiv);
    var loadPage = '/services/OnReelzChannelTv.aspx?f=html&out=titleonly';
    $('#reelzChannelTv').load(loadPage);
    loadPage = '/services/show/GetShowDetail.aspx?f=html&showid=-1';
    $('#reelzShowList').load(loadPage);
    locationInit('reelzchannel-lookup-location', 'False');
    setupReelzLookup('lookup-panel', 'reelz-headends-list', document.getElementById('reelzchannel-lookup'), 'full,withicons,grey', 7);
}
function theatersHoverInit(parentDivId) {
    var toDayDate = new Date(); if (toDayDate.getDay() != 0) toDayDate.setDate(toDayDate.getDate() - toDayDate.getDay());
    var startDate = (toDayDate.getMonth() + 1) + "/" + toDayDate.getDate() + "/" + toDayDate.getFullYear();
    var endDate = new Date(toDayDate); endDate.setDate(toDayDate.getDate() + 7);
    var comingSoonStartDate = new Date(endDate);
    endDate = (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
    var comingSoonEndDate = new Date(comingSoonStartDate); comingSoonEndDate.setDate(comingSoonStartDate.getDate() + 7);
    comingSoonStartDate = (comingSoonStartDate.getMonth() + 1) + "/" + comingSoonStartDate.getDate() + "/" + comingSoonStartDate.getFullYear();
    comingSoonEndDate = (comingSoonEndDate.getMonth() + 1) + "/" + comingSoonEndDate.getDate() + "/" + comingSoonEndDate.getFullYear();
    var char1 = "'";
    var hoverDiv = '<div class="navD wide theaterPosRight"><div class="navD-inner"><div class="navD-col narrow"><h2>OPENING THIS WEEK</h2><div id="newInTheaters"></div><a href="/reviews/" class="more">Movie Reviews</a><div class="clear"></div></div><div class="navD-col narrow"><h2>COMING SOON</h2><div id="cominsoonInTheaters"></div></div><div id="TheatersMenu" class="navD-col wide last"><div id="theaterLookup"><h2>Your Theaters</h2><div class="location"><p>Set your location to view local theaters, movie times and purchase tickets.</p><span>Set Location: </span><input class="zip-input" type="text" size="5" maxlength="5" value="ZIP" onfocus="this.value = ' + char1 + char1 + '" onkeyup="javascript:onKeyUpTheaterLookupZip(this, ' + char1 + 'theaterLookup' + char1 + ', 1, event);"/><input class="zip-submit button" type="button" value="go" onclick="javascript:submitTheaterLookupZip(' + char1 + 'theaterLookup' + char1 + ', 1);"/><p class="error" style="display: none;"></p></div><div class="theater-list"></div><a class="more" href="/theaters">full theater listings</a><div class="clear"></div></div></div><div class="clear"></div></div></div>';
    $('#' + parentDivId).after(hoverDiv);
    var loadPage = '/services/getmoviesbyrelease.aspx?format=html&template=DVDList&out=postersonly,reducedtitle20,intheatersonly&releaseType=theater&count=4&pageNum=1&sortOrder=ASC&startDate=' + startDate + '&endDate=' + endDate;
    $('#newInTheaters').load(loadPage);
    loadPage = '/services/getmoviesbyrelease.aspx?format=html&template=DVDList&out=postersonly,reducedtitle20&releaseType=theater&count=4&pageNum=1&sortOrder=ASC&startDate=' + comingSoonStartDate + '&endDate=' + comingSoonEndDate;
    $('#cominsoonInTheaters').load(loadPage);
    findTheaters('theaterLookup', getZipCode());
}
function topNavReelzLookupInit(parentDivId) {
    var zipCookie = getZipCode();
    var html;
    if (zipCookie != null && zipCookie != ''){
       html = '<h2>WATCH REELZCHANNEL TV!</h2><div id="headendsList"></div><a class="more" href="/watch">More</a><div class="clear"></div>';
       $('#' + parentDivId).append(html);
        var loadPage = '/services/getheadends.aspx?f=html&c=3&out=withicons,white-sm&zip=' + zipCookie;
        $('#headendsList').load(loadPage);
    }
    else {
        html = '<h2>WATCH REELZCHANNEL TV!</h2><div><ul class="headends"><li><img alt="" src="/assets/provider-logo/dish-white-sm.png" /><span class="channel-number">299</span> </li><li><img alt="" src="/assets/provider-logo/directv-white-sm.png" /><span class="channel-number">238</span> </li></ul><p>Set your location to lookup ReelzChannel in your area.</p><div class="clear"></div></div>';
        $('#' + parentDivId).append(html);
    }
}
function topNavReelzLookupInitNew(parentDivId) {
    var zipCookie = getZipCode();
    var html;
    if (zipCookie != null && zipCookie != '') {
        html = '<div id="headendsList"></div>';
        $('#' + parentDivId).append(html);
        var loadPage = '/services/getheadends.aspx?f=html&c=3&out=withicons,white-sm&zip=' + zipCookie;
        $('#headendsList').load(loadPage);
    }
}
function leftColumnFmaInit(fmaDivId, nodeId) {
    var loadPage = '/services/GetFMA.aspx?format=html&position=l&header=false&nodeid=' + nodeId;
    $('#' + fmaDivId).load(loadPage);
}
function setMovieId(sender, id) {
    var html5Video = null;
    var flashMovie = document.getElementById('syndicatedSWF');
    if (flashMovie == null) {
        html5Video = document.getElementsByTagName('video')[0];
    }
    litags = document.getElementsByTagName("LI");
    clipListindex = 0;
    clipListLen = litags.length;
    for (clipListindex = 0; clipListindex < clipListLen; clipListindex++) {
        li = litags[clipListindex];
        if (li.className == "clipRow_active") li.className = "clipRow";
    }

    if (sender.parentNode && sender.parentNode.className == "clipRow") sender.parentNode.className = "clipRow_active";

    if (flashMovie) {
        flashMovie.setMovie(id);
    } else if (html5Video != null) {
        var clipPath = id; //$(sender.parentNode).attr('id'); // clip
        clipPath = 'http://cache.Reelz.com/assets/content/clips/mp4/' + clipPath + '.mp4';
        if (sender.parentNode != null && (typeof sender.parentNode != 'undefined')) {
            var repFrame = $(sender.parentNode).children('a').children('img').attr('src').replace('_th.jpg', '_med.jpg');
            html5Video.poster = repFrame;
        }
        else {
            html5Video.poster = null;
        }
        //adAlreadyPlayed = false;
        html5Video.src = clipPath;
        //html5Video.onloadeddata = 'javascript:html5VideoPlay(' + id + ');';
        //html5Video.onended = 'javascript:html5VideoEnded(' + id + ');';
        html5Video.addEventListener('loadeddata', function () { html5VideoPlay(' + id + '); }, false);
        html5Video.addEventListener('ended', function () { html5VideoEnded(' + id + '); }, false);
        html5Video.load();
        html5Video.play();
    }
    populateMovieTitleAndDetails(id);
    refreshAdCalls();
    return false;
}
function playerInit(parentDivId, clipListDivId, width, height, listCount, listPageNum, clipType, relatedId, releaseType, startDate, endDate, sortOrder, clipId, lpid, rpid) {
    if (releaseType == 'popular' && (relatedId == undefined || relatedId == null || relatedId == ''))
        relatedId = '0';
    var html = '';
    if (navigator.userAgent.toLowerCase().indexOf("ipad") >= 0 || navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
        if (clipListDivId != '') {
            var litags = $('#' + clipListDivId + ' li');
            if (litags != null && litags.length > 0) {
                var firstClip = litags[0];
                var clipPath = $(firstClip).attr('id'); // clip 
                var currentClipId = $(firstClip).attr('id');
                clipPath = 'http://cache.Reelz.com/assets/content/clips/mp4/' + clipPath + '.mp4';
                var repFrame = $(firstClip).children('a').children('img').attr('src').replace('_th.jpg', '_med.jpg');
                //html = '<video id="html5Video" onplay="javascript:playAd();" height=' + height + ' width=' + width + ' src="' + clipPath + '" onended="javascript:html5VideoEnded(' + currentClipId + ');" onloadeddata="javascript:html5VideoPlay(' + currentClipId + ');" poster=' + repFrame + ' controls="controls">Your browser does not support the video element.</video>';
                html = '<video id="html5Video" height=' + height + ' width=' + width + ' src="' + clipPath + '" onended="javascript:html5VideoEnded(' + currentClipId + ');" onloadeddata="javascript:html5VideoPlay(' + currentClipId + ');" poster=' + repFrame + ' controls="controls">Your browser does not support the video element.</video>';
            }
        } else {
             var clipPath = clipId; // clip 
            clipPath = 'http://cache.Reelz.com/assets/content/clips/mp4/' + clipPath + '.mp4';
            var repFrame = null;
            //html = '<video id="html5Video" onplay="javascript:playAd();" height=' + height + ' width=' + width + ' src="' + clipPath + '" onended="javascript:html5VideoEnded(' + clipId + ');" onloadeddata="javascript:html5VideoPlay(' + clipId + ');" poster=' + repFrame + ' controls="controls">Your browser does not support the video element.</video>';
            html = '<video id="html5Video" height=' + height + ' width=' + width + ' src="' + clipPath + '" onended="javascript:html5VideoEnded(' + clipId + ');" onloadeddata="javascript:html5VideoPlay(' + clipId + ');" poster=' + repFrame + ' controls="controls">Your browser does not support the video element.</video>';
        }
    } else {
    html = "<div id=\"flashContent\" class=\"flashContent\">" +
                                "<a id=\"playerInstallMsg\" style=\"display:none; color: #EEEEEE;\" href=\"http://get.adobe.com/flashplayer/\">Click here to download the Adobe Flash Player.</a>" +
                            "</div>" +
                            "<script type=\"text/javascript\">" +
                                "var flashVersion = swfobject.getFlashPlayerVersion().major + \".\" + swfobject.getFlashPlayerVersion().minor + \".\" + swfobject.getFlashPlayerVersion().release;" +
                                "if (!swfobject.hasFlashPlayerVersion(\"9.0.45\")) {" +
                                    "document.getElementById(\"playerInstallMsg\").style.display = \"block\"; swfobject.embedSWF(\"dne.swf\", \"flashContent\", \"100%\", \"100%\", \"9.0.124\", \"/assets/flash/expressInstall.swf\");" +
                                "} else {" +
                                    "var flashvars = {clipid: \"" + clipId + "\" ,listCount: \"" + listCount + "\" ,listPageNum: \"" + listPageNum + "\",listClipType: \"" + clipType + "\",listRelatedIds: \"" + relatedId + "\",lpid: \"" + lpid + "\",rpid: \"" + rpid + "\",listMovieReleaseType: \"" + releaseType + "\", listStartDate: \"" + startDate + "\",listEndDate: \"" + endDate + "\",listSortOrder: \"" + sortOrder + "\",showAbout: \"false\"};" +
                                    "var params = {allowScriptAccess: \"always\",allowFullScreen: \"true\",wmode: \"transparent\"};" +
                                    "var attributes = {id: \"syndicatedSWF\",name: \"syndicatedSWF\"};" +
                                    "swfobject.embedSWF(\"http://cache.reelz.com/assets/flash/syndicatedPlayer.swf\", \"flashContent\", \"100%\", \"100%\", flashVersion, \"/assets/flash/expressInstall.swf\", flashvars, params, attributes);" +
                                "}" +
                            "</script>";
    }
    $('#' + parentDivId).append(html);
}
function html5VideoPlay(clipid) {
    _gaq.push(['_trackEvent', 'html5 Video Play', 'html5', clipid.toString()]);
    //var pageTracker = _gat._getTracker("UA-343720-9");
    //pageTracker._initData();
    //pageTracker._trackEvent('html5 Video Play', 'html5', clipid);
}
function html5VideoEnded(clipid) {
    _gaq.push(['_trackEvent', 'html5 Video End', 'html5', clipid.toString()]);    
    //var pageTracker = _gat._getTracker("UA-343720-9");
    //pageTracker._initData();
    //pageTracker._trackEvent('html5 Video End', 'html5', clipid);
}
/*var adAlreadyPlayed = false; var clipUrl = ''; var clickUrl = ""; var adUrl = "";
function playAd() {
    if (adAlreadyPlayed) return;
    var video = document.getElementById('html5Video');
    video.pause();
    $('#player-embed').css("position", "relative");
    $('#player-embed').append('<img id="adLoading" src="http://cache.Reelz.com/assets/content/general/loading-blkbg.gif" style="border:0;left:207px;top:95px;width:100px;height:100px;position:absolute;z-index:1000;opacity: .8; filter: alpha(opacity=80);"/>');
    $('#videoAd').attr('src', 'http://www.Reelz.com/assets/widgets/ad.html?slot=i_html5_preroll');
    adAlreadyPlayed = true;
}
function videoAdRcvd(adXmlObj) {
    if (adXmlObj != null && typeof adXmlObj != 'undefined') {
        var adXml = adXmlObj.innerHTML;
        adUrl = $(adXml).find('url').text();
        clickUrl = $(adXml).find('clickurl').text();
        if (adUrl != '') {
            var video = document.getElementById('html5Video');
            clipUrl = video.src;
            $('#html5Video').removeAttr('controls');
            video.src = adUrl;
            video.load();
            video.play();
            video.addEventListener('click', adClicked, false);
            video.addEventListener('loadeddata', hideCurrentPlayer, false);
            video.addEventListener('ended', adEnded, false);
            return;
        }
    }
    $('#player-embed #adLoading').remove();
    var video = document.getElementById('html5Video'); video.play();
}
function adClicked() { window.open(clickUrl, '_blank'); }
function hideCurrentPlayer() { $('#player-embed #adLoading').remove(); $('#player-embed').append('<span id="adMessage" style="position:absolute;z-index:1000;color:#FFFFFF; font-size:16px; font-weight:bold;text-align:center;bottom:0px;left:0px;width:100%;height:24px;display:block;">Your selected video will start after this short ad.</span>'); }
function adEnded() {
    $('#player-embed #adMessage').remove();
    var video = document.getElementById('html5Video');
    video.src = clipUrl;
    var video = document.getElementById('html5Video');
    video.removeEventListener('loadeddata', hideCurrentPlayer, false);
    video.removeEventListener('ended', adEnded, false);
    video.removeEventListener('click', adClicked, false);
    video.load();
    video.play();
    $('#html5Video').attr('controls', 'controls');
}
*/

function hideMovieMineLink(elementId) {
    if (navigator.userAgent.toLowerCase().indexOf("ipad") >= 0 || navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
        $('#' + elementId).css('display', 'none');
        var prevMenu = $('#' + elementId).prev('.navItem');
        if (prevMenu != null) {
            var menuLink = $(prevMenu).children();
            if (menuLink != null)
                $(menuLink).addClass('last');
        }
    }
}
function hideMovieMineTab(classId) {
    if (navigator.userAgent.toLowerCase().indexOf("ipad") >= 0 || navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
        $('li.' + classId).css('display', 'none');
    }
}

// User Comments Methods
function submitCommentReport(commentId)
{
	var answer = confirm("Are you sure you want to report this?");
	if (answer)
	{		
		var toPost = "commentId=" + commentId;
		makeRequest(BASE_URL + "data/usercommentreport.aspx", commentReportSubmitted, toPost);
		
		var reported = document.getElementById("reported" + commentId);
		reported.innerHTML = "abuse reported";
	}
}

function commentReportSubmitted()
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var response = http_request.responseText;
	        
			if (response.length > 0)
			{

			}
		}
	}
}

function setParentControlId(valueToSet)
{
    $("div.commentForm").css("display", "none");
    $("div.commentForm").appendTo("#ReplyForm-" + valueToSet.toString());
    
    if ($("div.ReplyForm").css("display") == "block")
    {
        $("div.ReplyForm").css("display", "none");
    }
    else
    {
        $("div.ReplyForm").css("display", "block");    
    }
    
    $("div.commentForm").slideDown("slow");
    
    if (ParentControlID != null)
    {
        document.getElementById(ParentControlID).value = valueToSet;
    }
}

// TW sack
/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
					
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								 
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
								    self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

// HeadEnds JS
this.headEnds = new headEnds();
var pagename = "";
var zipcode = "";
var contentdiv = null;
function headEnds() {
    this.requesturl = "/services/getheadends.aspx";
    this.zipcodeParam = "zip";
    this.typeParam = "out";
   
    this.findReelzChannelHeadends = function(zip, contextName, results, type, maxcount) {
        if (zip.length == 5)
        {
            contentdiv = results;
            this.find(zip, type, contextName, maxcount);
	    }
    }
    this.find = function(zip, type, title, maxcount) {
	    this.ajax = new sack();            
        this.ajax.setVar( this.zipcodeParam, zip); 
        this.ajax.setVar( this.typeParam, type);
        this.ajax.setVar("f", "html");
        if (maxcount != null && maxcount > 0)
            this.ajax.setVar("c", maxcount.toString());
        this.ajax.requestFile = this.requesturl;
        this.ajax.method = "GET"; 
        this.ajax.element = contentdiv;
        
        contentObj = document.getElementById(contentdiv);
        if (contentObj) { contentObj.style.display = "block";}
        if (contentObj && contentObj.parentNode) { contentObj.parentNode.style.display = "block"; }
        obj = document.getElementById("allcities_reelzchannel");
        if (obj) { obj.style.display = "block";}           
        
        document.getElementById(contentdiv).innerHTML = "";	   
        zipcode = zip;
        pagename  = title;
        this.ajax.onCompletion = this.whenCompleted;
        this.ajax.runAJAX();
    }
    this.whenCompleted = function() {
        if (document.getElementById(contentdiv).innerHTML.length > 0) {
            if (document.getElementById(contentdiv).innerHTML.toLowerCase() != 'please enter a valid zip code.') {
                // If the member is logged in and the User's zipcode hasn't been changed
                // then skip the google analytics event.
                var previousZipcode = getZipCode();
                setZipCode(zipcode);
                var zipcodeChanged = false;
                if (previousZipcode != null) {
                    if (previousZipcode != zipcode) {
                        zipcodeChanged = true;
                    }
                }
                else {
                    zipcodeChanged = true;
                }
                if (getCookie("__REELZ_ACCOUNT_ID") != null || zipcodeChanged) {
                    if (pagename.length <= 0)
                        pagename = 'home';
                    if (!pageTracker) {
                        if (typeof (_gat) == 'object') {
                            var pageTracker = _gat._getTracker(_uacct);
                            pageTracker._trackPageview(); // seems wrong to have this, but is necessary avoid 'y is undefined error'
                            pageTracker._trackEvent('ZIP Code Lookups', pagename, zipcode);
                        }
                    }
                }
            }
        }
    }     
}

// Link Building Pro ver 1.0
// Copyright Latent Motion, at seox.org

//function init(){

//// Options:
//var useMetaKeyword = false; // Otherwise, page title
//var minLength = 40; // Min selection chars
//var useMetaAuthor = false; // Otherwise use domain
//var addLinks = true; // Otherwise, just cite at end
//var skip = new Array("home","link","click here"); // Don't link these (lowercase!)
//	
//function D(b,a,c){if(b.addEventListener)b.addEventListener(a,c,false);else b.attachEvent&&b.attachEvent("on"+a,c)}function o(b,a){if(typeof b=="undefined"||b==null||!RegExp)return false;a=new RegExp("(^|\\s)"+a+"(\\s|$)");if(typeof b=="string")return a.test(b);else if(typeof b=="object"&&b.className)return a.test(b.className);return false}function E(b,a){var c=false,j;for(j=b.parentNode;j!=undefined;){if(b.parentNode==e.body)break;else if(b.parentNode==a){c=true;break}j=j.parentNode}return c}
//function F(b){return b.replace(/^\s*/,"")}function G(b){return b.replace(/\s*$/,"")}function H(b){return G(F(b))}var I=new Array("home","link","click here"),e=document,x=window,t=e.getElementsByTagName("body")[0],p=e.getElementsByName("author"),i=e.getElementsByName("keywords"),q=x.location.toString(),u=e.title.toString(),d;if(!Array.indexOf)Array.prototype.indexOf=function(b,a){var c=-1;for(a=a|0;a<this.length||a==-1;a++)if(this[a]==b)c=a;return c};if(i.length>0&&useMetaKeyword){i=e.getElementsByName("keywords")[0].getAttribute("content").split(",");
//    u = Math.floor(Math.random() * i.length); i = i[u].replace(/^\s*|\s*$/, "")
//} else i = u; p = (p.length > 0 && useMetaAuthor) ? p[0].getAttribute("content") : e.domain;
//var y = "<p id='credit'><br/>Read more about <a href='" + q + "'>" + i + "</a> by <a href='http://" + e.domain + "' />" + p + "</a></p>";
//if (/MSIE/g.test(navigator.userAgent)) var v = "msie"; else if (/Safari/g.test(navigator.userAgent)) v = "safChrome";
//q=e.createElement("span");q.setAttribute("id","sasText");t.appendChild(q);d=e.getElementById("sasText");posType=document.all&&!window.opera&&!window.XMLHttpRequest?
//"absolute":"fixed";d.style.position=posType;d.style.top="0px";d.style.left="-9999px";D(t,"copy",function(){d.innerHTML=y;if(v=="msie"){for(var b=e.selection.createRange(),a=b.parentElement();a.nodeName!="BODY"&&!o(a,"lbExclude");)a=a.parentNode;if(o(a,"lbExclude"))return true;a=e.body.createTextRange();a.moveToElementText(d);var c=b.duplicate();c=c.htmlText;if(c.length>minLength){d.id="tempSasText";d.innerHTML=c+y;(c=e.getElementById("sasText"))&&c.parentNode.removeChild(c);d.id="sasText";a.select()}}else{b=
//x.getSelection(); for (a = b.anchorNode; a.nodeName != "BODY" && !o(a, "lbExclude"); ) a = a.parentNode; if (o(a, "lbExclude")) return false; if (b == "" && v == "safChrome")
//{d.innerHTML=t.innerHTML;a=document.createRange();b.removeAllRanges();a.selectNodeContents(d);b.addRange(a)}else if(b.toString().length>minLength){var j=e.getElementById("credit");a=b.getRangeAt(0);c=a.cloneContents();d.id="tempSasText";d.insertBefore(c,j);(c=e.getElementById("sasText"))&&c.parentNode.removeChild(c);d.id="sasText";b.removeAllRanges();a.selectNode(d);
//b.addRange(a)}}var w=[];a=d.getElementsByTagName("a");for(b=0;b<a.length;b++)w.push(a[b].href);if(addLinks){a=e.getElementsByTagName("a");for(b=0;b<a.length;b++){var r=a[b].href;if(w.indexOf(r)==-1)if(E(a[b],d)==false){var f=H(a[b].innerHTML).toLowerCase();if(skip.indexOf(f)==-1)if((new RegExp(e.domain,"g")).test(r)){var z=[];function n(g,k,l){for(var A=g.childNodes.length;A-- >0;){var h=g.childNodes[A];if(h.nodeType===1)h.tagName.toLowerCase()!=="a"&&n(h,k,l);else if(h.nodeType===3)for(var m=h.data.length;1;){m=
//h.data.lastIndexOf(k,m);if(m===-1||z.indexOf(k.toLowerCase())!==-1)break;var B=/\w/;if(h.nodeValue.charAt(m-1).match(B)||h.nodeValue.charAt(m+f.length).match(B))break;l.call(window,h,m)}}}function s(g,k){g.splitText(k+f.length);var l=e.createElement("a");l.href=r;l.appendChild(g.splitText(k));g.parentNode.insertBefore(l,g.nextSibling);z.push(f.toLowerCase());w.push(r)}n(d,f,s);f=f.charAt(0).toUpperCase()+f.slice(1);n(d,f,s);f=f.toUpperCase();n(d,f,s);f=f.replace(/\w\S*/g,function(g){return g.charAt(0).toUpperCase()+
//g.substr(1).toLowerCase()});n(d,f,s)}}}}})}window.onload=init;

// Facebook Connect JS
function DoFBLogout() 
{
    var session = FB.Facebook.apiClient.get_session();
    if (session != null) {
        var user = session ? session.uid : null;
        var singleton = FB.Connect._singleton;
        var nextUrl = FBIntern.Uri.addQueryParameters(
              FB.XdComm.Server.singleton.get_receiverUrl(),
              'fb_login&fname=_parent&session=loggedout'
            );
        singleton._ensureLoginHandler();
        singleton._logoutCallback = "/profile/signout.aspx";
        logoutUrl = FBIntern.Utility.getFacebookUrl('www');
        logoutUrl += 'logout.php?app_key=' + FB.Facebook.apiKey;
        logoutUrl += '&session_key=' + encodeURIComponent(
              session.session_key
            ) + '&next=' + encodeURIComponent(nextUrl);
                FB.Facebook.apiClient.set_session(null);
                singleton.set__userInfo(null);
                singleton._logoutIframe = FB.XdComm.Server.singleton.createNamedHiddenIFrame(
              'fbLogout',
              logoutUrl,
              'fb_logout',
              null
            );
    }
}
function loadPageWithQS(fromUrl, qs, qsValue) {
    var index = fromUrl.indexOf(qs, 0);
    if (index >= 0) {
        var remUrl = fromUrl.substring(index);
        var remQsIndex = remUrl.indexOf('&', 0);
        var url = fromUrl.substring(0, index) + qs + qsValue;
        if (remQsIndex >= 0)
            url += remUrl.substring(remQsIndex);
        location.href = url;
    }
    else {
        if (fromUrl.indexOf('?', 0) >= 0)
            location.href = fromUrl + "&" + qs + qsValue;
        else if (fromUrl.substring(fromUrl.length - 5) == '.aspx')
            location.href = fromUrl + "?" + qs + qsValue;
        else if (fromUrl.substring(fromUrl.length - 1) != '/')
            location.href = fromUrl + "/?" + qs + qsValue;
        else
            location.href = fromUrl + "?" + qs + qsValue;
    }
}
function removeQueryString(qs, fromUrl) {
    var url = fromUrl;
    var index = fromUrl.indexOf(qs, 0);
    if (index >= 0) {
        var remUrl = fromUrl.substring(index);
        var remQsIndex = remUrl.indexOf('&', 0);
        var url = fromUrl.substring(0, index - 1);
        if (remQsIndex >= 0)
            url += remUrl.substring(remQsIndex);
    }
    return url;
}
var submission_result;
function submitNewsletterOptInEmail(emailId, resultObj) {
    hideResponses();
    submission_result = resultObj;
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (emailPattern.test(emailId) == false) {
        submission_result.innerHTML = "<span>Please enter a valid email address.</span>";
        submission_result.style.display = "block";
    }
    else {
        $("#emailbox .loading").removeClass("hide"); ;
        submission_result.innerHTML = "";
        submission_result.style.display = "none";
        xmlHttp = getXmlHttpObject();
        xmlHttp.onreadystatechange = newsletterOptInEmailCallback;
        var url = BASE_URL + "webservices/alert.asmx/addEmailForNewsletterOptIn?email=" + emailId;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
        return;
    }
}
function hideResponses() {
    if ( submission_result != undefined && submission_result != null)
        submission_result.style.display = "none";
}
function newsletterOptInEmailCallback() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        $("#emailbox .loading").addClass("hide");
        submission_result.innerHTML = "<span>Check for the Newsletter Opt-In in your email.</span>";
        submission_result.style.display = "block";
    }
    else if (xmlHttp.readyState == 4) {
        $("#emailbox .loading").addClass("hide");
        submission_result.innerHTML = "<span>Subscription error, please try again later.</span>";
        submission_result.style.display = "block";
    }
}
function onKeyUpNewletterOptin(event, emailId, resultObj) {
    if (event.keyCode) {
        if (event.keyCode == 13) {
            //event.preventDefault();
            submitNewsletterOptInEmail(emailId, resultObj);
        }
    }
}
//var adtimerid = 0;
//$(document).ready(function () {
//    if ($("#expand-ad") != null && $("#expand-ad").length > 0) {
//        var today = new Date();
//        today.setUTCHours(today.getUTCHours() - 6);
//        var todayText = (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
//        if (todayText == '4/29/2011') {
//            if (today.getUTCHours() < 20 || today.getUTCHours() >= 22) { // B4 1PM MT
//                $('#expand-wrap a').attr('href', 'http://www.Reelz.com/specials/');
//                $('#expand-ad').css('background-image', 'url("http://cache.Reelz.com/assets/content/royalwedding/RW-pushdown-3.0.jpg")');
//            } else
//                $('#expand-ad').css('background-image', 'url("http://cache.Reelz.com/assets/content/kennedys/kennedys-pushdown-4.29.jpg")');
//        } else if (todayText == '4/30/2011') {
//            $('#expand-wrap a').attr('href', 'http://www.Reelz.com/specials/');
//            $('#expand-ad').css('background-image', 'url("http://cache.Reelz.com/assets/content/royalwedding/RW-pushdown-3.0.jpg")');
//        } else if (todayText == '5/1/2011' || todayText == '5/01/2011') {
//            $('#expand-wrap a').attr('href', 'http://www.Reelz.com/specials/');
//            $('#expand-ad').css('background-image', 'url("http://cache.Reelz.com/assets/content/royalwedding/RW-pushdown-3.0.jpg")');

//        } else {
//            $('#expand-ad').css('background-image', 'url("http://cache.Reelz.com/assets/content/kennedys/kennedys-pushdown-default.jpg")');
//        }
//        if (getQueryStringValue("pushdown") == "") {
//            startAdExpand();
//        } else {
//            if ($("#expand-wrap") != null && $("#expand-wrap").length > 0) { $("#expand-wrap").hide(); }
//        }
//    }
//});

function startAdExpand() {
    $("#expandBtn").click(function () { animateAdOpen(); return false; });
    // the following code is used to auto-expand the pushdown ad.
    /*if (getCookie("REELZ_PUSHONCE") == null) {
        $("#expand-ad").animate({ height: 400 }, 1000, null);
        setTimeout(endAdExpand, 6000);
    }
    var pushoncedt = new Date();
    pushoncedt.setTime(pushoncedt.getTime() + (60 * 60 * 1000)); // 1 hour ahead
    setCookie("REELZ_PUSHONCE", "1", pushoncedt);*/
}
function endAdExpand() {
    /*$("#expand-ad").animate({ height: 100 }, 1000, null);*/
}
function animateAdOpen() {
    //clearTimeout(adtimerid);
    $("#expandBtn").click(function () { animateAdClose(); return false; });
    $("#expandBtn").css("background-image", "url(http://cache.reelz.com/assets/content/general/collapsebutton.png)");
    $("#expand-ad").stop(false, false);
    $("#expand-ad").animate({ height: 400 }, { queue: false, duration: 500 }, null);
}
function animateAdClose() {
    //clearTimeout(adtimerid);
    $("#expandBtn").click(function () { animateAdOpen(); return false; });
    $("#expandBtn").css("background-image", "url(http://cache.reelz.com/assets/content/general/expandbutton.png)");
    $("#expand-ad").stop(false, false);
    $("#expand-ad").animate({ height: 100 }, { queue: false, duration: 300 }, null);
}

function onKeywordListSearch() {
    var searchKeyword = unescape(document.getElementById("txtKeywordSearch").value);
    if (searchKeyword != unescape(document.getElementById("txtKeywordSearch").defaultValue))
    {
        var url = removeQueryString("page=", location.href);
        loadPageWithQS(url, "keyword=", document.getElementById("txtKeywordSearch").value);
     }
    return false;
}
function onKeyUpKeywordListSearch(event) {
    if (event.keyCode) {
        if (event.keyCode == 13) {
            onKeywordListSearch();
        }
    }
    return false;
}
