$(document).ready(function(){

	/* SidebarLink Check for contact us link --> redirect to popup form (using existing optInLock code) */
	var skip = 'no'; // Default set no. Skip yes generally for sidebarLink content popup form.
	var sidebarLink = $(".call_action").attr('href');
	var sidebarAlt = $(".call_action img").attr('alt');
	if (sidebarLink == '/page/1/contact-us.jsp' || sidebarLink == '/page/contact-us.jsp') { // looks for contact us page link!
		sidebarLink = window.location.href;
		$(".call_action").attr('href',sidebarLink); // resets link to current page
		$(".call_action").wrap('<span class="optInLock sidebarContact" />');
		console.log('Sidebar heads to contact us page! '+sidebarAlt);
	}
	
	// Updating the documentation site with a popup!
	// using the existing overlay (if all works out!)
	$(".full img").each(function(i) {
		// Resize the image to the max width //
		var i = i + 1;
		var thisWidth = $(this).attr("width");
		var thisHeight = $(this).attr("height");
		var thisSrc = $(this).attr("src");
		var thisRel = "enlarge" + i;
		var newHeight = parseInt(thisHeight * 700 / thisWidth); // "Make it fit" height
	  $(this).attr({"width":"700","height":newHeight,"rel":thisRel,"title":"Click for larger view!"}).wrap("<a href='' rel='#enlarge"+ i +"' />");
	  $(this).parents("span").addClass("pop doc").removeClass("full");
	  $("div#wrap").append("<div id='"+ thisRel +"' class='enlarged_image'><img src='"+ thisSrc +"' width='"+ thisWidth +"' /></div>");
	});
	
	
	// Helping George H with the behavior of the tabs... 
	// He wants the tab to open, but the visitor to be at the top of the page.
	var pageHash = window.location.hash;
			
	if (pageHash == '#tech' || pageHash == '#tab2' || pageHash == '#tab3' || pageHash == '#tab4') {
		$( 'html, body' ).animate( { scrollTop: 0 }, 'slow' );
	}
	
	// call tabs when bizTechTabs class is present
	
  if ($('.bizTechTabs').length >= 1 || $('.contactStartTabs').length >= 1 || $('.fourTabs').length >= 1) {
	  
	  $("#callout").tabs();
		
		// update contact us footer - depending upon tab you are on
		
		$("#contactTab").click(function() {
			$("#contact_footer").html("<p>*Required Fields</p>");
		});
		
		$("#startTab").click(function() {
			$("#contact_footer").html("<p>&nbsp;</p>");
		});
			  
	}
	
	
	if ($.browser.msie && $.browser.version=="6.0") {
	
		// Need to adjust to measure the tabs - and subtract the closed/hidden one from the page. (on open, the tech tab)
		
		// scripting to auto-detect the footer padding-bottom and parse it w/o px 
	  
	  // $("div#content").css("padding-bottom", pb+'px' );
		
		popIt();
		
		$("ul.ui-tabs-nav li a").click(popIt);
		
		function popIt(){
		 
		 	var pb = parseInt($("div#content").css("padding-bottom"));
		 	
	    // was height auto, but testing this out as a reset
	    // $("div#content").height('auto !important');
			
			$("div#content").css({"height":"auto"});
			
	    setTimeout(function() { 
	    // now do the math to solidly set heights for content
	    var fh = $(document).height();
	    var hsub = fh - pb;  /* pb (429) is the current content padding-bottom used to keep footer down. */
	    $("div#content").attr("rel", pb); /* just a test to check parseInt(); */
			// $("div#content").height(hsub+'px');
			$("div#content").css("height",hsub+"px");
			
			// testing to see if reinforcing this helps keep that pesky footer down there.
			// $("footer").css("bottom","0");
			// $("footer").css("position","absolute");
			}, 500); 
			
	  }
	  
	}
	
	
	/***********************************************
	*  optInLock Script Update
	*  check for optIn - if no contact info grab
	************************************************/
	
	// Function to set cookie 
  // vlt_Set_Cookie('vlt_optIn', 'true', '1000', '/', '', '');
	function vlt_Set_Cookie ( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires ) {
      expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
  }

	// Function to get cookie //
  function vlt_Get_Cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
      // now we'll split apart each name=value pair
      a_temp_cookie = a_all_cookies[i].split( '=' );

      // and trim left/right whitespace while we're at it
      cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

      // if the extracted name matches passed check_name
      if ( cookie_name == check_name )
      {
        b_cookie_found = true;
        // we need to handle case where cookie has no value but exists (no = sign, that is):
        if ( a_temp_cookie.length > 1 )
        {
          cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
        }
        // note that in cases where cookie is initialized but no value, null is returned
        return cookie_value;
        break;
      }
      a_temp_cookie = null;
      cookie_name = '';
    }
    if ( !b_cookie_found )
    {
      return null;
    }
  }
	
	// Locked Video Unlocker (and more!) //
	function unlockLockedVideos() {
		$(".optInLock a").each(function(m){
      
      if ($(this).hasClass('call_action')) { // for sidebar cta's!
      	return;
      }
      
      else {
      	
      	$(this).parents().removeClass('optInLock');
      	
      	var className = $(this).attr('class');
	      // alert("div."+className);
	      var linkHref = $("div."+ className +" a").attr('href');
	      $("div."+ className).remove();
	      // alert(linkHref);
	      $(this).attr('href',linkHref);
	      
	      // $("."+ className).removeAttr('class');
	      $("."+ className).removeClass(className);
	      
      }
      
		});
		return;
	}
	
	// Find all the locks! //
	$(".optInLock a").each(function(m){
		
		if ($(this).parents().hasClass('sidebarContact')) {
      var skip = 'yes';
    }
		
		if (vlt_Get_Cookie('vlt_optIn') && skip != 'yes') { // if cookies, unlock and let them rip!
			$(this).parents().removeClass('optInLock');
		}
		else {
			var link = $(this).attr('href');
			$(this).attr('href','');
			$('body').append('<div class="funkyNum_'+ m +' hidden"><a href="'+ link +'">Link!</a></div>');
			$(this).addClass('funkyNum_'+ m);
			// $(this).attr('rel',link);
		}	
	});
	
  // Video popup calls //
  $(".video a , .document a, .externalVid a, .sidebarContact a").click(function(){
  	
   	// var reSource = mediaUrl;
  	// this class but for the lower div anchor ;)
  	
  	$("body").append('<div id="optedIn"></div>');
  	
	  var picked = $(this).addClass('optInPicked');
  	
  	if ($(this).parents().hasClass('optInLock')) {
  		
  		if ($(this).parents().hasClass('sidebarContact')) {
        var skip = 'yes';
      }
  		
			if (vlt_Get_Cookie('vlt_optIn') && skip != 'yes') { // This is superceded by the above "Find all the locks!"
      	// show download link
        console.log('you have the cookie');
        return;
      }
      else {
        // show sign in/up popup link
			  	
			  	var pickedOne = $(this).removeClass('optInPicked').attr('class');
			  	$(pickedOne).addClass('optInPicked');
			  	pickedUrl = $("div."+pickedOne+" a").attr('href'); // set global - no var
			  	
			  	if ($(this).parents().hasClass('document')) { 
			  		tb_show("","/page/1/opt-in-document.jsp?pickedUrl="+pickedUrl+"&KeepThis=true&width=460&height=402");
			  	}
			  	else if ($(this).parents().hasClass('externalVid')) {
			  		tb_show("","/page/1/opt-in-video.jsp?pickedUrl="+pickedUrl+"&KeepThis=true&width=460&height=402");
			  	}
			  	else if ($(this).parents().hasClass('sidebarContact')) {
						/* before sending off the sidebarAlt, fill spaces and such! */
						var string = sidebarAlt.toLowerCase();
						string = string.replace(/[^a-zA-Z0-9_]/g,'-');
						string = string.replace(/[-]{2,}/,'-');
						pickedUrl = string; // basically set pickedUrl to a prettyfied sidebarAlt for Salesforce records and such.
			  		tb_show("","/page/1/opt-in-cta.jsp?pickedUrl="+pickedUrl+"&KeepThis=true&width=460&height=402");
			  		// console.log("WOOHOO!");
			  	}
			  	else if ($(this).parents().hasClass('video')) { 
			  		tb_show("","/page/1/opt-in-video.jsp?pickedUrl="+pickedUrl+"&KeepThis=true&width=460&height=402");
			  	}
				  
				  $(picked).removeClass('optInPicked');
				  
				  // When a cool click comes... or is forced! 
				  $("#optedIn , #lovedog").live('click',function(){ // .live is depricated? wha? http://api.jquery.com/live/		  	
				    setTimeout(function(){ // Added a little time to things for loads and all. :)
						  
						  vlt_Set_Cookie('vlt_optIn', 'true', '1000', '/', '', ''); // Set the cookie!
						  $(picked).removeClass('optInPicked').attr('rel','optInPicked');
						  
				      unlockLockedVideos();
				      $(picked).removeAttr('rel').addClass('optInPicked');					      
				      if (skip == 'yes') {
				      	tb_show("","/page/1/opt-in-cta-thank-you.jsp?pickedUrl="+pickedUrl+"&KeepThis=true&width=460&height=150");
				      }
				      else {
				      	loadUrl();
				      }
				      return false;
				    },750);
				  });
		      return false;
      }	
  	}
  	else {
  		loadUrl();
  		return false;
  	}
    
  });
	
	// Check video url and launch //
  function loadUrl(){
  	var mediaUrl = $(".optInPicked").attr('href'); 
  	
  	if ($(".optInPicked").parents().hasClass('document')) { // document?
	    $(".optInPicked").removeAttr('class');
	    window.location.href = mediaUrl;
	    return false;
  	}
  	else if ($(".optInPicked").parents().hasClass('externalVid')) { // external video? (gets handled similar to documents)
	    $(".optInPicked").removeAttr('class');
	    window.location.href = mediaUrl;
	    return false;
  	}
  	else if ($(".optInPicked").parents().hasClass('sidebarContact')) { // external video? (gets handled similar to documents)
	    $(".optInPicked").removeAttr('class');
	    window.location.href = mediaUrl;
	    return false;
  	}
  	else if ($(".optInPicked").parents().hasClass('video')) { // internal video?
  		// if cloud front url then modify
		  var vidSplit = mediaUrl.split("cfx");
		  if(vidSplit.length > 1){
		    mediaUrl = mediaUrl.replace("http","rtmp");
		    mediaUrl = mediaUrl + "&cf=true&";
		  }        
		  if (mediaUrl.indexOf("metacdn") == -1) {
		  	tb_show('','/page/1/new-video-player.jsp?flv='+mediaUrl+'&height=300&width=490');
		  } else {
		  	tb_show('','/page/1/new-video-player-metacdn.jsp?flv='+mediaUrl+'&height=400&width=680');
		  }
	    $(".optInPicked").removeAttr('class');
	    return false;  
  	}
  	else { // whatev! (this should not happen)
  		return;
  	}

  }
    
	/* end optInLock scripting */
	
	
	$(".overlayLink a").attr('rel',"#video_modal");
	
	
  // video embed calls

  // use the jquery.flash 200003 to embed flash, content embedded via client
  $('span.videoembed').each(function(){
   		
   		
   		$(this).html('<div class="alt">'+$(this).html()+'</div>').addClass('flash-replaced');
   		$(this).after('<div id="noFlash">Hi.  <a href="http://www.adobe.com/go/getflashplayer/">You need Flash.</a></div>');
   		
	    var mediaUrl = $(this).find('a').attr('href');
	    // if cloud front url then modify
	    var vidSplit = mediaUrl.split("cfx");
	    if(vidSplit.length > 1){
	      mediaUrl = mediaUrl.replace("http","rtmp"); // Simplicis doesn't know what rtmp is?
	    }

      var params = {};
      params.play = "true";
      params.autostart = "true";
      params.allowFullScreen = "true";
      var flvPath = mediaUrl;
      var pathSplit = flvPath.split("st/");
      var filename = pathSplit[1];
      var streamer = pathSplit[0]+"st/";
	    
	    if ($(this).find('img').hasClass('embedded')) {
   			var img = $(this).find('img').attr('src');
   			swfobject.embedSWF("/media/flash/1/player.swf", "noFlash", "480", "290", "8", "http://verisae.com/media/flash/1/expressinstall.swf", {file:filename,streamer:streamer, image: img}, params);
   		}
   		else {
   			swfobject.embedSWF("/media/flash/1/player.swf", "noFlash", "480", "290", "8", "http://verisae.com/media/flash/1/expressinstall.swf", {file:filename,streamer:streamer}, params);
   		}
	    
	    /* $(this).flash({
	        src: "/media/flash/1/player.swf",
	        width: 490,
	        height: 300,
	        flashvars: { file: mediaUrl }
	      }); */

    // hide the orginal link which has been moved into div.alt (does this happen in flash?)
    $(this).find('.alt').hide();
  });
	
	jQuery.validator.addMethod("Allphone", function(value) { 
		return (value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); 
		}, "Please enter a valid phone number (Intl format accepted + ext: or x:)");
	
	jQuery.validator.addMethod("phoneUS", function(phone_number, element) { /* adds method phone number validation */
	  phone_number = phone_number.replace(/\s+/g, ""); 
		return this.optional(element) || phone_number.length > 9 &&
			phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
	}, "Please specify a valid phone number."); /* can also override in title of required inputs */
	    
	$("#startForm").validate({
	  rules: { /* rules adding for validator */
	    phone: {
	      required: true,
	      phoneUS: false,
	      Allphone: false
	    }
		}
	});
	
	$("#contactForm").validate({
	  rules: { /* rules adding for validator */
	    phone: {
	      required: true,
	      phoneUS: false,
	      Allphone: true
	    }
		}
	});
	
	$("#loginForm").validate({
	  rules: { /* rules adding for validator */
	    phone: {
	      required: true,
	      phoneUS: false,
	      Allphone: false
	    }
		}
	});
	
	$(".login a[rel]").overlay({
	
		left: 'center',
		top: '20%',
		// effect: 'apple',
	
	
	// some expose tweaks suitable for modal dialogs
	expose: {
		color: '#261006',
		loadSpeed: 200,
		opacity: 0.95
	},
	
	closeOnClick: true
	
	});


	$(".pop a[rel]").overlay({
		
		left: 'center',
		top: '10%',
		// effect: 'apple',
	
	
	// some expose tweaks suitable for modal dialogs
	expose: {
		color: '#261006',
		loadSpeed: 200,
		opacity: 0.95
	},
	
	closeOnClick: true,	

	onBeforeLoad: function() {
	
		var dh = $(document).height();
		
		$('div.sheldon_love').each(function(idx,el){
	    el.style.height = dh+'px';
	    
	  });
		
	}
	
	
	});
	
	$(".overlayLink a").attr('rel',"#video_modal");
	
	// video overlay link
	$(".overlayLink a[rel]").overlay({
		left: 'center',
		top: '20%',
		// effect: 'apple',
	
	
	// some expose tweaks suitable for modal dialogs
	expose: {
		color: '#261006',
		loadSpeed: 200,
		opacity: 0.95
	},
	
	closeOnClick: true,
	onBeforeLoad: function() { 
 
            // grab wrapper element inside content 
            var wrap = this.getContent().find(".contentWrap"); 
 
            // load the page specified in the trigger 
            wrap.load(this.getTrigger().attr("href")); 
        } 	
    });
  
  /***********************************************
	*  Pricing plan page
	*  toggle expand/collapse link and tooltip
	************************************************/
	
	/* For Compare Pricing drop-down */
	var toggleWrap = $("button.toggleWrap");

  $(toggleWrap).html('<a href="#" class="toggle">Compare pricing plans in detail</a>'); // Need to look into why this is needed in IE to show toggly/arrow
  
  toggleWrap.click(function() {
    
    var detail = $("div#detailTable");
    
    if ( detail.is(":hidden") ) {
      detail.slideToggle("fast");
      $(toggleWrap).html('<a href="#" class="toggle expanded">Hide pricing plan details</a>');
    }  
    else {
      detail.slideToggle("fast");
      $(toggleWrap).html('<a href="#" class="toggle">Compare pricing plans in detail</a>');
    }
    return false;
	});
	
	/* For Sign Up Now Button */
	$(".buttonLink").click( function() {
		var url = $(this).find("a").attr("href");
		window.location.href = url;
		return false;
	})
	
	/* Tooltips on hover over links in pricing drop-down table */
	$("div#planWrapper u").tooltip({
   position: 'top center',
   offset: [0,10], // tweaks the position
   relative: true // tooltip position relative to trigger element
  });//.dynamic(); // tooltip flips to top of not enough room to display - didn't behave nicely by side of page
  
  /* end pricing plan page scripts*/
  
});
