var lockHeaderAction = false;    
var DISCLAIMER_COOKIE = 'dwp_accept_agreement';
var VIEWED_SCENES = 'dwp_viewed_scenes';
var HEADER_VIDEO_VIEWED = 'dwp_video_autoplay';
var tab_timer = '';
var viewedScenes = new Array();  
var videos_playing = false;
                                

$(document).ready(function(){
      
      

     if($.cookie(VIEWED_SCENES)) {
        viewedScenes = $.cookie(VIEWED_SCENES).split(",");                      
     }
     

    //Bind Click on Scenes Browser Tab
        $("ul.scenes_browser_tab li:not(.pagination) a").click(changeTab);
        
    //Bind Click on the Pagination
        $(".pagination a.next, .pagination a.prev").click(changePage);          
       // $(".btn_continueformore").click(changePage);       
        
        $(".page_chooser").change(changePage);                                                              
        $(".page_chooser").keypress(function (e){
              if (e.which == 13)
              {
                 $(this).change();
              }
        });
        
    //Bind Click on the Dynamic Header Buttons
    if($(".dynamic_header").is(".is_dynamic"))
    {      
        $(".nav_part ul a").click(selectTab).focus(selectTab);
        tab_timer =  setTimeout("nextTab()", 7000);
        
        $(".tab_more").hover(function(){
               clearTimeout(tab_timer);
        }, function(){
            
           tab_timer =  setTimeout("nextTab()", 7000);     
        });
    }
        
    $(".btn_agree, .link_agree").click(agreeDisclaimer);
        
    if($(".nav_part li.selected a[@href='home']").size() != 0)
    {
           startHeaderVideo();         
    }
    
    $(".link_overlay").hover(function(){
       $(this).find("a").show();
    }, function(){
         $(this).find("a").hide();
    });
        
});



function showDisclaimer()
{      
    $("#disclaimer_agreement_bg, .disclaimer_agreement").width($("body").width());
    $("#disclaimer_agreement_bg, .disclaimer_agreement").height($("body").height()).show();
    $("#disclaimer_agreement_bg").fadeTo("fast", .9);
    $(".disclaimer_agreement").fadeTo("fast", 1);          
}

function hideDisclaimer()
{   
    $("#disclaimer_agreement_bg, .disclaimer_agreement").width($("body").width());
    $("#disclaimer_agreement_bg, .disclaimer_agreement").height($("body").height());
    $("#disclaimer_agreement_bg").fadeTo("slow", 0, function(){$(this).hide();});
    $(".disclaimer_agreement").fadeTo("slow", 0, function(){$(this).hide();});      
}

function agreeDisclaimer()
{   
    var date = new Date();
    date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
    $.cookie(DISCLAIMER_COOKIE, 'true', { path: '/', expires: date, domain: COOKIE_DOMAIN });

     hideDisclaimer();
     return false;
}


/**                                       
* @desc To the Ajax Request to go fecth Scenes Base on current parameters
*/
function getScenes(type, sort_by, widget, num_per_page, page)
{
     
  //Prepare ajax parameters
      var params = {
        'type' : type, 
        'sort_by' : sort_by,
        'widget' : widget,
        'page' : page,
        'num_per_page' : num_per_page
      };      
  
  //Do the Ajax Request
  $.get(base_url + "?action=ajax/get_scenes", params, function(response){      
    
    //Define a temporary container
        var content_dump = $("#content_dump");
        content_dump.html(response);
          
  
    //Get the info back from the request. 
        tab_request_info =  content_dump.find(".response_info");
        request_info = tab_request_info.metadata();
                                
        
        
        tab_request_info.remove();
     
        
     
    // Bind the new HTML  
        $("#scenes_browser").html(content_dump.html());                       
  
    
    // Dynamise the Widget Received. 
       if(request_info.widget_type == 'scene_normal'){
            dynamiseSceneNormal();
       }
  
       if(request_info.widget_type == 'pornstar'){
            dynamisePornstarWidget();
       }
  
  
    //Update Pagination info
        refreshPaginationRange(request_info.current_page, request_info.num_of_pages);
  
    //Remove the Loader
        showSceneBrowser();      
  });     
    
}


function getRelatedScenes(id)
{
  
 //Prepare ajax parameters
      var params = {
        'id' : id       
      };      
  
  //Do the Ajax Request
   $(".bz_scenes").fadeTo("fast", 0.1, function(){       
         $.get(base_url + "?action=ajax/get_related_bz_scenes", params, function(response){      
      
             if($(".related_bz_scenes").not(":visible")){
                    $(".related_bz_scenes").slideDown();
             }
            $(".bz_scenes").html(response).fadeTo("fast", 1);  
            
                $(".bz_scenes").find(".bz_related_scene_block").hover(function(){
                    var id = $(this).attr("id").replace("scene_", "");         
                    imageInterval = setInterval("swapImage(" + id + ")", 500);
                    $(this).find('.overlay_normal_text').css('color', '#ffde00');
                }, function(){
                    clearInterval(imageInterval);
                    $(this).find('.overlay_normal_text').css('color', 'white');
                }); 
         }); 
  });
}


/**
* @desc Change the scene type currently Browsed  
*/
function changeTab()
{
     /*
    * Fetch Parameters from the Tabs
    */   
        var tab = $(this);
        var strparams = $(this).attr("href").split("param-")[1];
        var params = strparams.split("-");           
    
    /*
    * Adapt Pagination Setting
    */
        refreshPaginationSetting(params);
        
    /*
    * Request Scenes to the Server
    */      
     $(".ajax_loader").height($("#scenes_browser").height()).show().fadeTo("slow", 0.95, function(){
        
         getScenes(params[0], params[1], params[2],  params[3], 1);          
     });    
       
                
    /*
    * Select new Tabs
    */
        $(".scenes_browser_tab li.selected").removeClass("selected");
        $(this).parents("li").addClass("selected");
        
    return false;
}

/**
* @desc Change the offset of the scene type currently Browsed  
*/
function changePage()
{                           
  
    /*
    * Prepare pagination information
    */   
   
    $this = $(this);
    var pagination = $(".pagination_master");         
    var page_chooser = $(".page_chooser");       
    var last_page = parseInt(pagination.find(".last_page").html());    
    var current_page = parseInt($(".pagination_master").find("input[@name='current_page']").val());  
     
    /*
    * Find Requested Page
    */     
    if($this.is(".prev"))
    {
        var requested_page = current_page - 1; 
    }
    else if($this.is(".next") || $(this).is(".btn_continueformore"))          
    {
        var requested_page = current_page + 1;       
    }else if($this.is(".page_chooser")) 
    {      
        var requested_page = parseInt($this.val());    
    } 
    else
    {   
        return false;
    }
    
    /*
    * Look is that page is in the right range
    */  
    if(requested_page >= 1 && requested_page <= last_page)
    {       
            /*
            *  Fetch the Pagination Setting
            */  
                var params = new Array();    
                params[0] = pagination.find("input[@name='type']").val();
                params[1] = pagination.find("input[@name='sort_by']").val();
                params[2] = pagination.find("input[@name='widget']").val();
                params[3] = pagination.find("input[@name='num_per_page']").val();        
            
            /*
            * Request Scenes to the Server
            */            
               $(".ajax_loader").height($("#scenes_browser").height()).show().fadeTo("slow", 0.95, function(){
                        $.scrollTo(".content", 'slow');        
                      getScenes(params[0], params[1], params[2], params[3], requested_page);          
               }); 
    }
    else
    {
        /*
        * Update the page selector
        */  
        if($(this).is(".btn_continueformore"))
        {
             window.location = $(".btn_getmembership").attr("href");
        }
        
        page_chooser.val(current_page);
        return false;
    }  
    return false;
}

function goToNextPage()
{
    alert('allo');
    return false;
}

/**
* @desc Refresh the pagination hidden parameters 
*/
function refreshPaginationSetting(params)
{
    var pagination = $(".pagination_master");
    pagination.find("input[@name='type']").val(params[0]);
    pagination.find("input[@name='sort_by']").val(params[1]);
    pagination.find("input[@name='widget']").val(params[2]);
    pagination.find("input[@name='num_per_page']").val(params[3]);      
}


/**
* @desc Refresh every paginator with new current page and page limit 
*/
function refreshPaginationRange(current, limit)
{   
    var pagination = $(".pagination");
    pagination.find("input[@name='current_page']").val(current);
    pagination.find("input[@name='page_chooser']").val(current);           
    pagination.find(".last_page").html(limit);       
}


               
/**
* @desc Remove the Loading Div
*/
function showSceneBrowser()
{
    $(".ajax_loader").fadeTo("slow", 0.1, function(){$(this).hide();});
}



function nextTab()
{
    
    if(videos_playing == true) return false;
    var num = parseInt($(".nav_part li.selected a").attr("href").split("tab")[1]);    
    var next = num + 1;
    if(next > 5){ next = 1;   }  
   
    $(".nav_part li a[@href='#tab" + next + "']").click();      
  
}

/**
* @desc Function that manipulate the header 
*/       
function selectTab()
{     
    if($(this).parent().hasClass('selected')) return false;
    if(lockHeaderAction == true) return false;
    lockHeaderAction = true;                                  
    
    videos_playing = false;   
    clearTimeout(tab_timer);
    tab_timer = setTimeout("nextTab()", 7000);   
    
    var spot = $("ul.left_part embed").remove();
    
    /*** Change the selected day ***/
    $(".nav_part li").removeClass('selected');
    $(this).parent().addClass('selected');
    var day = parseInt($(this).attr('href').split('tab')[1]);
    

    /*** Change the left image ***/
    $(".left_part li.selected").fadeOut('fast', function(){ $(this).removeClass('selected')});
    $(".left_part li:eq("+ (day - 1) +")").fadeIn('slow', function(){ $(this).addClass('selected')});  
    
    /*** Change the right content ***/
    $(".infos_part div.selected").fadeOut('fast', function(){ $(this).removeClass('selected')});
    $(".infos_part div.tabpanel:eq("+ (day - 1) +")").fadeIn('slow', function(){
    
        $(this).addClass('selected');lockHeaderAction = false;   
        
       //Start the video in the tabs
        if($(this).find("input[@name='video']").size())
        {
        
           var video = $(this).find("input[@name='video']").val(); 
           var spot = $("ul.left_part").find("li:eq(" + (day - 1) + ")"); 
           var img = spot.find("img").attr("src"); 
                            
            if($.cookie(HEADER_VIDEO_VIEWED) == null)
            {
                var auto = 1;
                var date = new Date();
                date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
                $.cookie(HEADER_VIDEO_VIEWED, true, { path: '/', expires: date });    
                          
            }
            else
            {
               var auto = 0;         
            } 
             
            
            
            var xml = base_url + "home_video.xml";      
                                                                                                     
            spot.html("");
         
            spot.flash(
                {
                    src: "http://scripts.brazzers.com/tours/dwp/tour/player/header_player.swf?v=18",
                    width: 640, 
                    height: 360,                       
                    wmode: "transparent",           
                    align: "middlel",
                   
                    allowfullscreen:true,            
                    allowscriptaccess: "always",
                    allownetworkaccess: "always",            
                    flashvars: {
                     options: xml,   
                      autoplay: auto, 
                      volume:0.20                    
                    }                           
                },
                {version:"9.0.115.0"}    
            );           
             
           
        }  
     });    
    
    return false;
}

 
 function videostart(){        
    if($("#player").size() == 0)
    {
       videos_playing = true;    
       clearTimeout(tab_timer);  
    }else{              
        $.get("?action=ajax/increase_view");
    }        
 }   
                               
 function videofinish(){       
    videos_playing = false;
    nextTab();       
    tab_timer =  setInterval("nextTab()", 7000);        
 }
    
 
 
/*
* Swap between 3 images at the interval set on the document ready
*/
function swapImage(id)
{
   
    var obj = $("#scene_"+ id);
    var img = obj.find(".bz_related_scene_img img");
    
    if(!img.data("nb"))
    {
       nb = parseInt(img.attr("alt"));
       img.data("nb", nb).removeAttr("alt");           
    }
    
    var imgNum = parseInt(img.data("nb"));    
    nextimgNum = imgNum + 1;
    nextimgNum %= 5;
    nextimgNum += 1;      
    
    img.data("nb", nextimgNum );     
     
    var src = img.attr("src");   
    var newsrc = src.replace("br" + imgNum, "br" + nextimgNum);    
    img.attr("src", newsrc);
    
}



function addScenesView(id){
   viewedScenes.push(id);     
   var date = new Date();
   date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
   $.cookie(VIEWED_SCENES, viewedScenes.getUniqueValues().join(","), { path: '/', expires: date, domain: COOKIE_DOMAIN});                
}


Array.prototype.getUniqueValues = function () {
    var hash = new Object();
    for (j = 0; j < this.length; j++) {hash[this[j]] = true}
    var array = new Array();
    for (value in hash) {array.push(value)};
    return array;
}

function gotojoin()
{
    window.location = "?action=join";
}

function startHeaderVideo()
{      
       
       spot = $(".left_part li.selected");
        var xml = base_url + "home_video.xml";      
              
          if($.cookie(HEADER_VIDEO_VIEWED) == null)
        {
            var auto = 1;
            var date = new Date();
            date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
            $.cookie(HEADER_VIDEO_VIEWED, true, { path: '/', expires: date });    
                      
        }
        else
        {
           var auto = 0;         
        } 
                   
              
                                                                                                     
            spot.html("");
         
            spot.flash(
                {
                    src: "http://scripts.brazzers.com/tours/dwp/tour/player/header_player.swf?v=18",
                    width: 640, 
                    height: 360,                       
                    wmode: "transparent",           
                    align: "middlel",
                   
                    allowfullscreen:true,            
                    allowscriptaccess: "always",
                    allownetworkaccess: "always",            
                    flashvars: {
                     options: xml,   
                      autoplay: auto, 
                      volume:0.20                    
                    }                           
                },
                {version:"9.0.115.0"}    
            ); 
                
          
}
