var lang = '';
var activeImageSet = '';
var imageSets = '';

if (typeof NATS_CODE == 'undefined')
	NATS_CODE = null;
if (typeof CURRENT_NATS == 'undefined')
	CURRENT_NATS = null;

$(document).ready(function(){

	$("span:contains('Members')").click(function(){AddClickTaleTag("visit_login_page");});
	$("a[rel='nofollow']").click(function(){AddClickTaleTag("visit_join_page");});

    // Fix for IPAD top bar width
    var isiPad       = navigator.userAgent.match(/iPad/i) != null;
    if (isiPad) {
        $('.bz_bar').css('width','1003px') ;
    }

	// Live Promo Functionality
	//$(".promo_player").html('<img src="http://scripts.brazzers.com/tours/bzn/tour3/images/live/live9/live_january13_join.jpg?v=1').hide();

	//$(".promo_extended").click(function(){window.location = "?action=join";});
	$('.specialbanner').click(function(event) {

        var isShown = $('a.promo_close:visible').size();
		if (isShown === 1) {
			$('div.promo_extended').show().animate({marginLeft:'728px', width:'0'}, 1000, function () {
				$('a.promo_close').hide();
                $('#promo_player').replaceWith('<div id="promo_player"></div>');
			});
		} else {
			$('div.promo_extended').show().animate({marginLeft:'0px', width:'732px'}, 1000, function () {
				$('a.promo_close').show();

                //if (typeof bzl_liveshow !== 'undefined' && parseInt(bzl_liveshow) > 0){
                 //   play_secure_stream('643');
                //} else {
                    getTrailer();
                //}

			});
		}
		event.preventDefault();
	});

	$('a.promo_close').click(function(event){
		$(this).hide();
		$('.promo_extended').animate({marginLeft: '900px', width: '5px'}, 1000, function(){
			$(this).hide();
		});

        var expiry = new Date();
        expiry.setTime(expiry.getTime() + (180 * 60 * 1000));
        $.cookie('live_' + bzl_config.upcoming_show.number + '_promo', "true", { path: '/', expires: expiry });

		event.preventDefault();
	});


	/**
	*
	*  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 = {};
	}
	else if(typeof bzl_config.status_bar_date != 'undefined' && bzl_config.status_bar_date != '')
	{
        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') ;
				}
			}
        }
	}


	lang = $("body").attr("id");
	$("a.restricted").click(showNotification);
	$("a.notif_back").click(closeNotification);

	$("#comments .pagination a").attr("href", $("a.join_url").attr("href"));

	/*
	  SELECT IN THE PORNSTAR WIDGET
	*/
	$("select#all_pornstars").change(function(){
		var id = $(this).val().split("_")[1];
		window.location = "index.php?action=pornstar_inside&pornstar_id=" + id ;
	});


	/*
	SELECT IN THE CATEGORIES WIDGET
	*/
	$("select#categories").change(function(){
		var cat = $(this).val();
		window.location = "index.php?action=all-our-scenes-by-category&category=" + cat;
	});

	$(".custom_selector ul.options").mouseout(function(){
		 var custom_selector  = $(this).parents(".custom_selector");
		 custom_selector_hover = setTimeout("$('#" + custom_selector.attr("id") + " .head').click();",1000);
	});

	$(".custom_selector ul.options").mouseover(function(){
		clearTimeout(custom_selector_hover);
	});


	$(".letter a").click(function(){
		 var letter = $(this).attr("href").replace("#", "");
		 $("#letter").val(letter);

		 if($("#do_search").size()){
			 $("#do_search").submit();
		 }else{
			  window.location = "index.php?action=all-our-pornstars&letter=" + letter;
		 }
		 return false;
	});


	$("div.language_chooser a.selected").click(function(){
		$(this).parents("div.language_chooser").find("div.language_choice").slideToggle();
		return false;
	});

	$("div.language_chooser div.language_choice a").click(function(){
		var qstring=document.location.href.split("#")[0].split('?')[1];

		var url = window.location.href

		var current_lang = $("body").attr("id");
		var lang = $(this).attr("href").split("#lang_")[1];
		loc = url.replace(current_lang + ".", lang + ".");
		loc = loc.replace("www.", lang + ".");

		/*
			Debug Mode
			console.log(url);
			console.log("replace " + current_lang + ". by " + lang + ".");
			console.log("replace www. by " + lang + ".");
			console.log(loc);
		*/

		 window.location = loc;
		return false;
	});

	// Find current NATS code from cookie
	if (typeof CURRENT_NATS != 'string')
		CURRENT_NATS = $.cookie('nats');

	// Make sure both are set
	if ((typeof NATS_CODE != 'string' || !NATS_CODE.length) && (typeof CURRENT_NATS == 'string' && CURRENT_NATS.length))
		NATS_CODE = CURRENT_NATS;
	else if (typeof NATS_CODE == 'string' && NATS_CODE.length)
		CURRENT_NATS = NATS_CODE;
	else
		NATS_CODE = CURRENT_NATS = null;

	// Add NATS codes to all links on BZN
	if (g_SITE_ID && g_SITE_ID == 49)
		window.setTimeout(append_nats_code, 150);



});


//Player Live promo stop callback
function playerEventStop()
{
	$("a.promo_close").click();
}


/**
 * @function append_nats_code
 * @description Appends NATS code to all links on the page
 * @param jQuery
 */
function append_nats_code(applyTo) {
	if (typeof applyTo != 'object' || !applyTo.find)
		applyTo = $(document);

	if (typeof NATS_CODE == 'string') {
		var href, el,
		NATSRgx = /[\?&]{1}nats=/,
		ActionRgx = /[\?&[1]action=/;
		applyTo.find('a').each(function(){
		el = $(this);
		href = el.attr("href");
		if (typeof href == 'string' && !NATSRgx.test(href) && ActionRgx.test(href)) {
			if (href.indexOf('?') > -1)
				el.attr("href", href + "&nats=" + NATS_CODE);
			else
				el.attr("href", href + "?nats=" + NATS_CODE);
			}
		});
	}
}

function showNotification()
{
   var info = $(this).attr("href").replace("#", "").split("-");

   var notification = $("#" + info[0]);
   notification.find("li").removeClass("active");
   notification.find("li#notif_" + info[1]).addClass("active");
   notification.fadeIn("slow");

   return false;
}

function closeNotification()
{
	$(this).parents(".notification").fadeOut("slow");
	return false;
}


function gotojoin()
{
   window.location = "index.php?action=join" + (NATS_CODE ? '&nats=' + NATS_CODE : '');
}


function lowBW()
{
	$(".lowbw").fadeIn();
}

function Headinator2(bannerId, headObj, imageSet)
{
	imageSet = imageSet || "head_left";
//if(typeof(console) != 'undefined') console.log(headObj);
	if (!headObj || !headObj.headers)
		return false;

	var dis = this;
	this.active = -1;
	this.images = headObj.headers[imageSet] || headObj.headers;
	this.basepath = headObj.basepath;
	this.banner = $(bannerId);
	this.hasLink = this.banner[0].tagName.toLowerCase() == 'a';
	this.timeOut = false;
	this.mouseIn = false;

	this.imgLoader = $(document.createElement('img'));

	this.loadImage = function(id) {
		clearTimeout(this.timeOut);
		if (this.active == id) return;
		this.active = id;
		this.loading.show();
		this.popIn();
		this.listWrapper.children('.active').removeClass('active');
		this.listWrapper.children(':eq('+id+')').addClass('active');
		this.imgLoader[0].onload = (function(id) {
			return function() { dis.loadImageNow(id); };
		})(id);
		this.imgLoader[0].src = dis.basepath + this.images[id].id;
	};
	this.loadImageNow = function(id) {
		var nextId = id+1;
		if (id >= this.images.length-1)
			nextId = 0;

		var natsTest = /(\?|&)nats=/;
		if (this.hasLink)
			this.banner.attr('href', (
				!this.images[id].url ? '#' : this.images[id].url + (
					g_SITE_ID == 49 && NATS_CODE ? ((
						!natsTest.test(this.images[id].url) &&
						(this.images[id].url.indexOf('http') == -1 ||
						this.images[id].url.indexOf('brazzersnetwork.com') > 0) &&
						this.images[id].url.indexOf('#') == -1
					) ? (this.images[id].url.indexOf('?') > -1 ? '&' : '?') + 'nats=' + NATS_CODE : '') : ''
				)
			));
		this.banner.css({ backgroundImage: 'url('+ dis.basepath + this.images[id].id +')' });
		this.loading.hide();
		this.popTime = setTimeout(this.popOut, 2500);
		var cycle = (function(nextId) { return function() { dis.loadImage(nextId); } })(nextId);
		function scheduleCycle(delay) {
			return setTimeout(function() {
				if(!dis.contextual.hovered) {
					cycle();
				}
				else {
					scheduleCycle(delay / 2);
				}
			}, delay);
		}
		this.timeOut = scheduleCycle(10000);
		this.contextual.find("h2").text(this.images[id].title);
		this.contextual.find("p").text(this.images[id].description);
		this.contextual.find("a.watchMoreNow").attr("href", this.images[id].url);
	};
	this.popOut = function() {
		clearTimeout(this.popTime);
		if (dis.mouseIn) return;

		if(dis.contextual.hasClass("collapsed")) {
			dis.contextual.addClass("expanding");
			dis.contextual.stop().animate({
				height: 78,
				duration: 500
			}, function() {
				dis.contextual.removeClass("collapsed");
				dis.contextual.removeClass("expanding");
			});
		}

		dis.listWrapper.parent().stop().animate({ bottom: (dis.listWrapper.parent().height() * -1), duration: 500 });
	};
	this.popIn = function() {
		clearTimeout(this.popTime);

		if(!dis.contextual.hasClass("collapsed")) {
			dis.contextual.addClass("expanding");
			dis.contextual.stop().animate({
				height: 21,
				duration: 500
			}, function() {
				dis.contextual.addClass("collapsed");
				dis.contextual.removeClass("expanding");
			});
		}

		dis.listWrapper.parent().stop().animate({ bottom: 0, duration: 500 });
	};

	this.loading = $(document.createElement('div')).attr('class', 'banner_loading').appendTo(this.banner).hide().show();
	this.listWrapper = $(document.createElement('ul')).attr('class', 'bannerList').appendTo($(document.createElement('div')).attr('class', 'bannerListWrap').css({ bottom: 0 }).appendTo(this.banner));
	$(document.createElement('div')).attr('class', 'bannerInner').appendTo('.bannerListWrap');
	this.contextual = $(document.createElement("div")).attr("class", "contextual collapsed").insertBefore(this.listWrapper.parent());
	this.contextual.html('<div class="content">'
		+ '<div class="veil"><!-- ie6 --></div>'
		+ '<h2></h2>'
		+ '<p class="description collapsed"></p>'
		+ '<a href="javascript://" class="watchMoreNow collapsed"><!-- Watch More Now --></a>'
		+ '</div>');

	var cloneLI = document.createElement('li'), cloneIMG = document.createElement('img');
// :TODO: put a limit of 6 and randomly select the ones that are displayed
	for (var i = 0; this.images[i]; i++) {
		$(cloneIMG.cloneNode(false)).attr('src', dis.basepath + this.images[i].thumb).appendTo($(cloneLI.cloneNode(false)).appendTo(this.listWrapper)).click((function(eId) {
			return function() { dis.loadImage(eId); return false; };
		})(i));
	}

	this.listWrapper.css({ width: this.listWrapper.children(':first').innerWidth() * this.images.length });

	this.contextual.mouseenter(function() {
		dis.contextual.hovered = true;
		dis.mouseIn = false;
		dis.popOut();
	});
	this.contextual.mouseleave(function() { dis.contextual.hovered = false; });
	this.banner.mouseenter(function() {
		setTimeout(function() {
			if(!dis.contextual.hovered) {
				dis.mouseIn = true;
				dis.popIn();
			}
		}, 500);
	});
	this.banner.mouseleave(function() { dis.mouseIn = false; dis.popTime = setTimeout(dis.popOut, 1000); });
	setTimeout(function(){dis.loadImage(Math.floor(Math.random() * (dis.images.length-0.001)));}, 500);

	return this;
}

function getTrailer(){
	var flashvars = {src: 'http://http.trailers.brazzerscontent.com/brazzerslive/bzlive_promo_trailer/vids/hd-trailers/bzl_bzlive_promo_trailer_480p_2000.mp4',autostart: 'true',bgColor: '000000',themeColor: '000000',mode: 'overlay',scaleMode: 'stretch',frameColor: '000000',fontColor: '000000',link: '',embed: ''},
	params = {
		menu: 'false',
		allowfullfcreen: 'true',
		allowscriptaccess: 'always',
		wmode: 'opaque'
	},
	attributes = {};
	rand = Math.round(Math.random() * 1000);
	swfobject.embedSWF("../cdn/tour3/player/bz_mini_player.swf?v=" + rand, "promo_player", "421", "238", "10.0.12", false, flashvars, params, attributes);
}

/**
*
*  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);

            if (!$.cookie('live_' + bzl_config.upcoming_show.number + '_promo'))
            {
                $('.specialbanner').click();
                //play_secure_stream('643');
            }

			$('#bz_statusbar_countdown').countdown('change', {
				until: bzl_liveshow, onExpiry: exp_status_preshow
			});

		break;

		case 'liveshow':
			status_light('on', period);

            if (!$.cookie('live_' + bzl_config.upcoming_show.number + '_promo'))
            {
                $('.specialbanner').click();
                getTrailer();
            }

			$('#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 Status 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 can call a parametered function
*
**/
function exp_status_before_start() {
	liveStatus('chat');
}
function exp_status_chat() {
	liveStatus('preshow');
}
function exp_status_preshow() {
	liveStatus('liveshow');
}
function exp_status_liveshow() {
	liveStatus('replay');
}

function AddClickTaleTag(Tag)
{
   if (window.ClickTaleTag)  ClickTaleTag(Tag);
}

function staticHeader(index, imageSet, prefix, suffix)
{

    // If there is more than 1 item in the set, break it down.
    if (imageSet.length > 1) {
        randomScene = Math.floor(Math.random() * imageSet.length);
        imageSet = imageSet[randomScene]
    } else {
        imageSet = imageSet[0]
    }

    // If there is more than 1 image in the set
    if (typeof imageSet[1] !== 'string') {
        randomImage = Math.floor(Math.random() * imageSet[1].length);
        imageSet[1] = imageSet[1][randomImage]
    }

    var title   = imageSet[0],
        image   = imageSet[1],
        sceneId = imageSet[1].match(/[0-9]*/),
        url     = "?action=scene&tab=trailer&id=" + sceneId,
        banner = document.getElementById("top-banner");

    prefix = typeof prefix == 'string' || !isNaN(prefix) ? prefix : 'http://i0.bzpics.com/header/727x378/';
    suffix = typeof suffix == 'string' || !isNaN(suffix) ? suffix : '.jpg';

    banner.style.display = 'block';
    banner.style.background = 'transparent url("'+ prefix + image + suffix +'") no-repeat  ';
    banner.href = url;

    /* // why would you want to cut down the names mikessss...
    if (model && model.length > 20) {
        model = model.split(",")[0];
        model = model.split("&")[0];
        model = model.split("and")[0];
    }
    */

    banner.innerHTML = '<a class="header_title">'
        + (index ? '<span class="header_title_name">' + index + '</span>' : '')
        + (title ? '<span class="header_title_description">' + title + '</span>' : '')
        + '</a>';

    banner.onclick = function (){
        _gaq.push(['_trackEvent', 'header_click', sceneId, url]);
        setTimeout(function () {
            window.location =  url;
        }, 250);
    }

    /*
    var images = imageSet,
        id = Math.floor(Math.random() * images.length),
        cimage = images[id],
        url =  cimage.url || "?action=scene&tab=trailer&id=" + cimage.scene_id,
        banner = document.getElementById("top-banner");

    prefix = typeof prefix == 'string' || !isNaN(prefix) ? prefix : '';
    suffix = typeof suffix == 'string' || !isNaN(suffix) ? suffix : '';

    banner.style.display = 'block';
    banner.style.background = 'transparent url("'+ prefix + cimage.image + suffix +'") no-repeat  ';
    banner.href = url;

    if (cimage.title && cimage.title.length > 20) {
        cimage.title = cimage.title.split(",")[0];
        cimage.title = cimage.title.split("&")[0];
        cimage.title = cimage.title.split("and")[0];
    }

    banner.innerHTML = '<a class="header_title">'
        + (cimage.title ? '<span class="header_title_name">' + cimage.title + '</span>' : '')
        + (cimage.description ? '<span class="header_title_description">' + cimage.description + '</span>' : '')
        + '</a>';

    banner.onclick = function (){
        _gaq.push(['_trackEvent', 'header_click', cimage.scene_id, cimage.url]);
        setTimeout(function () {
            window.location =  url;
        }, 250);
    }*/
}


var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

    var t = typeof (obj);
    if (t != "object" || obj === null) {

        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);

    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);

        for (n in obj) {
            v = obj[n]; t = typeof(v);

            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);

            json.push((arr ? "" : '"' + n + '":') + String(v));
        }

        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};


// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
    if (str === "") str = '""';
    eval("var p=" + str + ";");
    return p;
};

