$(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) {
	if(str == 'Sign up for TRIA Beauty updates')
	{
		alert('Please provide email address');
		return false;
	}
	else if (! email_validate(str)) {
		alert('The provided email address is not valid');
		return false;
	}
	
	return true;
}

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 ($('#shippingAddress2').val()) $('#billingAddress2').attr('value', $('#shippingAddress2').val());
		if ($('#shippingCity').val()) $('#billingCity').attr('value', $('#shippingCity').val());
		if ($('#shippingState').val()) $('#billingState').attr('value', $('#shippingState').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', '');
		$('#billingAddress2').attr('value', '');
		$('#billingCity').attr('value', '');
		$('#billingState').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 = document.getElementById(fid);
	if (ele) str = ele.value;
	
	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(0,2),10)*100 + parseInt(str.substring(3,5),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 valid = "0123456789-";
	var hyphencount = 0;

	if (! name) name = 'zip code';

	if (field.length<5) {
		return "Please enter your 5 digit " + name;
	}
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			return "Invalid characters in your " + 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
 }

