// Scriptaculous Toggle
function s_toggle(id,style){
	if (style==1)
	new Effect.toggle(id, 'appear');
	else
	new Effect.toggle(id, 'blind', { duration: 0.5 });
}



function ajax(page, objID, loadObj, getOrPost, str){
	
	// get XMLHttp Object:
	
	var xmlhttp=false; //Clear our fetching variable
	try {
		xmlhttp = new ActiveXObject('Msxml2.XMLHTTP'); //Try the first kind of active x object?
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //Try the second kind of active x object
		} catch (E) {
			xmlhttp = false;
		}
	}
	
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
	}
	
	// Process Ajax:
	obj=document.getElementById(objID); // Object where retrieved content will display.
	
	if (loadObj!=='0') {
		obj.innerHTML='<div id="'+loadObj+'">&nbsp;</div>'; // Start Loading...
	}
	
	var file = '/cp/assets/php/'+page; // Server Page
	
	if (getOrPost == "get"){
		xmlhttp.open('GET', file+str , true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
		
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status == 200) { //Check if it is ready to recieve data
				var content = xmlhttp.responseText; //The content data which has been retrieved ***
				if( content ){ //Make sure there is something in the content variable
					obj.innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
				}
			}
		}
		xmlhttp.send(null); //Nullify the XMLHttpRequest
		
	} else {

		xmlhttp.open('POST', file, true);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status == 200) { //Check if it is ready to recieve data
				var content = xmlhttp.responseText; //The content data which has been retrieved ***
				if( content ){ //Make sure there is something in the content variable
					obj.innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
				}
			}
		}
		xmlhttp.send(str);
	}
}

// Used in submitform() to get form objects
function getformvalues (fobj){
	fobj=document.getElementById(fobj);
	var str='';
	
	// run through list of objects in form and create var string.
	for (var i=0; i<fobj.elements.length; i++){
	
		if (fobj.elements[i].type == 'checkbox'){
		
			if (fobj.elements[i].checked==true){
		
				str += fobj.elements[i].name + '=1&';
			
			} else {
		
				str += fobj.elements[i].name + '=0&';
			
			}
			
		} else {
		
			str += fobj.elements[i].name + '=' + escape(fobj.elements[i].value) + '&';
			
		}
	}
	return str;
}

// Submits form with ajax()
function submitform (page, obj, loadObj, theform){
	var str=getformvalues(theform);
	ajax(page, obj, loadObj, "post", str);
}






// form validation function //
function validate(form) {
	//alert('validating...');
  //alert(form.logged_in.value);
  var first_name = form.first_name.value;
  var last_name = form.last_name.value;
  /*
  var primary_phone = form.primary_phone.value;
  var work_phone = form.work_phone.value;
  var secondary_phone = form.secondary_phone.value;
  var email_check = form.email_check.value;
  */
  
  var email_address = form.email.value;
  
  var cc_number = form.cc_number.value;
  var cc_exp_month = form.cc_exp_month.value;
  var cc_exp_year = form.cc_exp_year.value;
  var cc_code = form.cc_code.value;
  var bill_address = form.bill_address.value;
  var bill_city = form.bill_city.value;
  var bill_state = form.bill_state.value;
  var bill_zip = form.bill_zip.value;
  var ship_address = form.ship_address.value;
  var ship_city = form.ship_city.value;
  var ship_state = form.ship_state.value;
  var ship_zip = form.ship_zip.value;
  
  
  if (form.logged_in.value=='0'){

	  //alert('form.username_exists.value: '+form.username_exists.value);
  		var username = form.username.value;
  		var username_exists = form.username_exists.value;
  		var email_exists = form.email_exists.value;
	  var password1 = form.password1.value;
	  var password2 = form.password2.value;
	  //alert('3');
	  var username = form.username.value;

		  
		if(username_exists == '1') {
			inlineMsg('username','Please enter a unique username.',2);
			return false;
		}
		
		if(username == '') {
			inlineMsg('username','Please specify your username.',2);
			return false;
		}
		
		if(email_exists == '1') {
			inlineMsg('email','Please enter a unique email address.',2);
			return false;
		}
		
		if(email_address == '') {
			inlineMsg('email','Please specify your email address.',2);
			return false;
		}
		
		if(password1 != password2) {
			inlineMsg('password1','Your passwords must match.',2);
			return false;
		}
		
		if(password1 == "") {
			inlineMsg('password1','Please specify your password.',2);
			return false;
		}
		
		if(password1.length < 4) {
			inlineMsg('password1','Your password must be at least 4 characters long.',2);
			return false;
		}
  
  }
  
  
 // var email = form.email.value;
  //var gender = form.gender.value;
 // var message = form.message.value;
 // var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
  var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
 // var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
  if(first_name == "" || first_name == "First Name") {
    inlineMsg('first_name','Please enter your first name.',2);
    return false;
  }
  if(last_name == "" || last_name == "Last Name") {
    inlineMsg('last_name','Please enter your last name.',2);
    return false;
  }
    
  if(email_address == "") {
    inlineMsg('email','Please enter your email address.',2);
    return false;
  }
  
  if(!email_address.match(emailRegex)) {
    inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',2);
    return false;
  }
  
  
  if(ship_address == "") {
    inlineMsg('ship_address','Please enter your shipping address.',2);
    return false;
  }  
  
  if(ship_city == "") {
    inlineMsg('ship_city','Please enter your shipping city.',2);
    return false;
  }  
  
  if(ship_state == "") {
    inlineMsg('ship_state','Please enter your shipping state.',2);
    return false;
  }  
  
  if(ship_zip == "") {
    inlineMsg('ship_zip','Please enter your shipping zip code.',2);
    return false;
  }  
  
  
  
  if(bill_address == "") {
    inlineMsg('bill_address','Please enter your billing address.',2);
    return false;
  }  
  
  if(bill_city == "") {
    inlineMsg('bill_city','Please enter your billing city.',2);
    return false;
  }  
  
  if(bill_state == "") {
    inlineMsg('bill_state','Please enter your billing state.',2);
    return false;
  }  
  
  if(bill_zip == "") {
    inlineMsg('bill_zip','Please enter your billing zip code.',2);
    return false;
  }  
  
  
  if(cc_number == "") {
    inlineMsg('cc_number','Please enter your credit card number.',2);
    return false;
  }
  
  
  if(cc_exp_month == "") {
    inlineMsg('cc_exp_month','Please enter your expiration date (Month).',2);
    return false;
  }
  
  
  if(cc_exp_year == "") {
    inlineMsg('cc_exp_year','Please enter your expiration date (Year).',2);
    return false;
  }
  
  
  if(cc_code == "") {
    inlineMsg('cc_code','Please enter the verification code usually found on the back of your card.',2);
    return false;
  }
  
    
  /*
  if(!name.match(nameRegex)) {
    inlineMsg('name','You have entered an invalid name.',2);
    return false;
  }
  if(email == "") {
    inlineMsg('email','Please enter your email.',2);
    return false;
  }
  if(phone == "") {
    inlineMsg('phone','Please enter your phone number.',2);
    return false;
  }
  if(!checkInternationalPhone(phone)) {
    inlineMsg('phone','<strong>Error</strong><br />You have entered an invalid phone number.',2);
    return false;
  }
  /*
  if(gender == "") {
    inlineMsg('gender','<strong>Error</strong><br />You must select your gender.',2);
    return false;
  }
  */
  /*
  if(message == "") {
    inlineMsg('message','You must enter a message.');
    return false;
  }
  if(message.match(messageRegex)) {
    inlineMsg('message','You have entered an invalid message.');
    return false;
  }
  */
  return true;
}




// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// fade the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "images/msg_arrow.gif"; 
}



/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

// 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 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(strPhone.indexOf("+")>1) return false
if(strPhone.indexOf("-")!=-1)bracket=bracket+1
if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
var brchr=strPhone.indexOf("(")
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}




function checkEmail(email){


	ajax('ajax.php', 'emailCheck', '', 'post', 'checkEmail=1&email='+email);


}

