


var $j = jQuery.noConflict();
var phonesPlansFlashID = "phonesPlansFlash";

$j(document).ready(function () {

	$j("input[type='text']").setupFormField();
	$j("textarea").setupFormField();
	$j("#nav li").setupHover();
	
	$j("input[type='password']").setupPasswordField();
	
	setWrapperClicks();
	setupBackgroundImage();
	setMainContentHeight();
	
	if (($j('body').hasClass('reveal')) && ((typeof document.body.style.maxHeight != "undefined"))) {
		$j('html').css({'height':'100%','margin-bottom':'1px'});
		setTimeout("navSlide()", 1000);
	} else {
		$j('#nav').css('top','0');
		$j('#mainContent').css('display','block');
	}

	$j('form.validate').setupValidation();
	$j('.accordion').accordion();
	
	setupPanic();

//	setupSBNav();

	if (jQuery.url) {
		checkForLayers();
	}
	
	tabs('.visual_tabs', '.visual_tab_item');
	tabs('.inline_tabs', '.inline_tab_item');

	setupPhoneGrid();
	setupPhoneDetail();

	updateNavForFlash();
	
	updateLinks();
	addMouseOver();	
	checkLoggedIn();		

	$j(window).load(function(){
		setMainContentHeight();
	});
	
	
	/*if($j("#nav_main3_8")){
		  
		  var link_html = $j("#nav_main3_8").html();
		  //alert(link_html);
		  
		  if(link_html.indexOf("Luv")){
			  
			  $j("#nav_main3_8 a").attr('target','_blank');
			  
		  }
	}*/
	
	/*$j("#nav_main4").html("<div id='haiti' onclick='location.href=\"http://www.virginmobileusa.com/haiti\"'");*/


});


updateNavForFlash = function() {
	if (typeof(swfobject) != 'undefined') {
		if(swfobject.hasFlashPlayerVersion("9.0.0")) { 	
			if ($j('#page_phones').length || $j('#page_plangrid').length || $j('#page_familyplangrid').length || $j('#page_deals').length) {
				$j('#nav_main1_1 a').click(function() {
					getFlashMovie(phonesPlansFlashID).updateSlider('sectionPhones');
					return false;
				});
				$j('#nav_main1_2 a').click(function() {
					getFlashMovie(phonesPlansFlashID).updateSlider('sectionPlans');
					return false;
				});
				$j('#nav_main1_3 a').click(function() {
					getFlashMovie(phonesPlansFlashID).updateSlider('sectionDeals');
					return false;
				});
			}
		}
	}
}

setupPhoneGrid = function() {
	$j('#page_phones .phone').each(function () {
		var wrapper = $j(this);
		setPrice(wrapper);
		$j(wrapper).find('select').change(function () {
			setPrice(wrapper);
		});
	});
}
setPrice = function(wrapper) {
	var selectedItem = $j(wrapper).find('select').val();
	if (selectedItem) {
		$j(wrapper).find('h4').removeClass('current');
		$j(wrapper).find('#' + selectedItem).addClass('current');
	}
}
setupPhoneDetail = function() {
	$j('.page_phonedetail #selector_wrapper').each(function () {
		var wrapper = $j(this);
		setPriceDetail(wrapper);
		$j(wrapper).find('select').change(function () {
			setPriceDetail(wrapper);
		});
	});
}
setPriceDetail = function(wrapper) {
	var selectedItem = $j(wrapper).find('select').val();
	if (selectedItem) {
		$j(wrapper).find('div.detail_prices').removeClass('current');
		$j(wrapper).find('#' + selectedItem).addClass('current');
	}
}
checkForLayers = function() {
	if (jQuery.url.param("open")) {

		var urlArray = jQuery.url.param("open").split("|");
		var destinationURL = urlArray[1].replace("_amp_","&");

		switch(urlArray[0]) {
			case "accessory":
				if (destinationURL.indexOf('?') == -1) {
					tb_show(null,destinationURL+'?height=1000&width=778&TB_iframe=true',false);
				} 
				else {
					tb_show(null,destinationURL+'&height=1000&width=778&TB_iframe=true',false);
				}
				break;
			
			case "phone": 
			case "plan":
				if (destinationURL.indexOf('?') == -1) {
					tb_show(null,destinationURL+'?height=500&width=907&TB_iframe=true',false);
				}
				else {
					tb_show(null,destinationURL+'&height=500&width=907&TB_iframe=true',false);
				}
				break;
		}
	}
	
	// if the layer's been opened directly, then redirect to its default location
	if (typeof layerDefaultPage != 'undefined') {
		if (self == self.parent) {	
			if (layerDefaultPage.indexOf('?') == -1) {
				window.location.href = layerDefaultPage + '?open=' + layerURLData;
			}
			else {
				window.location.href = layerDefaultPage + '&open=' + layerURLData;
			}
		}
	}
}


navSlide = function() {
	$j("#nav").animate({"top": "+=70px"}, 500, 'jswing', fadeContent);
}
setupPanic = function() {
	$j('#panic').click(function () {
		alert('Oh no!');
		return false;
	});
}
fadeContent = function()
{
	if($j.browser.msie)
		$j('#mainContent').show(0, setMainContentHeight());
	else
		$j('#mainContent').fadeIn(700, setMainContentHeight());
}


window.onresize = function() {
	setBackgroundImageSize();
	setMainContentHeight();
}

/*
var currheight;
window.onresize = function(){
	if(currheight != document.documentElement.clientHeight)
	{
		// alert('onresize event triggered');
		setBackgroundImageSize();
		setMainContentHeight();	
	}
	currheight = document.documentElement.clientHeight;
}
*/

$j(window).scroll(function() {
	if(typeof document.body.style.maxHeight === "undefined") { //if IE 6
		$j("#background").css("top", $j(window).scrollTop() + "px");  // fix bg for ie6
//		$j("#header").css("top", $j(window).scrollTop() + "px"); // fix header for ie6
	}
});


setupBackgroundImage = function () {

	// total number of images, names backgroundN.jpg where N is a number. ie: background2.jpg
	totalBGImages = 5;
	// alert('bam');
	$j('#background img').replaceWith('<img src="http://www.virginmobileusa.com/_img/background' + randomBackground() + '.jpg" alt="" />');
 	setBackgroundImageSize()
}

randomBackground = function () {

	//check for cookie
	if ($j.cookie) {
		if ($j.cookie('bg')) {
			return $j.cookie('bg');
		} else {
			randBG = parseInt(Math.random()*totalBGImages);
			$j.cookie('bg', randBG, {path: '/', domain: '.virginmobileusa.com'});
			return randBG;
		}
	}

}

setBackgroundImageSize = function() {

	var docHeight = $j(document).height();
	var docWidth = $j(document).width();
		
	// preserve aspect ratio
	var imgHeight = (docWidth/1024)*768;
	
	$j('#background img').css({width:docWidth,height:imgHeight,margin:"0 auto"}).show();

}

setMainContentHeight = function() {


	$j('#mainContent').height('auto')
	// console.log('height() = ' + $j('#mainContent').height());		

	var docHeight = $j(document).height() - 200;
	
	if ($j('#TB_iframeContent').length > 0) {
		var thickboxHeight = $j('#TB_iframeContent').height();
//console.log('there is a thickbox that is ',thickboxHeight,'px tall');	
		if (thickboxHeight > docHeight) {
			docHeight = thickboxHeight;	
		}
	}
// console.log('docHeight = ' + docHeight);		
	var mainContentHeight = $j('#mainContent').height();
// console.log('mainContentHeight = ' + mainContentHeight);			
	if (mainContentHeight < docHeight) {
		$j('#mainContent').height(docHeight);
		// console.log('mainContentHeight < docHeight');	
	} else {
		// console.log('! mainContentHeight < docHeight');	
		$j('#mainContent').height(mainContentHeight);	
		//$j('#mainContent').height('auto');           
	}

// console.log('setMainContentHeight : ' + $j('#mainContent').height());	

}

setWrapperClicks = function() {

	$j('#foreground').css('opacity', '0.5');
	
	$j('#nav_secondary4').click(function () {
		$j('#nav_secondary4 > a').addClass('active');
		$j('#nav_secondary4').css({'z-index': '1000'});
		$j('#nav_secondary4 ul').css('display', 'block');
		if (typeof document.body.style.maxHeight != "undefined") {//if NOT IE 6
			$j('#foreground').fadeIn('slow');
		}
		return false;
	});
	$j('#nav_secondary4 ul').bind("click", function (e){
			e.stopPropagation();
	});
	$j('#nav_secondary5').bind('click', function () {
		  /*$j('#nav_secondary5 > a').addClass('active');
		  $j('#nav_secondary5').css({'z-index': '1000'});
		  $j('#nav_secondary5 ul').css('display', 'block');
		  $j('#nav_secondary5 ul li iframe').attr('src', 'https://sso.virginmobileusa.com/cas/login?helioView=vmu'); 
		  if (typeof document.body.style.maxHeight != "undefined") {//if NOT IE 6
			  $j('#foreground').fadeIn('slow');
		  }
		  return false;*/
		  window.location.href="https://www.virginmobileusa.com/myvirginmobile/home.do";
	});
	$j('#foreground, #nav, #container').click(function () {
		$j('#nav_secondary4 > a').removeClass('active');
		$j('#nav_secondary5 > a').removeClass('active');
		$j('#nav_secondary4').css({'z-index': ''});
		$j('#nav_secondary5').css({'z-index': ''});
		$j('#nav_secondary5 ul').css('display', 'none');
		$j('#nav_secondary4 ul').css('display', 'none');
		if (typeof document.body.style.maxHeight != "undefined") {//if NOT IE 6
			$j('#foreground').fadeOut();
		}
	});
}

jQuery.fn.setupFormField = function(theField) {
	return this.each(function() {
	
		// Save original value
		// $j(this).attr('originalValue',$j(this).val());
		
		// Add focus action (selecting field)
		$j(this).focus(function() {
			if ($j(this).val() == $j(this).attr('title')) {
				$j(this).val('');
			}
			else {
				$j(this).select();
			}
		});

		// Add blur action (moving off of field)
		$j(this).blur(function() {
			if ($j(this).val() == '') {
				$j(this).val($j(this).attr('title'));
			}
		});	
	});
}; 

jQuery.fn.setupPasswordField = function(theField) {
	return this.each(function() {
	
		// Add focus action (selecting field)
		$j(this).focus(function() {
			$j(this).addClass('hidepasswordlabel');
		});
		
		// Add blur action (moving off of field)
		$j(this).blur(function() {
			if ($j(this).val().length == 0) {
			$j(this).removeClass('hidepasswordlabel');
		}
		});
	
	});
}; 


jQuery.fn.setupHover = function() {
	return this.each(function() {
	
		$j(this).hover(
		function() {
			$j(this).addClass('hover');
		},
		function() {
			$j(this).removeClass('hover');
		});
	
	});
};

jQuery.fn.accordion = function() {

		return this.each(function() {
				//initialize
	
		$j(this).find('dd').hide();
		$j(this).find('dt.expanded').next('dd').show();
		
		$j(this).find('dt').each(function() {

			$j(this).click(
				function() {

						if ($j(this).hasClass('expanded')) {
							//$j(this).removeClass('expanded').next('dd').slideUp(300);
							$j(this).removeClass('expanded').next('dd').hide();

						} else {
							//$j(this).addClass('expanded').next('dd').slideDown(300);
							$j(this).addClass('expanded').next('dd').show();

						}
						setMainContentHeight();

			});

		});
	
	});

};

 

jQuery.fn.accordion2 = function() {
	return this.each(function() {
	
		//initialize
		$j(this).find('dd').hide();
		$j(this).find('dt.expanded').next('dd').show();
		
		$j(this).find('dt').each(function() {
			$j(this).click(
			function() {
				if ($j(this).hasClass('expanded')) {
					$j(this).removeClass('expanded').next('dd').hide();
				} else {
					$j(this).addClass('expanded').next('dd').show();
				}
			});
		});
	});
}; 

jQuery.fn.setupValidation = function() {

	// $j(".validation_notice").hide();
	// $j(".validation_notice li").hide();
	
	this.submit(function() {
		// alert('submit');
		var errors = new Array();
		
		$j("input, select, textarea").removeClass("invalid");
		// passwords
		// check to see if pass1 and pass2 are long enough, then make sure they match
		
		if (($j("#password1").length > 0) && ($j("#password2").length > 0)) {
			if ( ($j("#password1").val().length < 4) || ($j("#password2").val().length < 4) || ($j("#password1").val() != $j("#password2").val()) ) {
			
				errors.push("password");
				$j("#password1").addClass("invalid");
				$j("#password2").addClass("invalid");
			
			}
		}
		
		// all other required form elements
		$j(".required").each(function() {
			// detect if it's been modified
			if ( $j(this).attr("title") == $j(this).val() || $j(this).val() == "") {
			
				// alert(this.id);
				// it hasn't, so show it's related LI
				errors.push(this.id);
				$j(this).addClass("invalid");
			}
		});
		
		// if email exists
		if ($j(".email").length > 0) {
		
			// does it have one @
			if ($j(".email").val().split("@").length == 2 ) {
				
				// does it have at least one dot in the 2nd half
				if ($j(".email").val().split("@")[1].split(".").length > 1 ) {
					
					//we're ok folks!
					
				} else {
					// alert("no dot");
					errors.push("email");
					$j(".email").addClass("invalid");
				}
			} else {
				// alert("not the right number of @'s in the address");
				errors.push("email");
				$j(".email").addClass("invalid");
			}
		}
		
		if ( errors.length > 0 ) {
			// drawErrors(errors);
			return false;
		} else {
			// alert("submitting");
			return true;
		}
	});
};


// *** Commented out by MW for side nav menu

//setupSBNav = function() {
//	if (($j('#sbnav').length) && (typeof sbnav != "undefined")) {

//		if (sbnav.length) {
//			$j('#sbnav li').removeClass('current');
//		}

//		if (sbnav.length > 0) {
//			$j('#sbnav > li').eq(sbnav[0]).addClass('current');
//		}
//		if (sbnav.length > 1) {
//			$j('li.current ul').children('li').eq(sbnav[1]).addClass('current').children('a').prepend("&gt; ");
			
//		}
//		if (sbnav.length > 2) {
//			$j('li.current li.current ul').children('li').eq(sbnav[2]).addClass('current');
//		}
//	}
//}

setVisitor = function(type, value) {
	// get existing values
	var prospectCookieVal = $j.cookie('u_pr');
	var customerCookieVal = $j.cookie('u_cst');

	switch (type) {
		case "p":
			// set as long as there's no customer cookie
			if (customerCookieVal) {
			
				// if cookie val > 0 and value = 0, then do nothing
				if (prospectCookieVal && prospectCookieVal > 0) {
					return true;
				}
				
				// if cookie value = 1, then don't override for 4 or 7
				if (prospectCookieVal && prospectCookieVal == 1) {
					if (value != 4 && value != 7) {
						 $j.cookie('u_pr', value, {path: '/', expires: 30, domain: '.virginmobileusa.com'});
					}	
				}
				
				// otherwise, set the cookie
				else {
					 $j.cookie('u_pr', value, {path: '/', expires: 30, domain: '.virginmobileusa.com'});
				}
				
			}
						
			break;
			
		case "c":
			// delete prospect cookie
			if (prospectCookieVal) {
				$j.cookie('u_pr', null, {path: '/'});
			}
			
			// set value
			$j.cookie('u_cst', value, {path: '/', expires: 150, domain: '.virginmobileusa.com'});
			
			break;
	}
}	

tabs = function(tabs, tabItems) {
	$j(tabs + ' li').click(function() {
		$j(this).siblings().removeClass('current');
		$j(this).addClass('current');
		$j(this).parent().parent().find(tabItems).removeClass('current');
		clickedID = $j(this).find('a').attr('href');
		$j(clickedID).addClass('current');
		setMainContentHeight();
		return false;
	});
}; 


function getFlashMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {             
		return window[movieName];         
	} 
	else {             
		return document[movieName];         
	}     
}     




updateLinks = function() {
	
	// Set the target of any links that should open in a new window
	$j("a[rel='new']").attr('target','_blank');
	
	// Any element that has the class .clickable, watch for click and take user to first href's URL.
	$j(".clickable").click(
		function () {
			document.location = $j(this).find('a:first').attr('href');
		}
	);
}

addMouseOver = function() {
	// Format any external URLs to go through the exit interstitial
	$j(".mouseout").hover(
		function () {
			$j(this).removeClass('mouseout').addClass('mouseover');
		}, 
		function () {
			$j(this).removeClass('mouseover').addClass('mouseout');
		}
	);
}

checkLoggedIn = function() {

	if ($j.cookie || $j('body').hasClass('log_pre') || $j('body').hasClass('log_post')) {
		if ($j.cookie('u_log')) {
			cookieValue = $j.cookie('u_log');
			
			if (cookieValue == "pre") {
				$j('body').addClass('log');
				$j('body').addClass('log_pre');
			} else if (cookieValue == "post") {
				$j('body').addClass('log');
				$j('body').addClass('log_post');
			} 
		}

		// if body doesn't have the 'log' class at this point, then exit
		if (!($j('body').hasClass('log'))) {
			return;	
		}

		// add log out menu item
		$j('#nav_secondary8').before('<li id="nav_secondary9"><a>Log Out</a></li>');
		
		
		if ($j('body').hasClass('log_pre')) {
			// replace login/my account link
			$j('#nav_secondary5').unbind('click').find('a').attr("href", "https://www1.virginmobileusa.com/myvirginmobile/home.do");
				
			// add logout link
			$j('#nav_secondary9').find('a').attr("href", "https://www1.virginmobileusa.com/login/logout.do");
			
			$j('#nav_secondary9').bind('click', function () {
														  
								//$j('body').removeClass('log');
								//$j('body').removeClass('log_pre');			
								//$j.cookie('u_log', '', {path: '/', domain: '.virginmobileusa.com', expires: -100});
								$j.cookie('u_log', '', {path: '/', domain: '.virginmobileusa.com'});
			});
		}
		else if ($j('body').hasClass('log_post')) {
			// replace login/my account link
			$j('#nav_secondary5').unbind('click').find('a').attr("href", "https://www2.virginmobileusa.com");
				
			// add logout link
			$j('#nav_secondary9').find('a').attr("href", "https://www2.virginmobileusa.com/cas/logout");
			
			$j('#nav_secondary9').bind('click', function () {
														  
								//$j('body').removeClass('log');
								//$j('body').removeClass('log_post');			
								//$j.cookie('u_log', '', {path: '/', domain: '.virginmobileusa.com', expires: -100});
								$j.cookie('u_log', '', {path: '/', domain: '.virginmobileusa.com'});
														  
			});
			
		}
			
	} 
}

function resizeiFrame(iframeContentHeight){

	// alert('resizeiFrame: ' + iframeContentHeight);
	$j('#TB_iframeContent').height(iframeContentHeight);

}


function awMigrationWarning(){
	
	if (confirm("IMPORTANT!\n\nIf you decide to switch to a Virgin Mobile plan, you will no longer receive 200 FREE Anytime Minutes each month.   If you leave Assurance Wireless now, you will need to re-apply if you wish to return to Assurance Wireless at a later time. Do you still wish to switch to a Virgin Mobile plan?"))
        {         

           window.location.href('/myvirginmobile/migrationOverview.do');

        }

        else

        {         

          

        } 
}



