/* Detect IE */

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
function useIE()
{
  var msg = false;
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 8.0 ) 
      msg = true
    else
      msg = true;
  }
  return msg;
}


/* Audio Controls 
*  Features: play , audio
*/
(function($){
  $.fn.videoCtrls = function(options){
     //debug(this);
        var opts = $.extend({}, $.fn.videoCtrls.defaults, options);
        var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
        var videoObj = $(o.videoElement);
        
        if(videoObj.length){
            if(typeof videoObj.autoplay == 'boolean') { /*console.log(videoObj);*/ } else {
                play(videoObj);
            }
            
            if(typeof videoObj.loop == 'boolean') { loop(videoObj); } else {
                videoObj.bind('ended',function(){this.play();});
            }
            
            $(this).bind("click", function(e){
                e.preventDefault();
                if( o.feature == "play")
                     if( $(this).attr("class") == o.classPlay ) {$(this).attr("class", o.classPause);pause(videoObj);
                     } else {$(this).attr("class", o.classPlay);play(videoObj);}
                if( o.feature == "audio")
                     if( $(this).attr("class") == o.classMuted ) {$(this).attr("class", o.classAudio);mute(videoObj);
                     } else {$(this).attr("class", o.classMuted);sound(videoObj);}          
            });
        }    
           
       
};
    
   function play(video){video.get(0).play()};
   function pause(video){video.get(0).pause()};
   function mute(video){video.attr('muted', true)};
   function sound(video){video.attr('muted', false)};
   function loop(video){ video.attr('loop',true)};

   $.fn.videoCtrls.defaults = {
            classPlay: "playControl",
            classPause: "pauseControl",
            classMuted: "mutedControl",
            classAudio: "audioControl",
            videoElement: ".videoNissan",
            autoplay: true,
            action: 'play'
    }

    //function debug($obj){
    //      if(window.console && window.console.log)
    //      window.console.log('VideoControls selection count:' + $obj.size());
    //};         
}(jQuery));

///* OnError Video Controls */
//function failed(e) {
//   // video playback failed - show a message saying why  --<video onerror="failed(event)" >--
//   switch (e.target.error.code) {
//     case e.target.error.MEDIA_ERR_ABORTED:
//       alert('You aborted the video playback.');
//       break;
//     case e.target.error.MEDIA_ERR_NETWORK:
//       alert('A network error caused the video download to fail part-way.');
//       break;
//     case e.target.error.MEDIA_ERR_DECODE:
//       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
//       break;
//     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
//       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');
//       break;
//     default:
//       alert('An unknown error occurred.');
//       break;
//   }
// }

$(document).ready(function() {
    
    /*******************
     * Menu Vehiculos
     ******************/
    
    /******** var ********/
    var vehiclesSub = $("#vehiclesSubMenuWrapper");
    var currentMenu = 0;
    var currentSub  = $('.modelsList:nth-child(1)');
    var busy = false;
    var slide = true;
    var vehicleViewer = $('#vehiclesViewer');
    var currentVehicule;
    var limit; 
    var url;
    var eVisible = 3;
    
    var submenuDock = false;
    var vehiclesMenu = false;
            
    /******** events ********/
     	
    $(".vehiclesMenu").click(function(){
       	showLiquidMenu("top");
    })
    
                        
    //$("#vehiclesViewer").click(function(e){
    //   	url = url.replace("preview", "");
    //   	window.location = url;            	            	
    //})
         
    $("#right_btn, #left_btn").click(function(e) {
        var pos = 0;
        var eVisible = 3;
        
        if(busy == false ){            		
            limit = currentSub.width() - $("#vehiclesWrapper").width();
            if(e.currentTarget.id == 'left_btn'){
                if(currentSub.position().left > -limit){
                    //$("#debug").html(limit+"  "+currentSub.position().left)
                    restantes= currentSub.position().left + limit;
                    if(restantes < eVisible*140){
                        pos =  -limit; /*currentSub.position().left - restantes*/
                    }else {
                        pos = currentSub.position().left - (eVisible*140);
                    }
                    //console.log('recorrer: '+ restantes );
                }        			
            } else {
                if(currentSub.position().left < 0 ){
                    if(currentSub.position().left <= -140 && currentSub.position().left > (eVisible*-140) ){
                        pos = 0;
                    }else {
                        pos = currentSub.position().left + (eVisible*140);
                    }
                }        				        			
            }
                        
            busy = true;
            currentSub.animate({left: pos} , '500',function(){
                    //console.log('posicion actual'+currentSub.position().left);
                    if(currentSub.position().left < 0) {
                        $('#right_btn').show();
                    }else if (currentSub.position().left == 0) {
                        $('#right_btn').hide();
                    }
                busy = false;
            });
      
            }    
        });

            
    //vehicleViewer.mouseleave(function(){
    //    hideViewer();
    //})         

    $(".modelsList li").click(function(e){
        if(busy == false ){            	
            busy = true;
            url = $(e.target).attr('rel');
                            
            /******* parche ********/
            url = url.replace("preview", "");
            window.location = url;    
            return;
            currentVehicule = $(e.currentTarget)            	
     
            vehiclesSub.css({
                    height: 300            		
            });
                
            if(slide == true){
                var posL = (currentVehicule.position().left)+(currentSub.position().left);
            }else{
                var posL = (currentVehicule.position().left)+(420-currentSub.width());
            }
                
            if(vehiclesSub.position().top+297 > vehiclesSub.parent().height() ){
                var posT = vehiclesSub.position().top-185;
            }else{
                var posT = vehiclesSub.position().top;	            		
            }
                
            vehicleViewer.css({
                left: posL,
                top: posT
            }).fadeIn();
            vehicleViewer.load(url,function(){
            busy = false;     
              })
          }

    })
    /*Selector 2/4 elemento*/
    $("#vehicleMenuElements a.vehicleMenuElement").eq(3).css({'line-height':'20px', 'height': '75px', 'padding-top': '35px'});
    $("#vehicleMenuElements a.vehicleMenuElement").eq(1).css({'line-height':'20px', 'height': '75px', 'padding-top': '35px', 'text-indent':'5px'});
            
                        
    $("#dock_menu li").click(function(e){           	
        showLiquidMenu("dock"); 
        showMenu($('#dock_menu li').index(e.currentTarget)+1);
    })

    $('.vehicleMenuElement').click(function(e){
        $('#right_btn').hide(); 
        showMenu($('.vehicleMenuElement').index(e.currentTarget)+1);
     });
    
    if(useIE() == false){
        $("#vehiclesMenuWrapper").mouseleave(function(){
        hideSubMenu();
        })
    }
    
    
    /******** Show menu/submenu ********/
    
    function showLiquidMenu(e){     
        if(e == "top"){
                if(vehiclesMenu == false){
                        hideLiquidMenu();
                $("#vehiclesMenuWrapper").animate({ 
                                width:'700',
                                height: '470'
                        });   
                vehiclesMenu = true;
                }else{
                        hideVehiclesMenu();         
                        vehiclesMenu = false;
                } 
                
        }else{
                hideLiquidMenu();
                $("#vehiclesMenuWrapper").animate({ 
                        width:'700',
                        height: '465'
                });   
                vehiclesMenu = true;
        }
        
    }
    
    function showMenu(item){
        if(busy == false ){     
            busy = true;
            currentMenu = item;
            $("#vehiclesSubMenuControls").hide();
            $("#vehiclesSubMenuControls").fadeOut(function(){
                    vehicleViewer.fadeOut("normal",function(){
                    vehiclesSub.css({
                    height: 112
                });                 	
                   
                    currentSub.animate({left: 580} ,'500',function(){   
                        vehiclesSub.css("top", ($('#vehicleMenuElements li:nth-child('+item+')').offset().top)-85);
                        vehiclesSub.show();
                        currentSub = $('.modelsList:nth-child('+currentMenu+')');
                            if(currentSub.children().size() <= 3){
                                slide = false;
                                $("#vehiclesWrapper").width(currentSub.children().size()*140);               			 
                            }else{
                                slide =  true;
                                //$("#vehiclesWrapper").width(4*140);
                                $("#vehiclesWrapper").width(3*140);
                                $("#vehiclesSubMenuControls").fadeIn();
                            }
                            currentSub.width(140*currentSub.children().size());
                            currentSub.animate({left: 0} , '500',function(){
                                //if(slide == true){
                                    //$("#vehiclesSubMenuControls").fadeIn();
                                //}
                                busy = false;
                            });
                                                                 
                    });
                        
                });
           });   
        }       	
    }
    
    
    
    
    /******** hide menu/submenu ********/   
   function hideVehiclesMenu(){
        if(vehiclesMenu == true){
                $("#vehiclesMenuWrapper").animate({ 
                        width:'0'
                });
                hideSubMenu();
                vehiclesMenu = false;	
        }
    }

    
    function hideViewer(){	
        if(busy == false ){  
                busy = true;
                vehicleViewer.fadeOut();	            	
                vehiclesSub.css({
                height: 112            		
                });
                busy = false;
        }          	            	
    }          
    
    function hideSubMenu(){
        if(busy == false ){  
                busy = true;
                vehicleViewer.fadeOut("normal",function(){
                vehiclesSub.css({
                    height: 112            		
                });
                
                $("#vehiclesSubMenuControls").fadeOut(function(){
                        currentSub.animate({left: 580} ,'500',function(){ 
                        vehiclesSub.hide();
                        busy = false;	   
                    });     
                }); 
                        
                });	            	
                

        }
    }
    
                /******** END ********/

            
                                    
            /*Liquid Section Menu Bottom*/
             $("#liquidMenu h3").click(function(event){
                event.preventDefault();
                $("#liquidMenu ul ul").animate({
                    height: 'toggle'} , {duration: '600'     
                });
            });
            
            /* Controles de Audio */
             
            $('#togglePlayPause').videoCtrls({feature: "play"});
            $('#toggleMuteAudio').videoCtrls({feature: "audio"});
            
            /* SubmenuToggle */
            
            $('.submenuDock').click(function(){
            	
            	if(submenuDock == false){
                     hideVehiclesMenu();      
                     $('.submenuDock > button').html('&laquo;');
                     $('#submenu, .titleSubmenu, .subtitleSubmenu, .submenuDock, .submenuDock button' ).animate({height: "100px"} , {queue: false, duration: '600'});
                     $('#submenu h2 a, .subtitleSubmenu h3').hide().css( 'lineHeight', '100px' ).show(900);
                     $('.sectionSubmenu').delay(600).show('fast').css('opacity', 0.7);    
                     submenuDock = true;

            	}else{     
            		hideLiquidMenu();
                    submenuDock = false;
            	}
            });
   
            
           function hideLiquidMenu(){
        	   if(submenuDock == true){
                   $('#submenu h2 a, .subtitleSubmenu h3').hide(0).css( 'lineHeight', '32px' ).delay(300).show('slow');
                   $('.submenuDock > button').html('&raquo;');
                   $('.sectionSubmenu').hide('fast').css('opacity', 0);
                   $('#submenu, .titleSubmenu, .subtitleSubmenu, .submenuDock, .submenuDock button' ).delay(300).animate({height: "32px"} , {duration: '600'});   
                   submenuDock = false;
        	   }                  	
            }
            
            /*$('div.vehiclesCarouselWrapper').carousel({ auto: 800, speed: 1000 });*/

});


function request(params){
    // params url:--- , loading:--- , data: ---- , finished: ---- , target: ----
    var response='';
    
    if(params.data==undefined)
        params.data='';

    if(params.loading==undefined)
        params.loading='';

    if(params.target!=undefined)
        $(params.target).html(params.loading);
    
    if(params.async!=undefined)
        params.async=true;
    
    $.ajax({
        url:params.url,
        data:params.data,
        success:function(data, textStatus, jqXHR){
            $(params.target).html(data);

            if(params.finished!=undefined)
                params.finished();
        }
    });

    return response;
}

function cb_alert(params){
    $.colorbox({width:"500px",height:"250px", inline:true, href:"#js_msg"});
}

$(document).ready(function(){
    $('#video_rogue').click(function(){
            $.colorbox({
                    href:_baseUrl+"anuncios/rogue",
                    onComplete:function(){
                            var v = document.getElementsByTagName("video")[0];
                            v.play();
                    }
                });
            return false;
        });
});
