/**
 *  GLOBALS VARIABLES
 *  @todo need to be defined  where they are used...
 **/
var site_list_open = false;
var timer = null;
/**
 *  Mysterious function not used anywhere...
 *  ------------------------------------------------
 *  @return
 *  @todo    to be remove
 **/

function gup(name) {
    //name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    //var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regexS = "([0-9]+)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    ///alert(results);
    if (results == null) return "";
    else
    return results[1];
}
/**
 *  Tag something as a favorites for this user.
 *  ------------------------------------------------

 *  @param   type        model, scene, video, picture
 *  @param   id          the id of the item
 *  @param   scene_id    the id of the scene related to that item
 *  @call    ajax
 *  @return  void
 *  @todo    clean
 **/
var favedScenes = {};

function addFavorite(type, id, scene_id, nopopup) {
    //    alert("id in: " + id + ", scene_id:" + scene_id);
    if (typeof scene_id == 'boolean') {
        nopopup = scene_id;
        scene_id = null;
    }
    // Prevent many requests of the same ID
/*if (!favedScenes[''+type+id+scene_id])
		favedScenes[''+type+id+scene_id] = true;
	else
		return false;*/
    var url = "?guimode=ajax&action=addfavorite&type=" + type + "&id=" + id + "&scene_id=" + scene_id;
    $.get(url, function (data) {
        if (nopopup) {} else {
            processReturn(data);
        }
    });
    return false;
}
/**
 *  Tag something as a favorites for this user.
 *  ------------------------------------------------

 *  @param   data        a string messages receive from a callback
 *  @return  void
 *  @todo    clean
 **/

function processReturn(data) {
    $("#ajax_messages").html(data);
    $('#ajax_messages').slideDown('slow');
    setTimeout("$('#ajax_messages').slideUp('slow')", 5000);
}
/**
 *  Function call before a search submit to prepare the search
 *  ------------------------------------------------
 *  @return  void
 **/

function doSearch(event) {
    var filter_form = $('#search-filters');
    if (filter_form.length > 0) {
        $('#search_term').val($('#header_search_term_real').val());
        $('#search-filters').submit();
        if (arguments.length && event.preventDefault) event.preventDefault();
        else
        return false;
    } else if (!arguments.length || !event.target || (event.target != $('#header-search_real')[0] && (!event.target.form || event.target.form != $('#header-search_real')[0]))) $('#header-search_real').submit();
}
/**
 *  Open/Close the list of the site in the left nav
 *  ------------------------------------------------
 *  @return  void
 *  @todo   clean
 **/

function toggleSiteList() {
    $("#site_list").removeClass("leftnav-bullets");
    if (site_list_open) {
        $('#site_list').slideUp('slow');
        site_list_open = false;
    } else {
        $('#site_list').slideDown('slow');
        site_list_open = true;
    }
    $("#site_list").addClass("leftnav-bullets");
}
/**
 *  Call a Flash Player in a User Profile
 *  ------------------------------------------------

 *  @param   part        A speficic part of the scene ?
 *  @param   scene_id    id of the scene
 *  @param   type        type of video
 *  @param   ext         video format ?
 *  @param   video       source of the file
 *  @param   is_trial    does the user is a trial ?
 *  @param   autoplay    autoplay switch
 *  @param   squished    switch that change the size of the player.
 *  @return  void
 *  @todo    clean and maybe merge with other function
 **/

function showPlayerFromProfile(part, scene_id, type, ext, video, is_trial, autoplay, squished) {
    var width, height, fs;
    if (typeof(autoplay) == "undefined") {
        autoplay = 0;
    }
    if (typeof(squished) == "undefined") {
        squished = 0;
    }
    if (squished) {
        width = 503;
        height = 397;
        fs = 'true';
    } else {
        width = 640;
        height = 506;
        fs = 'true';
    }
    if (is_trial) {
        width = 400;
        height = 326;
        fs = 'false';
    }
    var targetID = "#video_wrapper";
    if (is_trial) {
        targetID = "#porn_trial"
    }
    var browserversion = navigator.appVersion,
        is_mac = (browserversion.toLowerCase().indexOf("mac") != -1);
    if (ext == 'wmv') {
        height += 50;
        if (is_mac) {
            $(targetID).html('<embed type="application/x-mplayer2" src="' + video + '" name="MediaPlayer width="' + width + '" height="' + height + '" showStatusBar="true" scale="ASPECT"></embed>');
        } else {
            if (window.ie7) {
                $(targetID).html('<object classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" type="application/x-oleobject" width="' + width + '" height="' + height + '" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" standby="Loading Microsoft Windows Media Player components..."><param name="url" value="' + video + '"><param name="autostart" value="' + autoplay + '"><param name="ShowStatusBar" value="true"><param name="volume" value="100"><param name="stretchToFit" value="false"></object>');
            } else {
                if (is_trial) target = 'porn_trial';
                else target = 'video_wrapper';
                player = document.getElementById(target);
                player.innerHTML = '<object id="mplayer" width="' + width + '" height="' + height + '" type="application/x-mplayer2"><param name="fileName" value="' + video + '"><param name="autostart" value="' + autoplay + '"><param name="ShowStatusBar" value="1"><param name="volume" value="0"></object>';
            }
        }
        $(targetID).show();
    } else {
        if (type == 'Parts') {
            file = 'parts.php';
            url = 'videooptions/' + file + '?infos=' + scene_id + '/' + (part - 1) + '/' + ext + '/' + autoplay;
        } else if (type == 'OneMin') {
            file = 'one_min.php';
            url = 'videooptions/' + file + '?infos=' + scene_id + '/' + (part - 1) + '/' + ext + '/' + autoplay;
        } else if (type == 'Trailer') {
            file = 'trailer.php';
            url = 'videooptions/' + file + '?infos=' + scene_id + '//' + ext + "/" + autoplay;
        } else {
            file = '';
            url = 'videooptions?infos=' + scene_id + '//' + ext + '/' + autoplay;
        }
        var target = 'porn_' + scene_id;
        html = '<div id="porn_' + scene_id + '"></div>' + '<script language="javascript">' +
        //'var s1 = new SWFObject("player/brazzers_new_player2.swf?v=2", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' +
        'var s1 = new SWFObject("http://static.brazzers.com/player/brazzers_new_player2.swf", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' + 's1.addParam("allowFullScreen","' + fs + '");' + 's1.addParam("AllowScriptAccess","always");' + 's1.addParam("wmode", "transparent");' + 's1.addVariable("options", "' + url + '");' + 's1.write("porn_' + scene_id + '");' + '</script>';
        $(targetID).html(html).show();
    }
    // now set the currently Currently Loaded Video span id=current_video if type=MainVideo or Parts
    if (type == "MainVideo") $("#current_video").html("Full Video");
    if (type == "Parts") $("#current_video").html("Partial Video #" + part);
    if (type == "OneMin") $("#current_video").html("One Minute Clip #" + part);
}

function showPlayer(part, scene_id, type, ext, video, is_trial, autoplay, squished) {
    if ((typeof BSPlayer == 'object' || typeof BSPlayer == 'function') && (typeof pornoman == 'object' || typeof pornoman == 'function')) {
        return false;
    }
    if (part == '') part = 0;
    if (typeof(autoplay) == "undefined") {
        autoplay = 0;
    }
    if (typeof(squished) == "undefined") {
        squished = 0;
    }
    var width, height, fs;
    if (ext == 'wmv' || ext == 'flv') {
        if (squished) {
            width = 503;
            height = 397;
            fs = 'true';
        } else {
            width = 640;
            height = 506;
            fs = 'true';
        }
        if (is_trial) {
            width = 400;
            height = 326;
            fs = 'false';
        }
        var targetID = "#video_wrapper";
        if (is_trial) {
            targetID = "#porn_trial"
        }
        var browserversion = navigator.appVersion,
            is_mac = (browserversion.toLowerCase().indexOf("mac") != -1);
        if (ext == 'wmv') {
            height += 50;
            if (is_mac) {
                $(targetID).html('<embed type="application/x-mplayer2" src="' + video + '" name="MediaPlayer width="' + width + '" height="' + height + '" showStatusBar="true" scale="ASPECT"></embed>');
            } else {
                if (window.ie7) {
                    $(targetID).html('<object classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" type="application/x-oleobject" width="' + width + '" height="' + height + '" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" standby="Loading Microsoft Windows Media Player components..."><param name="url" value="' + video + '"><param name="autostart" value="' + autoplay + '"><param name="ShowStatusBar" value="true"><param name="volume" value="100"><param name="stretchToFit" value="false"></object>');
                } else {
                    if (is_trial) {
                        target = 'porn_trial';
                    } else {
                        target = 'video_wrapper';
                    }
                    player = document.getElementById(target);
                    player.innerHTML = '<object id="mplayer" width="' + width + '" height="' + height + '" type="application/x-mplayer2"><param name="fileName" value="' + video + '"><param name="autostart" value="' + autoplay + '"><param name="ShowStatusBar" value="1"><param name="volume" value="0"></object>';
                }
            }
            $(targetID).show();
            if (autoplay) {
                $.scrollTo(targetID, 'slow');
            }
        } else {
            var url, file;
            if (type == 'Parts') {
                file = 'parts.php';
                url = 'videooptions/' + file + '?infos=' + scene_id + '/' + (part - 1) + '/' + ext + '/' + autoplay;
            } else if (type == 'OneMin') {
                file = 'one_min.php';
                url = 'videooptions/' + file + '?infos=' + scene_id + '/' + (part - 1) + '/' + ext + '/' + autoplay;
            } else if (type == 'Trailer') {
                file = 'trailer.php';
                url = 'videooptions/' + file + '?infos=' + scene_id + '//' + ext + "/" + autoplay;
            } else {
                file = '';
                url = 'videooptions?infos=' + scene_id + '//' + ext + '/' + autoplay;
            }
            var pversion = 'brazzers_new_player2',
                target = 'porn_' + scene_id;
            if ($(".trial_popup_block").size() == 1) {
                pversion = 'brazzers_new_player10';
            }
            html = '<div id="porn_' + scene_id + '"></div>' + '<script language="javascript">' +
            //'var s1 = new SWFObject("player/brazzers_new_player2.swf?v=2", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' +
            'var s1 = new SWFObject("http://static.brazzers.com/player/' + pversion + '.swf", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' + 's1.addParam("allowFullScreen","' + fs + '");' + 's1.addParam("AllowScriptAccess","always");' + 's1.addParam("wmode", "transparent");' + 's1.addVariable("options", "' + url + '");' + 's1.write("porn_' + scene_id + '");' + '</script>';
            $(targetID).html(html).show();
            if (autoplay) {
                $.scrollTo(targetID, 'slow');
            }
        }
    } else {
        if (type == 'hdvideo_768' || type == 'hdvideo_1280' || type == 'trailer') {
            var method = PLAYER_MODE.method,
                quality = PLAYER_MODE.quality,
                flow_bg_image = flow_bg_image_480;
            aspect_ratio = '16:9';
            if (quality == 'tl-hd' || quality == 'hd') {
                type = 'hdvideo_1280';
                flow_bg_image = flow_bg_image_720;
            }
        }
        var is_hd = sceneIsHd,
            is_wide = sceneWidePlayer,
            aspect_ratio = sceneAspectRatio,
            showinfo = 1;
        if (autoplay) showinfo = 0;
        if (aspect_ratio == '16:9') {
            width = 768;
            height = 432 + 6;
        } else {
            width = 768;
            height = 480 + 6;
        }
        switch (type) {
        case "Parts":
            part = part - 1;
            break;
        case "OneMin":
            part = part - 1;
            break;
        case "hdvideo_1280":
            part = 0;
            width = 975;
            height = 548 + 6;
            break;
        }
        if (typeof fp_stream_data != 'undefined') {
            var clipobj = {
                'autoPlay': false,
                'scaling': 'fit',
                // the try is because logging logic used right now is based on old xml format, and the function is built within the scene page..
                // which may or may not be used here...
                'onStart': function (event) {
                    try {
                        videostart();
                    } catch (ex) {}
                }
            },
                pluginsobj = {},
                video_type = (type == 'trailer') ? 'trailer' : 'full'; /* Select video quality based on Cookie Preference. The first condition define the new video format standard. */
            if (fp_stream_data[video_type]['http'][320] != undefined) {
                if (method == 'http') {
                    clipobj.provider = 'pseudostreaming';
                    switch (quality) {
                    case "sd-light":
                        clipobj.url = fp_stream_data[video_type]['http'][320]['mp4'][500]['url'];
                        break;
                    case "sd-med":
                        clipobj.url = fp_stream_data[video_type]['http'][480]['mp4'][750]['url'];
                        break;
                    case "sd-high":
                        clipobj.url = fp_stream_data[video_type]['http'][480]['mp4'][2000]['url'];
                        break;
                    case "hd":
                        clipobj.url = fp_stream_data[video_type]['http'][720]['mp4'][2600]['url'];
                        break;
                    case "tl-hd":
                        clipobj.url = fp_stream_data[video_type]['http'][720]['mp4'][3800]['url'];
                        break;
                    }
                } else // RTMP by default
                {
                    clipobj.provider = 'rtmp';
                    pluginsobj.rtmp = {
                        netConnectionUrl: fp_stream_data[video_type]['rtmp']['connection']
                    };
                    switch (quality) {
                    case "sd-light":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][320]['mp4'][500];
                        break;
                    case "sd-med":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][480]['mp4'][750];
                        break;
                    case "sd-high":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][480]['mp4'][2000];
                        break;
                    case "hd":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][720]['mp4'][2600];
                        break;
                    case "tl-hd":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][720]['mp4'][3800];
                        break;
                    }
                }
            } else {
                if (method == 'http') {
                    clipobj.provider = 'pseudostreaming';
                    switch (quality) {
                    case "sd-light":
                        clipobj.url = fp_stream_data[video_type]['http'][432]['f4v'][700]['url'];
                        break;
                    case "sd-med":
                        clipobj.url = fp_stream_data[video_type]['http'][432]['f4v'][1000]['url'];
                        break;
                    case "sd-high":
                        clipobj.url = fp_stream_data[video_type]['http'][432]['f4v'][1500]['url'];
                        break;
                    case "hd":
                        clipobj.url = fp_stream_data[video_type]['http'][720]['f4v'][3000]['url'];
                        break;
                    case "tl-hd":
                        clipobj.url = fp_stream_data[video_type]['http'][720]['f4v'][4000]['url'];
                        break;
                    }
                } else // RTMP by default
                {
                    clipobj.provider = 'rtmp';
                    pluginsobj.rtmp = {
                        netConnectionUrl: fp_stream_data[video_type]['rtmp']['connection']
                    };
                    switch (quality) {
                    case "sd-light":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][432]['f4v'][700];
                        break;
                    case "sd-med":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][432]['f4v'][1000];
                        break;
                    case "sd-high":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][432]['f4v'][1500]
                        break;
                    case "hd":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][720]['f4v'][3000]
                        break;
                    case "tl-hd":
                        clipobj.url = fp_stream_data[video_type]['rtmp'][720]['f4v'][4000]
                        break;
                    }
                }
            }
            var reg = new RegExp("cdn1.", "i");
            if (pluginsobj.rtmp) {
                if (reg.test(pluginsobj.rtmp.netConnectionUrl)) {
                    $("#porn").data("provider", "level3");
                } else {
                    $("#porn").data("provider", "swittwill");
                }
            } else {
                $("#porn").data("provider", "swittwill");
            }
            // The videobufferingstart event handler
            clipobj.onBegin = function (e) {
                var date = new Date();
                $("#porn").data("bufferstart", date.getTime());
                body.trigger("videoplayer.begin");
            };
            // The videostreamingstart event handler
            clipobj.onStart = function (e) {
                $this = $("#porn");
                var date = new Date();
                $this.data("bufferingdone", date.getTime());
                var bufferstart = $this.data("bufferstart"),
                    bufferdone = $this.data("bufferingdone");
                if (!bufferstart || !bufferdone) return false;
                // video start - buffer start time = buffering laps time
                var buffertime = bufferdone - bufferstart,
                    scene_id = $("#scene_id").val(),
                    site_id = $("#site_id").val();
                var provider = $("#porn").data("provider");
                window._ST = window._ST || [];
                // Track scene watched
                window._ST.push(['_event', "videoplayer", "videoplayer.ma.scene.watched", "site:" + $("#site_id").val() + ",scene:" + $("#scene_id").val(), PLAYER_MODE.method + "_" + PLAYER_MODE.quality, 1]);
                // Send bufferingtime to stats server if ST is defined
                var event = (method == 'http') ? "videoplayer.ma." + provider + ".http.3sbuffering" : "videoplayer.ma." + provider + ".rtmp.3sbuffering";
                window._ST.push(['_event', "videoplayer", event, "site:" + site_id + ",scene:" + scene_id, buffertime]);
                body.trigger("videoplayer.start");
            };
            // The video pause event handler
            clipobj.onPause = function (e) {
                body.trigger("videoplayer.pause")
            };
            // The video resume event handler
            clipobj.onResume = function (e) {
                body.trigger("videoplayer.resume");
            };
            // The video seek event handler
            clipobj.onSeek = function (e) {
                body.trigger("videoplayer.seek")
            };
            // The video finish event handler
            clipobj.onFinish = function (e) {
                body.trigger("videoplayer.finish");
            };
            $('<img />').load(function () {
                showPlayerLoad(width, height, clipobj, pluginsobj, flow_bg_image);
            }).error(function () {
                showPlayerLoad(width, height, clipobj, pluginsobj, false);
            }).attr('src', flow_bg_image);
        }
        // Non HD Scene Player
        else if (!((type.split("_")[0] == 'hdvideo') && ($('div.player.lv3').size() != 0))) {
            // if not lv3 and other than hdvideo
            var videooptions_url = "get_scenes/" + scene_id + "/" + type + "/" + part + "/" + ext + "/autoplay-" + autoplay + "/show-info-" + showinfo;
            try {
                $('#fl_stream').val(videooptions_url);
            } catch (e) {}
            player = $("#porn");
            var flashvars = {
                options: videooptions_url,
                autostart: 'true',
                themeColor: '0395d3',
                mode: 'overlay',
                scaleMode: 'stretch',
                frameColor: '333333',
                fontColor: 'cccccc',
                link: '',
                embed: ''
            },
                params = {
                    allowFullScreen: 'true',
                    'wmode': 'transparent',
                    allowscriptaccess: 'always'
                },
                attributes = {
                    id: 'porn',
                    name: 'porn',
                    wmode: 'transparent'
                };
            swfobject.embedSWF('http://static.brazzers.com/player/wide_ma_player.swf', 'porn', width, height, '10.0.0', 'expressInstall.swf', flashvars, params, attributes);
        }
        var scene_title = $(".scene_navigation"),
            page_url = window.location.href,
            site_shortname = $("#site_shortname").val();
        if (page_url.indexOf('#comments') == -1) {
            $.scrollTo(scene_title, 'slow');
        }
        if (typeof(pageTracker) != "undefined") {
            pageTracker._trackEvent('Stream&Download', 'Stream-' + type, site_shortname + "/" + scene_id, 1);
        }
    }
    return false;
}

function showPlayerLoad(width, height, clipobj, pluginsobj, flow_bg_image) {
    var date = new Date();
    $("#porn").data("loadstart", date.getTime());
    $('#porn').html('<p style="padding-top: 200px;">Player is loading...</p>');
    var playlist = [];
    if (flow_bg_image) {
        playlist.push(flow_bg_image);
    }
    playlist.push(clipobj);
    var playObj = {
        key: flow_player_key,
        'playlist': playlist,
        plugins: pluginsobj
    };
    //Bind a custom error handler to the player
    playObj.onError = function (errorCode, errorMessage) {
        $this = $("#porn");
        var scene_id = $("#scene_id").val(),
            site_id = $("#site_id").val();
        // Send error type to stats server if ST is defined
        var provider = $("#porn").data("provider");
        var event = (clipobj.provider == 'pseudostreaming') ? "videoplayer.ma." + provider + ".http.error." : "videoplayer.ma." + provider + ".rtmp.error.";
        window._ST = window._ST || [];
        window._ST.push(['_event', "videoplayer", event + errorCode, "site:" + site_id + ",scene:" + scene_id, 1]);
        if (params.error_url) window.location = params.error_url;
        return false;
    };
    playObj.onLoad = function () {
        $this = $("#porn");
        var loadstart = $this.data("loadstart");
        if (!loadstart) return false;
        var date = new Date();
        var loaddone = date.getTime();
        // loaddone - loadstart = buffering laps time
        var loadtime = loaddone - loadstart;
        // Send loadtime to stats server if ST is defined
        window._ST = window._ST || [];
        window._ST.push(['_event', "videoplayer", "videoplayer.ma.loadtime", params.mode, loadtime]);
        return false;
    }
    $('#porn').html('').css('width', width + 'px').css('height', height + 'px');
    $f("porn", {
        'src': 'http://static.brazzers.com/player/player_rtmp_prog_bw_cont.swf',
        'wmode': 'opaque'
    }, playObj);
}
/**
 *  Call a Flash Player in the Home Header
 *  ------------------------------------------------
 **/

function showHeaderPlayer(scene_id, ext) {
    var videooptions_url = "get_scenes/" + scene_id + "/HeaderTrailer/0/" + ext + "/autoplay-0/show-info-0";
    var player = $("#porn");
    player.html("");
    player.flash({
        src: "http://static.brazzers.com/player/wide_ma_player.swf",
        width: 351,
        height: 229,
        wmode: "transparent",
        align: "middlel",
        allowfullscreen: true,
        allowscriptaccess: "always",
        allownetworkaccess: "always",
        flashvars: {
            options: videooptions_url
        }
    }, {
        version: "10.0.22"
    });
}
/**
 *
 * Clicks on the 480p or 720p tabs
 * (this function is called from the player)
 *
 **/

function toggleHdTabs(type) {
    if (type == 'hdvideo_1280') {
        $("#720p_link").click();
    } else {
        $("#480p_link").click();
    }
}
/**
 *  Call a Flash Player in a User Profile
 *  ------------------------------------------------
 *  @todo  clean and maybe merge with other top function
 **/

function showInterviewPlayer(id, vurl) {
    var scene_id = '';
    var width = 640;
    var height = 506;
    var fs = 'true';
    var file = 'simple.php';
    var url = 'videooptions/' + file + '?url=' + escape(vurl);
    var html = '<div id="porn_' + id + '"></div>' + '<script language="javascript">' + 'var s1 = new SWFObject("http://static.brazzers.com/player/brazzers_new_player2.swf", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' + 's1.addParam("allowFullScreen","' + fs + '");' + 's1.addParam("AllowScriptAccess","always");' + 's1.addParam("wmode", "transparent");' + 's1.addVariable("options", "' + url + '");' + 's1.write("porn_' + id + '");' + '</script>';
    $('#video_wrapper').html(html);
    $('#video_wrapper').show();
    var targetID = '#porn_' + id;
    // $.scrollTo(targetID, 'slow');
}
/**
 *  Call a Flash Player in a User Profile
 *  ------------------------------------------------
 *  @todo    clean and maybe merge with other top function
 **/

function showInterviewPlayerForProfile(id, vurl) {
    var scene_id = '';
    var width = 503;
    var height = 397;
    var fs = 'true';
    var file = 'simple.php';
    var url = 'videooptions/' + file + '?url=' + escape(vurl);
    var html = '<div id="porn_' + id + '"></div>' + '<script language="javascript">' + 'var s1 = new SWFObject("http://static.brazzers.com/player/brazzers_new_player2.swf", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' + 's1.addParam("allowFullScreen","' + fs + '");' + 's1.addParam("AllowScriptAccess","always");' + 's1.addParam("wmode", "transparent");' + 's1.addVariable("options", "' + url + '");' + 's1.write("porn_' + id + '");' + '</script>';
    $('#video_wrapper').html(html);
    $('#video_wrapper').show();
    var targetID = '#porn_' + id;
    //$.scrollTo(targetID, 'slow');
}
/**
 *  Call a Flash Player in a User Profile
 *  ------------------------------------------------
 *  @param   id          the id of the videos
 *  @param   autoplay    autoplay switch
 *  @param   squished    switch that change the size of the player.
 *  @return  void
 *  @todo    clean and maybe merge with other function
 **/

function showUserVidPlayer(id, autoplay, squished) {
    var width, height, fs;
    if (typeof(squished) == "undefined") {
        squished = 0;
    }
    if (squished) {
        width = 503;
        height = 397;
        fs = 'true';
    } else {
        width = 640;
        height = 506;
        fs = 'true';
    }
    var file = 'user_vids.php';
    var url = 'videooptions/' + file + '?infos=' + id + '/' + autoplay;
    var html = '<div id="porn_' + id + '"></div>' + '<script language="javascript">' + 'var s1 = new SWFObject("http://static.brazzers.com/player/brazzers_new_player2.swf", "pornplayer", "' + width + '", "' + height + '", "9.0.115.0");' + 's1.addParam("allowFullScreen","true");' + 's1.addParam("AllowScriptAccess","always");' + 's1.addParam("wmode", "transparent");' + 's1.addVariable("options", "' + url + '");' + 's1.write("porn_' + id + '");' + '</script>';
    $('#video_wrapper').html(html);
    $('#video_wrapper').show();
    var target = 'porn_' + id;
}
timer = null;
$(document).ready(function () {
    (function () {
        var blur_field = function () {
            if (!this.value) this.value = dvalue;
        },
            focus_field = function () {
                if (this.value == dvalue) this.value = '';
            },
            el = $('#header_search_term_real'),
            dvalue = el.focus(focus_field).blur(blur_field).bind('manual_blur', blur_field).attr('dvalue') || 'Enter Search Text...';
        el.trigger('manual_blur');
        delete el;
        $('#header-search_real').submit(doSearch);
    })();
    $("label.overlabel").overlabel();
    $(".pbtn_community, .pbtn_community").click(function () {
        $(".community_popup").show();
        return false;
    });
    $(".scene_unlock_720p_show, .scene_unlock_720p_show").click(function () {
        $(".scene_unlock_720p_popup").show();
        return false;
    });
    $(".scene_unlock_1080p_show, .scene_unlock_1080p_show").click(function () {
        $(".scene_unlock_1080p_popup").show();
        return false;
    });
    $(".pbtn_bzr, .btn_pb_bzr").click(function () {
        $.get("index.php?action=ajax/get_member_status", {
            site: 'bzr'
        }, function (res) {
            var info = $.trim(res).split("|");
            if (info[0] == 'full' || info[0] == 'trial') {
                $("#bzr_username").val(info[1]);
                $("#bzr_password").val(info[2]);
                $(".bzreel_popup form").submit();
            } else {
                window.location = $("#bzr_1clicklink").val();
            }
        });
        return false;
    });
    $("a.close").click(function () {
        $(this).parents("#popup_container").hide();
        return false;
    });
/*
	 * Submit cross login to mofos with captcha overwrite
	**/
    $("#get_capcha_and_submit").click(function () {
        var form = $(this).parents('form');
        $.get("?action=portal&guimode=ajax&get_capcha=true", function (capcha) {
            $("#captcha_bypass").val(capcha);
            form.submit();
        });
    });
    $("#setting_selector div div").hover(function () {
        $(this).addClass("settings_toggle_hover");
    }, function () {
        $(this).removeClass("settings_toggle_hover");
    });
    $('#settings_toggle').mouseover(function () {
        $('#setting_selector').slideToggle();
    });
    $('#setting_selector').mouseout(function () {
        timer = setTimeout('closeSettingSelector()', 3000);
    });
    $('#setting_selector').mouseover(function () {
        //cancel the closing timer
        clearTimeout(timer);
    });
/*
	 * Rewrite upsell links into nice looking ones..
	**/
    $('a.pbtn_empty, a.pbtn_footer_upsell, .upsell_leftnav a, .partner_block a, partner_block_large a, .portal_box a').each(function () {
        // In case the span with the rewrite url is not present, we dont want to execute this script
        if ($(this).attr('name') != '') {
            function clickLink() {
                var el = $(this);
                $.data(this, 'href', el.attr('href'));
                el.attr('href', $(this).attr('name'));
            }
            $(this).hover(function () {
                this.href = $(this).attr('name');
            }).mouseup(function () {
                this.href = $.data(this, 'href');
            })
            $.proxy(clickLink, this)();
        }
    });
    /**
     *
     *  Auto detect if the Brazzer Live Status bar has to show up based on the event day & settings
     *  Display the proper state for the user
     *
     **/
    if (typeof bzl_config != 'object') {
        bzl_config = {};
    }
    if (typeof bzl_config.status_bar_date != 'undefined' && bzl_config.status_bar_date != '') {
        /*
        var currentDate = new Date();
        var dd = currentDate.getDate();
        var mm = currentDate.getMonth() + 1;
        var yyyy = currentDate.getFullYear();
        if (dd < 10) {
            dd = '0' + dd
        }
        if (mm < 10) {
            mm = '0' + mm
        }
        currentDate = yyyy + '-' + mm + '-' + dd;
        if (currentDate >= bzl_config.bzl_status_bar_date) {
            if (typeof bzl_config.bzl_show_state !== 'undefined') {
                if (bzl_config.bzl_show_state != 'off') {
                    var shortly = null;
                    $('#bz_statusbar_countdown').countdown({
                        until: shortly,
                        expiryText: ''
                    });
                    if (typeof bzl_chat != 'undefined') {
                        if (parseFloat(bzl_chat) <= 0) {
                            if (parseFloat(bzl_replay) <= 0) {
                                liveStatus('replay');
                            } else if (parseFloat(bzl_liveshow) <= 0) {
                                $("a.promo_close").click();
                                liveStatus('liveshow');
                            } else if (parseFloat(bzl_preshow) <= 0) {
                                liveStatus('preshow');
                            } else {
                                liveStatus('chat');
                            }
                        } else {
                            liveStatus('before_start');
                        }
                    }
                }
            }
        }*/


        if (typeof bzl_chat !== 'undefined' &&
            typeof bzl_preshow !== 'undefined' &&
            typeof bzl_liveshow !== 'undefined' &&
            typeof bzl_replay !== 'undefined') {

            if (bzl_config.show_state != 'off') {
                var shortly = null;
                $('#bz_statusbar_countdown').countdown({
                    until: shortly, expiryText: ''
                });

                // Logic for status_bar
                if (typeof bzl_chat !== 'undefined') {
                    (parseInt(bzl_chat) <= 0 || bzl_chat === '') ?
                    ((parseInt(bzl_replay) <= 0) ?
                        liveStatus('replay') :
                        ((parseInt(bzl_liveshow) <= 0) ?
                            liveStatus('liveshow') :
                            ((parseInt(bzl_preshow) <= 0) ?
                                liveStatus('preshow') :
                                    (bzl_chat !== '') ?
                                    liveStatus('chat') :
                                    liveStatus('before_start')
                            )
                        )
                    )
                 : liveStatus('before_start') ;
                }
            }
        }








    }
    //Logout button tracking
    $(".btn_logout").click(function () {
        if (typeof(pageTracker) != "undefined") {
            pageTracker._trackEvent('GlobalEvent', 'Memberareas', 'logout', 1);
        }
    });
    /**
     *  Clear the default initial value on click
     *  Simply put the default value in the label tag
     *  ------------------------------------------------
     * @author: Mike (added here by GL)
     **/
    $(".clear_input").focus(function () {
        if ($(this).attr("label") == $(this).val()) {
            $(this).val("");
        }
    }).blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr("label"));
        }
    });
});

function closeSettingSelector(elementId) {
    $('#setting_selector').slideUp();
}

function showNetworkScenes() {
    $('#brazzers_content_scenes').fadeOut('fast', function () {
        $('#brazzers_network_scenes').fadeIn('fast');
    });
}

function showContentScenes() {
    $('#brazzers_network_scenes').fadeOut('fast', function () {
        $('#brazzers_content_scenes').fadeIn('fast');
    });
}

function getScroll() {
    var scrollY = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollY = document.documentElement.scrollTop;
    } else if (document.body && document.body.scrollTop) {
        scrollY = document.body.scrollTop;
    } else if (window.pageYOffset) {
        scrollY = window.pageYOffset;
    } else if (window.scrollY) {
        scrollY = window.scrollY;
    }
    return scrollY;
}
/**
 * @function: isScrolledIntoView
 * @description: Returns true if a given element (in jQuery) is visible in the window's current scroll range.
 */

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
/**
 * @function: roundFloat
 * @description: Rounds num to dec decimal places and returns it.
 */

function roundFloat(num, dec) {
    if (typeof dec != 'number') dec = 2;
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

function AddClickTaleTag(Tag) {
    if (window.ClickTaleTag) ClickTaleTag(Tag);
}
/**
 *
 *  Main Brazzers Live Status Bar function that splits up time into period and activate
 *  countdown for the next period based on settings
 *
 **/

function liveStatus(period) {
    status_light('off');
    if (period != 'before_start') {
        if ($.cookie("live_" + bzl_config.upcoming_show.number + "_status_bar")) {
            $('div.status_bar_container').height(35);
            $('div.status_bar_container').show();
        } else if ($('div.status_bar_container').height() != '35') {
            $('div.status_bar_container').show();
            $('div.status_bar_container').animate({
                height: 35
            }, 1000, function () {
                var expiry = new Date();
                expiry.setTime(expiry.getTime() + (30 * 60 * 1000));
                $.cookie("live_" + bzl_config.upcoming_show.number + "_status_bar", true, {
                    path: '/',
                    expires: expiry
                });
            });
        }
    }
    switch (period) {
    case 'chat':
        status_light('on', period);
        $('#bz_statusbar_countdown').countdown('change', {
            until: bzl_preshow,
            onExpiry: exp_status_chat
        });
        break;
    case 'preshow':
        status_light('on', period);
        $('#bz_statusbar_countdown').countdown('change', {
            until: bzl_liveshow,
            onExpiry: exp_status_preshow
        });
        break;
    case 'liveshow':
        $("a.promo_close").click();
        status_light('on', period);
        $('#bz_statusbar_countdown').countdown('change', {
            until: bzl_replay,
            onExpiry: exp_status_liveshow
        });
        break;
    case 'replay':
        status_light('on', period);
        break;
    default:
        var standby = (typeof bzl_chat !== 'undefined' && bzl_chat !== '') ? bzl_chat : bzl_preshow;

        $('#bz_statusbar_countdown').countdown('change', {
            until: standby, onExpiry: ((typeof bzl_chat !== 'undefined' && bzl_chat !== '') ? exp_status_before_start : exp_status_chat)
        });
        break;
    }
}
/**
 *
 *  Brazzers Live Status Bar, lights up the proper state
 *
 **/

function status_light(state, which) {
    if (state == 'off') {
        $('div.live_status ul li.on').addClass('off');
        $('div.live_status ul li.on').removeClass('on');
    } else {
        $('div.live_status ul li.off div.' + which).parent().addClass('on');
        $('div.live_status ul li.off div.' + which).parent().removeClass('off');
    }
}
/**
 *
 *  List of functions that are executed once the Live Satus Bar timer runs out
 *  Mainly this will update the state to the new one based on the defined settings
 *  TODO : look in the countdown class if onExpiry param can call a parametered function
 *
 **/

function exp_status_before_start() {
    liveStatus('chat');
}

function exp_status_chat() {
    liveStatus('preshow');
}

function exp_status_preshow() {
    $("a.promo_close").click();
    liveStatus('liveshow');
}

function exp_status_liveshow() {
    liveStatus('replay');
}
/**
 * @function countDownNow
 * @param object options
 * @param string el
 * @description options.offset is seconds from now, OR options.to is the time to go to (in epoch milliseconds)
 *  el is the element ID prefix all items have (ie. id="livecount_day-A" is livecount)
 */
var countDownNow = function (options, el) {
    var settings = {
        skipWeeks: true
    },
        now = new Date();
    $.extend(settings, options);
    var digitRgx = /(?:(?: ?digit_[0-9]+)|$)/;
    var countTo = (options.offset ? (options.offset * 1000 + now.getTime()) : options.to);
    var last = {
        time: 0,
        w: -1,
        d: -1,
        h: -1,
        m: -1,
        s: -1
    };
    var timerOut;
    var changeCount = function (name, to) {
        var b = to % 10;
        var a = to - b;
        a = a <= 0 ? '0' : ('' + a).charAt(0);
        b = b <= 0 ? '0' : b;
        var elA = $('#' + el + '_' + name + '-A').text(a),
            elB = $('#' + el + '_' + name + '-B').text(b);
        if (elA[0]) elA[0].className = elA[0].className ? elA[0].className.replace(digitRgx, ' digit_' + a) : 'digit_' + a;
        if (elB[0]) elB[0].className = elB[0].className ? elB[0].className.replace(digitRgx, ' digit_' + b) : 'digit_' + b;
    };
    var countDownGo = function () {
        now = new Date();
        var current = {
            time: now.getTime(),
            w: 0,
            d: 0,
            h: 0,
            m: 0,
            s: 0
        };
        var diff = (countTo - current.time) / 1000;
        if (diff <= 0) diff = 0;
        current.w = Math.floor(diff / 604800);
        current.d = Math.floor((settings.skipWeeks ? diff : diff % 604800) / 86400);
        current.h = Math.floor(diff % 86400 / 3600);
        current.m = Math.floor(diff % 3600 / 60);
        current.s = Math.floor(diff % 60);
        if (!settings.skipWeeks && last.w != current.w) changeCount('week', current.w);
        if (last.d != current.d) changeCount('day', current.d);
        if (last.h != current.h) changeCount('hour', current.h);
        if (last.m != current.m) changeCount('minute', current.m);
        if (last.s != current.s) changeCount('second', current.s);
        last = current;
        if (typeof settings.tick == 'function') {
            window.setTimeout(function () {
                settings.tick(diff, current);
            }, 1);
        }
        if (diff) {
            timerOut = window.setTimeout(countDownGo, 1000);
        } else {
            if (typeof settings.complete == 'function') {
                settings.complete();
            }
        }
    };
    $(window).bind('beforeunload.countDownNow', function () {
        countTo = now.getTime();
        window.clearTimeout(timerOut);
    });
    countDownGo();
};
