$(document).ready(setupHeaderForm);
var COOKIEDATE = new Date();COOKIEDATE.setTime(COOKIEDATE.getTime() + (100 * 24 * 60 * 60 * 1000)); // 100 days
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; }
var cookieExpiryDate = new Date();cookieExpiryDate.setDate(cookieExpiryDate.getDate() + 10);
function setCookie(name, value, expires, domain, secure) { deleteCookie(name); document.cookie = name + "=" + value + ((expires) ? "; expires=" + expires.toGMTString() : "") + "; path=/" + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); }
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"; } }
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 validateZipCodeOnEnter(textinput, event, loadPage) {
    if (event.keyCode == 10 || event.keyCode == 13) {
        if (textinput.value.length == 5) {
            validateZipCode(textinput, loadPage);
        } else {
            textinput.value = "invalid zip";
        }
    }
    return false;
}
function validateZipCode(textinput, loadPage) {
    if (textinput.value.length == 5) {
        $.get("/services/zipcode.aspx?format=xml&zipcode=" + textinput.value, function(data) {
            var xml;
            if ($.browser.msie && typeof data == "string") {
                xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = false;
                xml.loadXML(data);
            } else {
                xml = data;
            }
            var zipRcvd = $(xml).find('zipcode').text();
            if (zipRcvd == textinput.value) {
                if (loadPage) {
                    setCookie("ZIPCODE", textinput.value, cookieExpiryDate);
                    setCookie("TIMEZONE", $(xml).find('zipcode').attr('timezone'), cookieExpiryDate);
                    if (location.href.indexOf('z=') > 0)
                        top.location = location.href.substring(0, location.href.indexOf('z=') - 1);
                    else
                        top.location = location.href;
                }
                else {
                    setCookie("ZIPCODE", textinput.value, cookieExpiryDate);
                    setCookie("TIMEZONE", $(xml).find('zipcode').attr('timezone'), cookieExpiryDate);
                }
            } else {
                textinput.value = "invalid zip";
            }
        });
    }
    return false;
}
function doClear(textinput) { textinput.value = "" }
function setDefaultWhenEmpty(textinput) { if (textinput.value == '') { textinput.value = textinput.defaultValue } }
function setupHeaderForm() {   
    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'));}; }
    var zipcode = getCookie("ZIPCODE");
    if (zipcode != null) {
        $("#txtZipHdr").val(zipcode);
    } else if ($("#txtZipHdr").val() == '') {
        $("#txtZipHdr").val(document.getElementById('txtZipHdr').defaultvalue);
    }
}
function setDefaultZipWhenEmpty(textinput) {
    var zipcode = getCookie("ZIPCODE");
    if (zipcode != null) {
        $("#txtZipHdr").val(zipcode);
    } else if (textinput.value == '') { textinput.value = textinput.defaultValue }
}
function navigateToTheaterMovieTimes(movieId) {
    location.href = "/theater-movie-times.aspx?movieid=" + movieId;
    return false;
}
function navigateToCableMovieTimes(movieId) {
    location.href = "/cable-movie-times.aspx?movieid=" + movieId;
    return false;
}
function getEpisodesByWeek(showId, startDate, endDate) {
    location.href = "/episodes.aspx?showid=" + showId + "&startDate=" + startDate + "&endDate=" + endDate;
}
function getBlogList(pageNum) {
    location.href = "/movie-news/?page=" + pageNum;
}
function getClipList(pageNum) {
    var index = location.href.indexOf('page=', 0);
    if (index >= 0) {
        location.href = location.href.substring(0, index) + "page=" + pageNum;
    } else {
        location.href = location.href + "?page=" + pageNum;
    }
}
function getTheaterDetail(theaterId, friendlyName, startDate) {
    location.href = "/theater/" + theaterId + "/" + friendlyName + "?date=" + encodeURIComponent(startDate);
}
function getTheaterMovieShowtimes(startDate, movieid, zipInput, zipcode) {
    if (zipInput != null) {
        validateZipCode(zipInput, 1);
    } else {
        location.href = "/theater-movie-times.aspx?zipcode=" + zipcode + "&movieid=" + movieid + "&startDate=" + encodeURIComponent(startDate);
    }
    return false;
}
var myRating;
function setMovieRating(movieId, rating, userId) {
    // call the web service to add/update movie rating for the user
    myRating = rating;
    xmlHttp = getXmlHttpObject();
    xmlHttp.onreadystatechange = movieRatingAdded;
    var url;
    if (userId != null && userId.length > 0) {
        url = "/webservices/rating.asmx/SetMovieRating?movieId=" + movieId + "&rating=" + rating + "&profileGuid=" + userId;
    } else {
        url = "/webservices/rating.asmx/SetMovieRatingNoGuid?movieId=" + movieId + "&rating=" + rating;
    }
    xmlHttp.open("GET", url, true);
    var beforeMe = document.getElementById("userratingspanel");
    if (beforeMe != null) {
        var newDivTag = document.createElement("div");
        newDivTag.id = "ratingSB"; newDivTag.innerHTML = '<div id="confMessage"><p>Thank You.</p><p>You have rated this movie <span class="rating rate' + rating.toString() + '">' + rating.toString() + '</span></p></div>';
        beforeMe.appendChild(newDivTag);
    }
    xmlHttp.send(null);
}
function movieRatingAdded() {
    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 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 getByDateAndTimeZone(startDate, timezone) {
    var newUrl;
    newUrl = getNewUrl(location.href, 'sd=', startDate);
    newUrl = getNewUrl(newUrl, 'tz=', timezone);
    top.location = newUrl;
}
function getNewUrl(url, qs, qsValue) {
    if (url.indexOf(qs) > 0) {
        var prefixIndex = url.indexOf(qs);
        var queryParamSize = url.substring(prefixIndex).indexOf('&');
        if (queryParamSize > 0) {
            newUrl = url.substring(0, prefixIndex + qs.length) + encodeURIComponent(qsValue) + url.substring(prefixIndex + queryParamSize);
        } else {
            newUrl = url.substring(0, prefixIndex + qs.length) + encodeURIComponent(qsValue);
        }
    } else if (url.indexOf('.aspx?') > 0) {
        newUrl = url + '&' + qs + encodeURIComponent(qsValue);
    } else {
        newUrl = url + '?' + qs + encodeURIComponent(qsValue);
    }
    return newUrl;
}
function trackVideoView(clipId, clipName, clipType) {
    if (typeof (_gaq) != 'object') {
        var _uacct = "UA-343720-12";
        if (document.location.hostname.toLowerCase().indexOf("m.reelz.com") >= 0) {
            _uacct = "UA-343720-15";
        }
        _gaq = _gaq || []; _gaq.push(['_setAccount', _uacct]); 
        _gaq.push(['_setDomainName', '.Reelz.com']);
    }    
    _gaq.push(['_trackEvent', 'Video Start', clipType, clipName + "-" + clipId]);
}
function trackVideoEnd(clipId, clipName, clipType) {
    if (typeof (_gaq) != 'object') {
        var _uacct = "UA-343720-12";
        if (document.location.hostname.toLowerCase().indexOf("m.reelz.com") >= 0) {
            _uacct = "UA-343720-15";
        }
        _gaq = _gaq || []; _gaq.push(['_setAccount', _uacct]); 
        _gaq.push(['_setDomainName', '.Reelz.com']);
    }    
    _gaq.push(['_trackEvent', 'Video End', clipType, clipName + "-" + clipId]);
}
var adAlreadyPlayed = false;var clipUrl = ''; var clickUrl = "";var adUrl = "";var html5ClipId = ""; var html5ClipName = ""; html5ClipType = "";
function playAd(clipId, clipName, clipType) {    
    if (adAlreadyPlayed) return;
    html5ClipId = clipId; html5ClipName = clipName; html5ClipType = clipType;
    var video = document.getElementById('html5Video');
    video.pause();
    $('#player').append('<img id="adLaoding" src="http://cache.Reelz.com/assets/content/general/loading-blkbg.gif" style="border:0;width:100px;height:100px;position:absolute;z-index:1000;opacity: .8; filter: alpha(opacity=80);"/>');
    $('#videoAd').attr('src', 'http://i.Reelz.com/assets/widgets/ad.html?slot=i_html5_preroll&cliptype=' + clipType);
    adAlreadyPlayed = true;    
    trackVideoView(clipId, clipName, clipType);
}
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 #adLaoding').remove();
  var video = document.getElementById('html5Video');video.play();
  video.addEventListener('ended', function() { trackVideoEnd(html5ClipId, html5ClipName, html5ClipType); },false);     
}
function adClicked() { window.open(clickUrl, '_blank'); }
function hideCurrentPlayer() {  $('#player #adLaoding').remove();$('#player').append('<span id="adMessage" style="position:absolute;z-index:1000;color:#FFFFFF; font-size:12px; 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 #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.addEventListener('ended', function() { trackVideoEnd(html5ClipId, html5ClipName, html5ClipType); },false);     
   video.load();
   video.play(); 
   $('#html5Video').attr('controls', 'controls');
}
function clipTypesMenuClick() {
    if ($('#ClipTypesMenu').css("display") == "block") {
        $('#ClipTypesMenu').slideUp(500);
    } else {
        $('#ClipTypesMenu').slideDown(500); 
    }
}
function loadClips(type) {
       $('#ClipTypesMenu').slideUp(500);
       location.href = "/trailer-clips/?type=" + type;        
}
function hideClipTypesMenu() {
    $('#ClipTypesMenu').slideUp(500);
}
function getMovieDetails(movieId) {
    var details = $('#movie-' + movieId );
    if (details != null && $(details).hasClass('current')) {
        $(details).slideUp(500);
        $(details).removeClass('current');
        return;
    }
    var currentVisibleDetails = $('#movie-review ul.movies .details.current');
    if (currentVisibleDetails != null && currentVisibleDetails.length > 0) {         
            $('#movie-review ul.movies .details.current').slideUp(500, function() {
                $('#movie-review ul.movies .details.current').removeClass('current');            
                $(details).slideDown(500);
                if ($(details).html().indexOf('LOADING') >= 0) {
                    $(details).load('/services/movie/getmoviedetail.aspx?format=html&mobile=true&out=consolidated&movieid=' + movieId, function() {                
                        $(details).css('background-color', '#CCCCCC');
                        $(details).css('text-align', 'left');
                        var clips = $('#cliplistUL-' + movieId + ' li');
                        if (clips.length > 0) {
                            var clipImageWidth = $(clips[0]).css("width");
                            clipImageWidth = clipImageWidth.substring(0, clipImageWidth.length - 2);
                            $('#cliplistUL-' + movieId).css("width", (parseInt(clipImageWidth) * clips.length).toString() + "px");
                        }
                        scrollContent = new iScroll('cliplistUL-' +  movieId, { hScrollbar: false });
                    });   
                }
                $(details).addClass('current');
            });
        
    } else {    
        $(details).slideDown(500);
        if ($(details).html().indexOf('LOADING') >= 0) {
            $(details).load('/services/movie/getmoviedetail.aspx?format=html&mobile=true&out=consolidated&movieid=' + movieId, function() {                
                $(details).css('background-color', '#CCCCCC');
                $(details).css('text-align', 'left');
                var clips = $('#cliplistUL-' + movieId + ' li');
                if (clips.length > 0) {
                    var clipImageWidth = $(clips[0]).css("width");
                    clipImageWidth = clipImageWidth.substring(0, clipImageWidth.length - 2);
                    $('#cliplistUL-' + movieId).css("width", (parseInt(clipImageWidth) * clips.length).toString() + "px");
                }
                scrollContent = new iScroll('cliplistUL-' +  movieId, { hScrollbar: false });
            });   
        }
        $(details).addClass('current');
    }        
}
