$(document).ready(function(){			
 	hoverEffect();
	initializeMedia();
	$('#item2btn').click(function(){
		addMedimFlashMovie('movie2',this.rel,'videocontain');
	});
	$('#item3btn').click(function(){
		addLargeFlashMovie('movie3',this.rel,'videocontain2');
	});
	$('#oa_quantity').focus(function(){
		if(this.value == '1'){
			this.value ='';
		}
	});
	$('#oa_quantity').blur(function(){
		if(this.value == ''){
			this.value ='1';
		}
	});
});
function addMedimFlashMovie(_movieName, _videoSrc,_writePlace){
	var fo = new SWFObject("/flash/general/video_medium.swf",_movieName,"420px", "284px", "9", "#FFFFFF", true);
	fo.addParam("allowScriptAccess", "always");
	fo.addParam("allowFullScreen","true");
	fo.addParam("allowScale", "true");
	fo.addParam("wmode", "opaque");
	fo.addVariable("playSt",_videoSrc);
	fo.write(_writePlace);
}
function addLargeFlashMovie(_movieName, _videoSrc,_writePlace){
    var fo = new SWFObject("/flash/general/video_large.swf", _movieName, "540px", "346px", "9", "#FFFFFF", true);
    fo.addParam("allowScriptAccess", "always");
    fo.addParam("allowFullScreen","true");
    fo.addParam("allowScale", "true");
    fo.addParam("wmode", "opaque");
    fo.addVariable("playSt",_videoSrc);
    fo.write(_writePlace);
}
//Function to Load additional CSS file.
function loadCSS(){
	filename = "/css/hasJS.css";
	var fileref=document.createElement("link");
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("href", filename);
	
	document.getElementsByTagName("head")[0].appendChild(fileref)
}
$(document).ready(function() {loadCSS();});

function hoverEffect()
{
	$("ul.productItemsList li").hover (
		function(){
		   $($(this)).addClass("hoverClass");
		},
		function(){
		   $($(this)).removeClass("hoverClass");
		  }
	)
	$("ul.productItemsList li").click (
		function(){	  
		var link = jQuery("a", this);	
		if(!link.onclick) 
		{
			for(var i=0; i<link.length;i++)
			{
				window.open(link[i].href, link.target || "_self");
			}
		}
	 }
);
}

function initializeMedia()
{
	if($('a.media')>0){
		$('a.media').media();
	}
}

/* JavaScript for scroll Functionality starts here*/

/**  
 * jQuery.ScrollShow - Scrolling Slideshow.
 * Copyright (c) 2007 Ariel Flesler - aflesler(at)gmail(dot)com
 * Licensed under GPL license (http://www.opensource.org/licenses/gpl-license.php).
 * Date: 10/30/2007
 * @author Ariel Flesler
 * @version 0.7
 *
 * @id jQuery.fn.scrollShow
 * @param {Object} settings Hash of settings (detailed below).
 * @return {jQuery} Returns the same jQuery object, for chaining.
 **/
(function( $ ){
	var VISIBLE_ITEMS = 3;
	var defaults = {
		elements:'li',//elements selector (relative to view)
		//itemSize:{	},
		view:null,//container of the elements, the one to fix the width.
		navigators:null,//selector to the elements to navigate the slideshow.
		navigationMode:'s',//sequential, random, localscroll
		speed:300,//speed of transition, 1 for no-animation
		wrappers:'simple',//simple,resize,crop,link
		circular:false,//should the slideshow rewind/advance on the extremes ?.
		easing:'linear',//easing equation
		axis:'x',//axis to displace the slideshow
		margin:true,//take margin in account?
		start:null, //force the scroll to start at some position element.
		setWidth:false//whether to calculate and set, the overall width of the slideshow.
	};
	
	function wrap( $els, type, size ){//wrap the photos with several different wrappers.
		switch( type ){
			//case 'crop': $els = $els.wrap('<div class="jq-ss-crop">').parent().css('overflow','hidden');					
			//case 'resize': return $els.css( size );
			//case 'simple': return $els.wrap('<div class="jq-ss-simple">').parent();
			case 'link': 
				if( $els.is('img') )
					return $els.wrap('<a target="_blank" class="jq-ss-link">').parent().each(function(){
						this.href = this.firstChild.src;
					});
			default: return $els;					
		}
	};
	
	$.fn.scrollShow = function( settings ){
		settings = $.extend( {}, defaults, settings );
		
		return this.each(function(){
			var 
				widget	  = this,
				$view	  = settings.view ? $(settings.view, this) : this,
				$elements = $(settings.elements, $view),
				limit	  = $elements.length,
				active	  = 0;
				
			//$.each( settings.wrappers.split(/\s*,\s*/), function( i, wrapper ){
			//	$elements = wrap( $elements, wrapper, settings.itemSize );													 
			//});			
			//$elements.css( settings.itemSize );//ensure the outer elements have fixed size.
			
			if( !settings.navigators ){//this shouldn't get to happen
				settings.navigators = '';
				settings.navigationMode = 'r';
			}
			
			if( settings.navigators.constructor != Array )
				settings.navigators = [settings.navigators];
			
			$.each( settings.navigationMode.split(''), function( i, type ){
				switch( type.charAt(0) ){
					case 's'://sequential navigation
						$(settings.navigators[i],widget)
							.eq(0).bind('click', { dir: -3 }, sequential ).end()
							.eq(1).bind('click', { dir: +3 }, sequential );
					break;
					case 'r'://random navigation
						var $nav = $(settings.navigators[i] || $elements, widget),
							ratio = $elements.length / $nav.length;
							
						if( ratio === Infinity ) return;//no navigator found
						$nav.each(function( pos ){											   
							$("a.link", this).bind( 'click', { pos: Math.floor(ratio*pos) }, openDiv );							
						});
					break;
				}
			});				

			(function( $e, w ){					  
				var imgw = ($e.width() + attrs('margin') + attrs('padding') + attr('border'));
				
				do w -= imgw;
				while( w > 0 && limit-- );//find the last element we can scroll To.
				
				if( !settings.setWidth ) return;
				
				do{
					$e = $e.parent();
					if( $e[0] == $view[0] )
						return;
				}while( $e.length > 1 );
				$e.width( imgw * $elements.length  );//if there's a container for the elements, calculate it's width.
				
			})( $elements, $view.width() );

			if( settings.start != null )
				random( settings.start );
			
			function attrs( name ){
				return attr(name+'Left') + attr(name+'Right');
			};
			function attr( name ){
				return parseInt($elements.css(name)) || 0;	
			};
			
			function sequential( event ){
				event.data.pos = active + event.data.dir;				
				return random( event );
			};
			
			$(function()
			{
				$("#close").click(function()
					{
						limit = limit-VISIBLE_ITEMS;
					$(".media").remove();
					$(".image").remove();
					$("#details").hide();				

					if(active%VISIBLE_ITEMS == 1)
						random( active-1 )					
			  		else if (active%VISIBLE_ITEMS == 2)
					random( active-2 )
					else					
					random( active )
					
					return false;
       		 		});
			});
			
			function openDiv(event){
				var pos = typeof event == 'number' ? event : event.data.pos;				
				limit = limit+VISIBLE_ITEMS;
				random(event);
				if($(".link")[pos].title=="watch")
				{	
					$("#details").append("<a href="+"#"+" class="+"media"+"></a>");
					$(".media")[0].href = $(".link")[pos].href;						
					$('a.media').media();
				}				
				else if($(".link")[pos].title=="view")
				{
					$("#details").append("<img src alt class="+"image"+">");
					$("#details img")[0].src = $(".link")[pos].href;
				}
				$("#details").fadeIn("slow");
				$("#left").hide("slow");
				return false;
				
			}
			
			function random( event ){
				var pos = typeof event == 'number' ? event : event.data.pos;

				if( pos < 0 )
					pos = active == 0 && settings.circular ? limit : 0;
				else if(pos >= limit)	{
					pos = active == limit && settings.circular ? 0 : limit;	
					$("#right").hide("slow");
				} else
					$("#right").show("slow");

				if(pos==0)
					$("#left").hide("slow");
				else
					$("#left").show();
				$view.stop().scrollTo( $elements[pos], settings );
				active = pos;				
				return false;
			};				
		});
	};
		  
})( jQuery );

/* JavaScript for scroll Functionality ends here*/

/* Javascript for tool tip starts*/

function showToolTip(e, _tip, _tipcontent){	
	$("#"+ _tip).css({'display':'block','position':'absolute'});
	var pos = $(e.target).offset();  
	$("#"+ _tip).css({'left':  (pos.left-20) + 'px'});
	$("#"+ _tip).css({'top':( pos.top - $("#"+ _tip).height() )  + 'px'});
	
}	
	

function hideToolTip(_item)
{
	$(_item).hide();	
}
/* Javascript for tool tip ends*/

/* JavaScript for 1 by 1 scroll  starts*/
	jQuery.fn.accessNews = function(settings) {
    settings = jQuery.extend({       
        newsSpeed: "normal"
    }, settings);
    return this.each(function(i) {
        aBlogsSlider.itemWidth = parseInt(jQuery(".item:eq(" + i + ")",".blogs_slider").css("width")) + parseInt(jQuery(".item:eq(" + i + ")",".blogs_slider").css("margin-right"));
        aBlogsSlider.init(settings,this);       
    });
};
var aBlogsSlider = {
    itemWidth: 0,
    init: function(s,p) {
        itemLength = jQuery(".item",p).length;
        newsContainerWidth = itemLength * aBlogsSlider.itemWidth;
        jQuery(".postContainer",p).css("width",newsContainerWidth + "px");
        jQuery(".next",p).css("display","block");
        animating = false;
        jQuery(".next",p).click(function() {
            if (animating == false) {
                animating = true;
				
                animateLeft = parseInt(jQuery(".postContainer",p).css("left")) - (aBlogsSlider.itemWidth * 1);
                if (animateLeft + parseInt(jQuery(".postContainer",p).css("width")) > 0) {
                    jQuery(".prev",p).css("display","block");
                    jQuery(".postContainer",p).animate({left: animateLeft}, s.newsSpeed, function() {
                        jQuery(this).css("left",animateLeft);
						var containerLeft = parseInt(jQuery(".postContainer",p).css("left"));
						var containerWidth = parseInt(jQuery(".postContainer",p).css("left"));
                        if((containerLeft + containerWidth) <= (aBlogsSlider.itemWidth * 2)) {
                            jQuery(".next",p).css("display","none");
                        }
                        animating = false;
                    });
                } else {
                    animating = false;
                }
            }
            return false;
        });
        jQuery(".prev",p).click(function() {
            if (animating == false) {
                animating = true;
                animateLeft = parseInt(jQuery(".postContainer",p).css("left")) + (aBlogsSlider.itemWidth * 1);
                if ((animateLeft + parseInt(jQuery(".postContainer",p).css("width"))) <= parseInt(jQuery(".postContainer",p).css("width"))) {
                    jQuery(".next",p).css("display","block");
                    jQuery(".postContainer",p).animate({left: animateLeft}, s.newsSpeed, function() {
                        jQuery(this).css("left",animateLeft);
                        if (parseInt(jQuery(".postContainer",p).css("left")) == 0) {
                            jQuery(".prev",p).css("display","none");
                        }
                        animating = false;
                    });
                } else {
                    animating = false;
                }
            }
            return false;
        });
    }
};

 
function addToCart() {
  var items = arguments;
  for(var i = 0; i < items.length; i++) {
    if( items[i] == "01217"){
      items[i] = "01211";
    }
    if( items[i] == "01218"){
      items[i] = "01212";
    }
    if( items[i] == "01219"){
      items[i] = "01213";
    }
    if( items[i] == "01220"){
      items[i] = "01214";
    }
    if( items[i] == "01221"){
      items[i] = "01215";
    }
    if( items[i] == "01222"){
      items[i] = "01216";
    }
    var data = {
      oa : 'AddItem',
      oa_id : items[i],
      oa_quantity : '1',
      ua : '',
      wl_action : ''
    };
    data.oa_attributes = [];
    data.oa_attributes[1] = 'Large+Bottle';
    data.oa_attributes[2] = 'Large+Bottle';
    data.oa_attributes[3] = 'Large+Bottle';
    data.oa_attributes[4] = 'Large+Bottle';
    data.oa_attributes[5] = 'Large+Bottle';
    data.oa_attributes[6] = 'Large+Bottle';
    analytics('/diagnostic_tool/add/' + items[i]);
    $.ajax({
        type: "POST",
        url: "/buy/index.php?", 
        data: data, 
        success: function(data){
            location.href = '/buy/index.php?p=cart';
        }
    });
  }
}
 
function initializeProductForm() {
  $("#productForm").submit(function(){
    $.ajax({
       type: "POST",
       url: "/buy/index.php?",
       data: $(this).serialize(),
       success: function(msg) {
        location.href = 'https://livingproof.com/buy/index.php?p=cart';
       }
     });
 
    return false;
  });
}


// email share functionality. --@marram
/**
 * Sends the email share form ajaxly.
 * 
 * @param: url: the URL of the service.
 */
function email_share(url){
  var form = $('#email_share_form');
  $('#form_spinner').show();
  $.post(url, {email: $('#email').val(), message: $('#message').val(), senderEmail: $('#senderEmail').val(), senderName: $('#senderName').val(), productId: $('#productId').val()}, function(transport){
      $('#form_spinner').hide();
      analytics('/email/share/'+$('#productId').val()+'/'+$('#email').val().split(',').length);
      //Show the success message.
      $('#email_share_inside').hide();
      $('#email_share_success').show();
  });
};

function email_share_promo(url, promo){
  var form = $('#email_share_form');
  $('#form_spinner').show();
  $.post(url, {email: $('#email').val(), message: $('#message').val(), senderEmail: $('#senderEmail').val(),
	senderName: $('#senderName').val(), productId: $('#productId').val(), promo: promo}, function(transport){
      pageTracker._trackEvent('Email a Friend', 'Order Complete', 'Free Hold');
      $('#form_spinner').hide();
      // analytics('/email/share/'+$('#productId').val()+'/'+$('#email').val().split(',').length);
      //Show the success message.
      // $('#email_share_inside').hide();
      $('#sent').slideDown('fast');
	  
  });
};


/**
 * Resets the email_share UI, and closes it.
 */
function email_share_reset(){
    // close
    tb_remove();
    // add a delay for the ui reset because of the fade-out animation in thickbox.
    setTimeout(function(){
        // reset
        $('#email_share_success').hide();
        $('#email_share_inside').show();        
    }, 1000)
};
/**
 * @param name: The user's name.
 * @param email: The user's email.
 * @successElement: The element to toggle after submitting to the server.
 */
function outOfStockSignup(name, email, successElement){
    return whatscomingSignup(name, email, successElement);
    /*successElement.show();
    var nameSplit = name.split(' ');
    var fname = nameSplit[0];
    var lname = nameSplit.slice(1).join(' ');
    $.post('/_inc/save_email.php', {'fname': fname, 'lname': lname, 'email': email, 'hear': 'other'});
    */
};

/**
 * @param name: The user's name.
 * @param email: The user's email.
 * @successElement: The element to toggle after submitting to the server.
 */
function whatscomingSignup(name, email, successElement){
    successElement.show();
    $.post('/_inc/upcoming_signup.php', {'name': name, 'email': email});
};