$(document).ready(function () {
	var base = (document.getElementsByTagName ('BASE')[0] && document.getElementsByTagName( 'BASE')[0].href) || location.href
	var href = window.location.href;
	var hrefs = window.location.href.split('?');
	$('#nav_left_side a').each(
			function (intIndex ) {
				var links = ($(this).attr("href")).split('?');
				if (links[0] == 'reViewStory.htm' || links[0] == 'orderHistory.htm') {
					var link = links[0] + "?" + links[1];
					if (base+link == href)
						$(this).addClass("current");
				} else if (base+links[0] == hrefs[0]) {
					$(this).addClass("current");
				}
			}
	);

	var mainNavs = {
			'nav_events': 'images/global/nav/nav_events_on.gif',
			'nav_hair': 'images/global/nav/nav_hair_on.gif',
			'nav_acne': 'images/global/nav/nav_acne_on.gif',
			'nav_see': 'images/global/nav/nav_see_on.gif',
			'nav_what': 'images/global/nav/nav_what_on.gif'
	};
	
	for(var navId in mainNavs) {
		if (document.getElementById(navId)) {
			document.getElementById('img_'+navId).src = mainNavs[navId];
			document.getElementById('img_'+navId).setAttribute('onmouseout', "");
			document.getElementById('img_'+navId).setAttribute('onmouseover', "");
			break;
		}
	}
	
});


function triaShopNow() {
	document.location.href = 'displayProducts.htm?opcode=1&product=hair_removal';
}

function trimInput(ele) {
	try {
		ele.value = ele.value.replace(/^\s+|\s+$/g, '') ;
	} catch (err) {
		return false;
	}
}

var DD_NAV_MOUSEOVER = {};
function dd_nav_mouseover(dd) {
	var div = document.getElementById('dd_'+dd);

	div.style.left = "auto";

	DD_NAV_MOUSEOVER[dd] = true;
	if (navigator.platform.substring(0,3) == 'Mac') {
		if (jQuery.browser['mozilla']) {
			div.style.marginTop = '0px';
		} else {
			div.style.marginTop = '0px';
		}
	} else {
		if (jQuery.browser['mozilla']) {
			if (jQuery.browser.versionNumber >= 3.6) {
				div.style.marginTop = '0px';
			} else {
				div.style.marginTop = '-4px';
			}
		} else {
			div.style.marginTop = '0px';
		}
	}
}
function dd_nav_mouseout(dd) {
	var div = document.getElementById('dd_'+dd);
	var img = document.getElementById('image_'+dd);	

	DD_NAV_MOUSEOVER[dd] = false;
	setTimeout(function() {
		if (!DD_NAV_MOUSEOVER[dd]) {
			div.style.left = -999;
		}
	},30);
}

function showAlertLayer(target, id, width, height) {
    var isIE4 = (document.all && !document.getElementById) ? true : false;
    var isIE5 = (document.all && document.getElementById) ? true : false;
    var isIE = (isIE4||isIE5) ? true : false;

    if (! target) target = 'alert_link_div';
    var top = alertFindPosY(document.getElementById(target));
    var left = alertFindPosX(document.getElementById(target));

    if (!width) width = 0;
    if (!height) height = 320;
    
    if (isIE) {
      document.getElementById(id).style.top = (top - height - 10) + 'px';
      document.getElementById(id).style.left = (left + 10 + width) + 'px';
    } else {
      document.getElementById(id).style.top = (top - height) + 'px';
      document.getElementById(id).style.left = (left + 10 + width) + 'px';
    }
    document.getElementById(id).style.display = "block";
}

function alertFindPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}
function alertFindPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1)
      {
    	  curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
	  curleft += obj.x;
  return curleft;
}


function confirm_email(str,url) {
	
	if($('#firstname').val()=='First Name' || trim($('#firstname').val()).length == 0){
		alert('Please enter your name');
		return false;	
	}
	if(str == 'Email address')
	{
		alert('Please provide email address');
		return false;
	}
	else if (! email_validate(str)) {		
		
		alert('The provided email address is not valid');
		return false;
	}
	if($('#firstname').val()=='First Name' || trim($('#firstname').val()).length == 0){
		alert('Please enter your name');
		return false;	
	}
	
	
	var isSubSuccess = false;
	
	//var url="subscription.htm";
	var param={};
	param['email']=str;
	param['firstName']=$('#firstname').val();
	param['source']=$('#footerSource').val();
	
		$.ajax({
		   type: "POST",
		   url: url,
		   data: param,
		   async: false,
		   success: function(text){
			text = text.replace(/(\n|\r)+$/, '');
	 		//if( text == "OK" )
	 		//{
				
	 			isSubSuccess = true;
	 			
	 			$("#SubscriptionFooterDiv").html("Thanks for signing up!");
				$("#emailSubForm").hide();
				$("#SubscriptionFooterDiv").css({'color':'#0c6089','font-weight':'bold'});
	 			
	 		//} 
	 		}
		 });
		
	return isSubSuccess;
}
function confirm_promo_email(str,url) {
	if($('#firstpromoname').val()=='First Name' || trim($('#firstpromoname').val()).length == 0){
		alert('Please enter your name');
		return false;	
	}
	if(str == 'Email address' || trim(str).length == 0)
	{
		alert('Please provide email address');
		return false;
	}
	else if (! email_validate(str)) {		
		
		alert('The provided email address is not valid');
		return false;
	}
	
	if($('#firstpromoname').val()=='First Name' || trim($('#firstpromoname').val()).length == 0){
		alert('Please enter your name');
		return false;	
	}
	
	
	var isSubSuccess = false;
	//var url="subscription.htm";
	var param={};
	param['email']=str;
	param['firstName']=$('#firstpromoname').val();
	param['source']='UK-Headerpage';
	
		$.ajax({
		   type: "POST",
		   url: url,
		   data: param,
		   async: false,
		   success: function(text){
			text = text.replace(/(\n|\r)+$/, '');
	 		//if( text == "OK" )
	 		//{
				
	 			isSubSuccess = true;
	 			
	 			$("#SubscriptionDiv").html("Thanks! Check your inbox for the winners");
				$('#emailPromoForm').hide();
				$("#SubscriptionDiv").css({'color':'#0c6089','font-weight':'bold'});
				
	 			
	 			
	 			
	 		//} 
	 		}
		 });
		
	return isSubSuccess;
}


function email_validate(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
	    return false;
	 }

	 return true;
}


var eventLoadedCarsousel = {};
var eventCarousels = {};
function openEventGallery(id, carousel, link) {
	$('#'+id).show();
	if (! eventLoadedCarsousel[carousel]) {
		eventLoadedCarsousel[carousel] = 1;
		$('#'+carousel).jcarousel({scroll:2,auto:6,initCallback: eventCarousel_initCallback});
	} else {
		eventCarousels[carousel].scroll(1);
	}
	
	if (link) {
		document.getElementById(link).innerHTML = 'hide the photo gallery';
		document.getElementById(link).onclick = function(){ closeEventGallery(id, carousel, link); };
	}
}
function closeEventGallery(id, carousel, link) {
	$('#'+id).hide();

	if (link) {
		document.getElementById(link).innerHTML = 'view the photo gallery';
		document.getElementById(link).onclick = function(){ openEventGallery(id, carousel, link); };
	}
}
function eventCarousel_initCallback(carsouel) {
	for (var carId in eventLoadedCarsousel){};
	eventCarousels[carId] = carsouel;	
}

function checkReviewForm() {
	try {
		var fname = document.getElementById('firstName').value;
		var lname = document.getElementById('lastName').value;
		var email = document.getElementById('emailAddress').value;
		var gender = document.getElementById('gender').value;
		var age = document.getElementById('age').value;
		var review = document.getElementById('experience').value;

		var msg = '';
		if (!fname) {
			msg += 'Please enter your First Name' + "\n";
		}
		if (!lname) {
			msg += 'Please enter your Last Name or Initial' + "\n";
		}
		if (!email) {
			msg += 'Please enter your Email Address' + "\n";
		} else if (!email_validate(email)) {
			msg += 'Your Email address is invalid';
		}
		var regExp = new RegExp('[0-9]{2}');
		if (!age) {
			msg += 'Please enter your Age' + "\n";
		} else if (!regExp.test(age)) {
			msg += 'Please enter a valid Age' + "\n";			
		} else if (age < 15 || age > 99) {
			msg += 'Please enter a valid Age' + "\n";			
		}
		if (!review) {
			msg += 'Please enter your Review' + "\n";
		}
		if (msg) {
			alert(msg);
			return false;
		} else {
			return true;
		}
	} catch(err) {
		alert(err.message);
	}
}

function showPasswords(checkbox) {
	if (checkbox.checked) {
		$('#pass').show();
		$('#pass1').show();
	} else {
		$('#pass').hide();
		$('#pass1').hide();
	}
	
	//isUserAvailable();
	
}


function shipping2billing(checkbox) {
	if (checkbox.checked) {
		if ($('#shippingFirstName').val()) $('#billingFirstName').attr('value', $('#shippingFirstName').val());
		if ($('#shippingLastName').val()) $('#billingLastName').attr('value', $('#shippingLastName').val());
		if ($('#shippingAddress1').val()) $('#billingAddress1').attr('value', $('#shippingAddress1').val());
		if ($('#shippingCompanyName').val()){
			$('#billingCompanyName').attr('value', $('#shippingCompanyName').val());
		}else{
			$('#billingCompanyName').attr('value', '');
		}
		if ($('#shippingHouseName').val()){
			$('#billingHouseName').attr('value', $('#shippingHouseName').val());
		}else{
			$('#billingHouseName').attr('value', '');
		}
		if ($('#shippingHouseNumber').val()){
			$('#billingHouseNumber').attr('value', $('#shippingHouseNumber').val());
		}else{
			$('#billingHouseNumber').attr('value', '');
		}
		if ($('#shippingAddress2').val()) $('#billingAddress2').attr('value', $('#shippingAddress2').val());
		if ($('#shippingCity').val()) $('#billingCity').attr('value', $('#shippingCity').val());
		if ($('#shippingCounty').val()) $('#billingCounty').attr('value', $('#shippingCounty').val());
		if ($('#shippingZip').val()) $('#billingZip').attr('value', $('#shippingZip').val());
		if ($('#shippingPhone').val()) $('#billingPhone').attr('value', $('#shippingPhone').val());
	} else {
		$('#billingFirstName').attr('value', '');
		$('#billingLastName').attr('value', '');
		$('#billingAddress1').attr('value', '');
		$('#billingCompanyName').attr('value', '');
		$('#billingHouseName').attr('value', '');
		$('#billingHouseNumber').attr('value', '');
		$('#billingAddress2').attr('value', '');
		$('#billingCity').attr('value', '');
		$('#billingCounty').attr('value', '');
		$('#billingZip').attr('value', '');
		$('#billingPhone').attr('value', '');
	}
}

function readMag(obj) {
	if (obj.pages.length <= 0) return false;

	if (obj.pages.length == 1) {
		tb_show(obj.name, obj.pages[0], null, null, obj.top);
	} else {
    	var pages = '';
    	for (var i=1; i<=obj.pages.length; i++) {
    		if (pages) pages += ' | ';
    		j = i - 1;
    		pages += '<a href="javascript:void(0)" onclick="document.getElementById(\'TB_Image\').src=\''+obj.pages[j]+'\';">Page ' + i + '</a>';
    	}
		tb_show(obj.name, obj.pages[0], null, pages, obj.top);
	}
}

/***** Save money cal ****/
function switch2Saving() {
	document.getElementById('save_cal_top').style.backgroundImage = 'url(images/benefits/box_save_title_savings.gif)';
	document.getElementById('calculator_convenience').style.display = 'none';
	document.getElementById('calculator_saving').style.display = 'block';
}
function switch2Convenience() {
	document.getElementById('save_cal_top').style.backgroundImage = 'url(images/benefits/box_save_title_convenience.gif)';
	document.getElementById('calculator_saving').style.display = 'none';
	document.getElementById('calculator_convenience').style.display = 'block';
}
function calSavings() {
	var price = document.getElementById('saving_dollar').value;
	var used = document.getElementById('saving_used').value;
	var will = document.getElementById('saving_keep').value;

	var total = (price * used) + (price * will);
	var ototal = "";
	while(total > 999) {
		var remin = total % 1000;
		var total = parseInt(total / 1000);

		if (remin < 9) 
			remin = "00" + remin;
		else if (remin < 99)
			remin = "0" + remin;
		
		ototal = "," + remin + ototal;
	}
	ototal = total + "" + ototal;
	
	document.getElementById('saving_result').innerHTML = '<div class="border_h" style="margin-bottom:10px"></div>'+
		'<div class="header">total saving: $'+ototal+
		'</div>Based on your answers, you will save an average of <b>$'+ototal+
		'</b> using the TRIA System for $495.' ;
}
function calConvenience() {
	var time = document.getElementById('convenience_time').value;
	var used = document.getElementById('saving_used').value;
	var will = document.getElementById('saving_keep').value;

	var total = (time * used) + (time * will);

	document.getElementById('convenience_result').innerHTML = '<div class="border_h" style="margin-bottom:10px"></div>'+
		'<div class="header">total time saving: '+total+
		' hours</div>Based on your answers, you will save an average of <b>'+total+' hours</b> using the TRIA ' +
		'System once per month for 6-8 months.' ;
}

/** form validating functions ***/
function modPhoneFormat(ele, name, type) {
	var str = ele.value.replace(/\D/g, '');
	if (str.length > 10 &&  (str.substring(0,1) == "1")) {
		ele.value = str.substring(1,4) + '-' + str.substring(4,7) + '-' + str.substring(7,11);
		ele.style.backgroundColor = '#ffffff';
		return true;
	} else if (str.length >= 10) {
		ele.value = str.substring(0,3) + '-' + str.substring(3,6) + '-' + str.substring(6,10);
		ele.style.backgroundColor = '#ffffff';
		return true;
	} else {
		if (((ele.value==null)||(ele.value=="")) && type == 'onblur'){	
			return true;
		}
		
		if (type == 'onblur')
			ele.style.backgroundColor = '#ffdddd';

		return false;
	}
}

function validateField(fid, name) {
	var ele = document.getElementById(fid);
	if (!ele.value) {
		return 'Please enter '+ name;		
	}
	return "";
}

function emailvalidate(fid, name, type)
{
	var str = "";
	var ele = $('#'+fid);
	if (ele) str = ele.val();
	
	if (((str==null)||(str=="")) && type == 'onblur'){
		return "";
	}
	
	if (! name) name = 'email address';
	if ((str==null)||(str=="")){
		return "Please enter the " + name;
	}
	else if(!email_validate(str))
	{
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');
		return "Please enter valid " + name;
	} else if (type == 'onblur') { 
		$('#'+fid).css('background-color','#ffffff');		
	}
	
	return "";
}
function validatezip(fid, name, type)
{
	var str = "";
	var ele = document.getElementById(fid);
	if (ele) str = ele.value;

	if (((str==null)||(str=="")) && type == 'onblur'){	
		return "";
	}
	
	if (! name) name = 'zip code';
	if ((str==null)||(str=="")){
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');

		return "Please enter the " + name;
	}

	var error = validateZIP(str, name);
	if (error && type == 'onblur') 
		$('#'+fid).css('background-color','#ffdddd');
	else
		$('#'+fid).css('background-color','#ffffff');

	return error;
}

function validatephone(fid, name, type)
{
	var str = "";
	var ele = document.getElementById(fid);
	if (ele) str = ele.value;

	if ((str==null)||(str=="")){
		return "Please enter the Phone #";
	}
	else if(!ValidatePhone(str))
	{
		return "Please Enter a Valid Phone #";
	}
	
	return "";
}

function validateDate(fid, name, type) {
	var ele = document.getElementById(fid);

	var str = "";
	var ele = document.getElementById(fid);
	if (ele) str = ele.value;

	if (((str==null)||(str=="")) && type == 'onblur'){	
		return "";
	}

	var str = ele.value + "";
	if (!str.match('^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$')) {
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');

		return 'Invalid date format!';		
	} else if (type == 'onblur') { 
		$('#'+fid).css('background-color','#ffffff');		
	}
	return "";
}

function validateAge(fid, name, type) {
	var ele = document.getElementById(fid);

	var str = ele.value + "";
	if (((str==null)||(str=="")) && type == 'onblur'){	
		return "";
	}
	
	if (! name) name = 'birthdate';
	if (!str.match('^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$')) {
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');

		return 'Invalid ' + name + ' format!';		
	}

	// only to check if is > 18, don't care about month or days
	// birthday in yyyymmdd
	var birthdate = parseInt(str.substring(6,10))*10000 + parseInt(str.substring(3,5))*100 + parseInt(str.substring(0,2));

	// current date in yyyymmdd
	var dat = new Date();
	var currentDate = (dat.getFullYear()*10000) + ((dat.getMonth()+1)*100) + dat.getDate();

	if ((currentDate - birthdate) < 180000) {
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');

		return 'You must be 18 of age to be eligible for this sweepstake';
	} else if (type == 'onblur') {
		$('#'+fid).css('background-color','#ffffff');				
	}	
	
	return "";
}

function isFutureDate(fid, name, type) {
	var ele = document.getElementById(fid);

	
	if (! name) name = 'Purchase Date';
	
	var str = ele.value + "";
	if (((str==null)||(str=="")) && type == 'onblur'){	
		return "";
	}

	if (!str.match('^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$')) {
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');

		return 'Invalid Purchase Date!';		
	}

	// only to check if is > 18, don't care about month or days
	// enteredDate in yyyymmdd
	var enteredDate = parseInt(str.substring(6,10))*10000 + parseInt(str.substring(3,5),10)*100 + parseInt(str.substring(0,2),10);
	// current date in yyyymmdd
	var dat = new Date();
	var currentDate = (dat.getFullYear()*10000) + ((dat.getMonth()+1)*100) + dat.getDate();
	if (enteredDate > currentDate) {
		if (type == 'onblur') 
			$('#'+fid).css('background-color','#ffdddd');

		return 'Invalid ' + name;
	} else if (type == 'onblur') {
		$('#'+fid).css('background-color','#ffffff');				
	}	
	
	return "";
}

function validateZIP(field, name) {
	    var zipCodePattern = /(^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$)/;
	if(!zipCodePattern.test(field)){
		return "Please enter Valid " + name;
	}
	
	return "";
}

function loadProfile(divId) {
	$('#our-founders-content-1').hide();
	$('#our-founders-content-2').hide();
	$('#our-founders-content-3').hide();
	$('#our-founders-content-4').hide();
	$('#our-scientists-content-1').hide();
	$('#our-scientists-content-2').hide();
	$('#our-scientists-content-3').hide();
	$('#our-scientists-content-4').hide();
	$('#our-scientists-content-5').hide();

	$('#'+divId).show();
}

function showlayer(layer){
	var newLayer = document.getElementById(layer).style.display;
		if(newLayer=="none"){
			document.getElementById(layer).style.display="block";
		} else { 
			document.getElementById(layer).style.display="none";
	}
}
function storeView(storeAddress) {
	window.open("http://"+storeAddress,"Window1","menubar=no,width=430,height=360,toolbar=no");
}

function retrieveAJAXURL(url,callbackfunction,params) {
    
    
    var req = createXHR();
    
    req.onreadystatechange = function(){
        this.r = req;
        this.callback = callbackfunction;
        processStateChange(this.r, this.callback);
    }
    try {
        req.open("post", url, true); //was get
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.setRequestHeader("Content-length", params.length);
        req.setRequestHeader("Connection", "close");
         
    } catch (e) {
    //alert("Problem Communicating with Server\n"+e);
    
    alert("There Was A Problem Communicating With Server. SERVER ERROR CODE "+e);
    
    if(typeof(ajax_cleanup_on_failure) != 'undefined')
        {
            ajax_cleanup_on_failure();
        }
    }
    req.send(params);// QUERY STRING PASSING
}

function processStateChange(req, callback) {
    
    if (req.readyState == 4) 
        { 
            
            if(req.status == 200) 
                {
            	 
                    if(typeof(callback) == 'function')
                        {
                            callback(req.responseText);
                        }
                    } else {
                    alert(" Server Problem. Please Try Again.(AJAX StatusCode="+req.status+" )" );
                    
                    if(typeof(ajax_cleanup_on_failure) != 'undefined'){
                        ajax_cleanup_on_failure();
                    }
                }
                
            }else{
            
            
        }
    }
    
    ////////////////////////////////////////   XMLHTTPRequest OBJECT ////////////////////////////////
    function createXHR() 
    {
        var xmlhttp;
        
        /*@cc_on
        
        @if (@_jscript_version >= 5)
        
        try {
        
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.5.0");
        
        } catch (e) {
        
        try {
        
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        
        } catch (E) {
        
        xmlhttp = false;
        
        }
        
        }
        
        @else
        
        xmlhttp = false;
        
        @end @*/
        
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
            
            try {
                
                xmlhttp = new XMLHttpRequest();
                
                
            } catch (e) {
            
            xmlhttp = false;
            
        }
        
    }
    
    return xmlhttp;
}
////////////////////////////////////////   AJAX OBJECT ////////////////////////////////
var contextpath;
    function changeLocale(cpath,locale){
    	contextpath=cpath;
    	finalurl=cpath+"/changelocale";
        var param="iso="+locale;
        retrieveAJAXURL(finalurl,reloadPage,param);
    }


function reloadPage(){
   	window.location=window.location.protocol + "//" + window.location.host + "/" + contextpath;
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function verify(s)
{   var i;
    var returnString = 0;
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c == "-") returnString += 1;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	var bracket=3
	strPhone=trim(strPhone)

	if(verify(strPhone)!=2) return false
	if(strPhone.indexOf("+")>1) return false
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
	
	s = stripCharsInBag(strPhone, validWorldPhoneChars);

	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidatePhone(Phone){
	if (checkInternationalPhone(Phone)==false){
		return false
	}
	return true
 }




function toggleThisFun(dicClassNem,shoDiv,isPlayer){
    var PleyerId = dicClassNem+shoDiv+'Player';
 for(var i = 1;i<=2;i++){
    if(i == shoDiv ){
        $('.'+dicClassNem+i).show();
        
        //$('#'+dicClassNem+'Image'+i).attr('src','inactiveicons/small'+i+'.jpg');
	
          if(isPlayer=='true'){
		 
            $('#'+PleyerId).css('display','block');
            $('#'+PleyerId).css('width','270px');
            $('#'+PleyerId).css('height','224px');
            flowplayer(PleyerId,"assets/swf/flowplayer-3.0.5.swf");
          }
		 // else if(i!=2 && shoDiv != 2 ){
           //$('#'+PleyerId).css('display','none');
            //}
    } else {
        $('.'+dicClassNem+i).hide();
        
        //$('#'+dicClassNem+'Image'+i).attr('src','small'+i+'.jpg');
    }
 }
}

function toggleThisFunLanding(dicClassNem,shoDiv,isPlayer){
    var PleyerId = dicClassNem+shoDiv+'Player';
 for(var i = 1;i<=2;i++){
    if(i == shoDiv ){
        $('.'+dicClassNem+i).show();
        
        //$('#'+dicClassNem+'Image'+i).attr('src','inactiveicons/small'+i+'.jpg');
	
          if(isPlayer=='true'){
		 
            $('#'+PleyerId).css('display','block');
            $('#'+PleyerId).css('width','372px');
            $('#'+PleyerId).css('height','306px');
            flowplayer(PleyerId,"assets/swf/flowplayer-3.0.5.swf");
          }
		 // else if(i!=2 && shoDiv != 2 ){
           //$('#'+PleyerId).css('display','none');
            //}
    } else {
        $('.'+dicClassNem+i).hide();
        
        //$('#'+dicClassNem+'Image'+i).attr('src','small'+i+'.jpg');
    }
 }
}

function slideDown(){
/*	if (jQuery.browser.msie) {
$("#header ul.main_nav ").css("margin-top","-4px");
//$("#header ul.main_nav ").css("margin-bottom","0px");
//$("#header ul.top_nav li.ie_canada").css("position","relative");
//$("#header ul.top_nav li.ie_canada").css("top","-20px");
//$("#header ul.top_nav li.ie_canada").css("margin-bottom","-3px");

//$("#header ul.main_nav li .ie_canada").css("margin-top","-20px !important");
	}
*/ 

	$("#slide_down").show();

	$("#subEmail").focus();
	$('#subEmail').attr('value', '');

}
function slideUp(){
	if (jQuery.browser.msie) {
$("#header ul.main_nav ").css("margin-top","11px");
//$("#header ul.main_nav ").css("margin-bottom","10px");
//$("#header ul.top_nav li.ie_canada").css("position","relative");
//$("#header ul.top_nav li.ie_canada").css("top","0px");
//$("#header ul.top_nav li.ie_canada").css("margin-bottom","1px");

//$("#header ul.main_nav li .ie_canada").css("margin-top","-20px !important");
	}
	$("#slide_down").hide();

}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function calSavings2(){
	var price = document.getElementById('saving_dollar').value;
	var used = document.getElementById('saving_used').value;
	var will = document.getElementById('saving_keep').value;
	savingTime=(will*used*52);
	ototal=(price*will*12);	
	var commatotal1 = addCommas(ototal);
	var commatotal2 = addCommas(savingTime);	
	document.getElementById('saving_result').innerHTML = '<div class="border_h" style="margin-bottom:10px;border-top: 1px dotted #CCCCCC;"></div>'+
	'With the TRIA Laser you can save <b>£'+commatotal1+
	'</b> and <b>'+commatotal2+'</b> hours over a lifetime of hair removal. ' ;
	
} 
$(document).ready(function(){
    
	$x= $('#marketting_feature').html();
	$('.outer_right_hear_block').remove();
	$('#right_marketting_feature').html($x);
});
	
function tab_show_div(tabId){
	$tabTotal = ($('.bg_tab').length)+1;
	for(i=1;i<=$tabTotal;++i){
		if(i==tabId){
			$('#about_bg_'+i).attr('class','on');
			$tabBody = $('#tab_body_div'+i).html();
		
		 	$('#tab_content_txt').html($tabBody);	 
			}
		else{
			
			$('#about_bg_'+i).attr('class','bg_tab');
		}
		}
 	//$('#tab_learnmore_content').load('customercare/tab'+tabId+'.html');	 
}

function showQaLayer(layer,num){
	var newLayer = document.getElementById(layer+num+'_show').style.display;
		if(newLayer=="none"){
			document.getElementById(layer+num+'_show').style.display="block";
			$('#'+num+'more').html('show less');
		} else { 
			document.getElementById(layer+num+'_show').style.display="none";
			$('#'+num+'more').html('show more');
	}
}
function showlayer1(layer){
	//alert(layer);
	var newLayer = document.getElementById(layer).style.display;
		if(newLayer=="none"){
			document.getElementById(layer).style.display="block";
		} else { 
			document.getElementById(layer).style.display="none";
	}
}

function aboutHide(div1,div2,div3,div4){
		$('#'+div1).attr({'class':'link_blue'});
		$('#'+div2).attr({'class':'link_light_blue'});
		$('#'+div3).attr({'class':'link_light_blue'});
		$('#'+div4).attr({'class':'link_light_blue'});
		$('#about_'+div1).show();
		$('#about_'+div2).hide();
		$('#about_'+div3).hide();
		$('#about_'+div4).hide();
	
}

function showNewLayer(layer,layertext,arrow){
	var newLayer = document.getElementById(layer).style.display;
		if(newLayer=="none"){
			document.getElementById(layer).style.display="block";
			$('#'+layertext).html('show less');
			$('#'+layertext).removeClass(arrow);
			$('#'+layertext).addClass(arrow+'_inverted');
		} else { 
			document.getElementById(layer).style.display="none";
			$('#'+layertext).html('show more');
			$('#'+layertext).removeClass(arrow+'_inverted');
			$('#'+layertext).addClass(arrow);
			
	}
}

function mycarousel_initCallback6(carousel) {
    carousel_size= $('#carousel_ul_media li').size();
	
	 if(carousel_size<4){
	      	$('#right_scroll_derm').hide();
	      	$('#left_scroll_derm').hide();
		 }
    jQuery('#right_scroll_derm').bind('click', function() {
    
      	//$('#left_arrow_color6').attr('src','images/redesign/global/carousel_left_arrow_green.gif');
      	carousel.next();
      return false;
  });

  jQuery('#left_scroll_derm').bind('click', function() {
      carousel.prev();
      //	$('#right_arrow_color6').attr('src','images/redesign/global/carousel_right_arrow_green.gif');
      return false;
  });
};

$(document).ready(function(){
	jQuery("#carousel_ul_media").jcarousel({
	        scroll: 3,
	        initCallback: mycarousel_initCallback6,
	        // This tells jCarousel NOT to autobuild prev/next buttons
	        buttonNextHTML: null,
	        buttonPrevHTML: null
	    });
		
		function openPageDetail(pageNumber){
              $(".recommendation_detail").hide();
              $("#recommendationCopy"+pageNumber).show();
              tb_remove();
              return false;
            }

            jQuery("#carousel_ul_media").delegate("ul li.jcarousel-item","click",function(){
              var pageNum = $(this).attr("jcarouselindex");
              openPageDetail(pageNum);
            });  

//default: In the media page 1
            openPageDetail(1);  			
});


function showHopUpvideoMed(thisItem){

  //display outer hopup
  hp_showvideo(thisItem);

  //set position based on current browser viewport dimensions
  if ('innerWidth' in window) {   // all browsers, except IE before version 9
	  //var hpBodyX = window.innerWidth;
	  var hpBodyX = $(window).width();} 
  else  {  // Internet Explorer before version 9
	  var hpBodyX = document.documentElement.clientWidth;}
  if ('innerHeight' in window)  {  // all browsers, except IE before version 9
	  var hpBodyY = $(window).height();}
  else {  // Internet Explorer before version 9
	  var hpBodyY = document.documentElement.clientHeight;}
	  
	  
  //dimensions of the hopup
  var hpX = $(thisItem).outerWidth();
  var hpY = $(thisItem).outerHeight();
  
  //calculate position coordinates
  hpPositionX = (hpBodyX/2) - (hpX/2);
  hpPositionY = (hpBodyY/2) - (hpY/2);
  
  //set the position to maintain access to the hopup close button      
  //set the X position coordinate
  if ( hpPositionX <= 0 ) {
	$(thisItem).css("right", 0);
	$(thisItem).css("left", "auto"); } 
  else {
	$(thisItem).css("right", "auto");
	$(thisItem).css("left", hpPositionX);}
 
  //set the Y position coordinate
  if ( hpPositionY <= 0 ) {
	$(thisItem).css("top", 0);
	$(thisItem).css("bottom", "auto"); }
  else {
	$(thisItem).css("top", hpPositionY);
	$(thisItem).css("bottom", "auto");
  }}

function hp_removevideo(thisItem) {
  $("#hp_lightbox2").hide(); 
  $(thisItem).hide();}

//show the containing hop up div
function hp_showvideo(thisItem) {
  $("#hp_lightbox2").show(); 
  $(thisItem).show();}	


function playerReload(videodiv) {
	// install flowplayer inside a#player
	flowplayer(videodiv, {src: "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", wmode:'transparent'},{ 
		clip: {autoplay:true } ,
		plugins: {controls: {play:true, volume:true, mute:false, time:false, stop:false, playlist:false, fullscreen:true, scrubber: true}} 
			});  }  

$(document).ready(function(){
	$('#management_block').show();
	$('#board_block').hide();
	$('#scientists_block').hide();
	$('#lc_board').removeClass('link_blue').addClass('txt_blue');
	$('#lc_scientists').removeClass('link_blue').addClass('txt_blue');
	$('#lc_management').click(function(event){
		event.preventDefault();
		$('#management_block').show();
		$('#board_block').hide();
		$('#scientists_block').hide();
		$('#lc_board').removeClass('link_blue').addClass('txt_blue');
		$('#lc_scientists').removeClass('link_blue').addClass('txt_blue');
		$('#lc_management').removeClass('txt_blue').addClass('link_blue');
		
	});
	$('#lc_board').click(function(event){
		event.preventDefault();
		$('#board_block').show();
		$('#management_block').hide();
		$('#scientists_block').hide();
		$('#lc_management').removeClass('link_blue').addClass('txt_blue');
		$('#lc_scientists').removeClass('link_blue').addClass('txt_blue');
		$('#lc_board').removeClass('txt_blue').addClass('link_blue');
		
	});
	$('#lc_scientists').click(function(event){
		event.preventDefault();
		$('#scientists_block').show();
		$('#board_block').hide();
		$('#management_block').hide();
		$('#lc_management').removeClass('link_blue').addClass('txt_blue');
		$('#lc_board').removeClass('link_blue').addClass('txt_blue');
		$('#lc_scientists').removeClass('txt_blue').addClass('link_blue');
		
	});
});

function mediaVideo(videoId,statusCount){
	//alert(videoId);
	tb_show("","#TB_inline?height=330&amp;width=522&amp;inlineId=featured-media"+statusCount+"&amp;modal=false",null);
	
			flowplayer(videoId,{src:"http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", wmode: 'opaque'},{ 
				
				  clip: {
				autoPlay:true,
				 autoBuffering:true,
				 bufferLength:1} ,
				 
				 plugins: {
	controls: {
		
		// which buttons are visible and which are not?
		play:true,
		volume:false,
		mute:false,
		time:false,
		stop:false,
		playlist:false,
		fullscreen:true,

		// scrubber is a well-known nickname for the timeline/playhead combination
		scrubber: true

		// you can also use the "all" flag to disable/enable all controls
	}
}
	
	});
			$('#'+videoId).css({'display':'block !important'});
			
}

