
var accountInfo = {};
var requiredInfo = ['email-address','firstname','lastname','street-address','city','postcode','country','telephone'];
var requiredBillingInfo = ['bill_firstname','bill_lastname','bill_street-address','bill_city','bill_postcode','bill_country'];

var accountCreated = 0;

var timeOutErrorMsg= "Thank you for your patience.<br><br>We are experiencing some network connectivity issues.<br><br>Please wait a moment and click the \"Place Your Order\" button again. By doing so, you are not placing an additional order.<br><br>You will receive an order confirmation number, only after your order has been accepted by our system.<br><br>If you continue to have problems, please order by phone, or email us at: info@jumpsnap.com ";

//we want to lock the checkout button so that people can't checkout while we are still processing info
var checkoutLockCount = 0;

/**
 * Desc: Simple locking, so the usere can't checkout while stuff is still being processed.
 *
 * @param bool lock=true|false
 * @return none 
 * @uses checkoutLock(1); do some stuf ; checkoutLock(0);
 * @author   23-Apr-2007, YDL: 
 */
function checkoutLock(lock){
//lock= true|false
     if (lock){
	  checkoutLockCount = checkoutLockCount + 1 ;
     }
     else  checkoutLockCount = checkoutLockCount - 1 ;
     if (checkoutLockCount > 0){
	  //lock it up
	  $('continueButton').style.display='none';
	  $('continueButtonWait').style.display='';
     }
     else{
	  checkoutLockCount = 0 ;
	  $('continueButtonWait').style.display='none';	  
	  $('continueButton').style.display='';
     }
	  
     
}



function accountCreateSuccess(transport){
	var response = transport.responseText || "no response text";
	//      alert("Success! [create_account]\n\n" + response);
	$('error-output').innerHTML=transport.responseText; //do this no mater what 
	if(!(transport.responseText)){
		accountCreated = 1;
		getShippingQuotes();
		processShipping(); // make sure that we always have a shipping method selected
	} else {
		accountCreated = 0; 
		$('error-output').innerHTML=transport.responseText;
		$('error-output').focus();
		Element.scrollTo('error-output');
	}
	checkoutLock(0);
}



function getAccountGender(){


    if($F('gender-male')){

      gender = $F('gender-male');

    } else {
      gender = $F('gender-female');
    }

   

return gender;

}



function getBillingAccountGender(){


    if($F('bill_gender-male')){

      gender = $F('bill_gender-male');

    } else {
      gender = $F('bill_gender-female');
    }

   

return gender;

}





function clearBillingAccountGender(){


      $('bill_gender-male').value = "";
      $('bill_gender-female').value = "";

}


function setBillingAccountGender(){


      $('bill_gender-male').value = "m";
      $('bill_gender-female').value = "f";

}






function getAccountStatePair(){


    if($F('stateZone')){

      statePair = '&zone_id=' + $F('stateZone');

    } else {
      statePair = '&state=' + $F('state');
    }

   

return statePair;

}



function getBillingAccountStatePair(){


    if($F('bill_stateZone')){

      statePair = '&zone_id=' + $F('bill_stateZone');

    } else {
      statePair = '&state=' + $F('bill_state');
    }

   

return statePair;

}

function clearBillingAccountStatePair(){


      $('bill_stateZone').value = "";

      $('bill_state').value = "";


}



function requestAccountCreate(){
	// subbmit more info to intellicontact, we need to unpop..
	popped=false;
	//joinPopUp();

    gender = getAccountGender();
    statePair = getAccountStatePair();

    checkoutLock(1);
new Ajax.Request('index.php?main_page=ajax'

, { 

method:'post', 
parameters:'&rs=create_account' 
+ "&email_address=" + $F('email-address') 
+ "&gender=" + gender 
+ "&firstname=" + $F('firstname') 
+ "&lastname=" + $F('lastname') 
+ "&street_address=" + $F('street-address') 
+ "&city=" + $F('city') 
+ statePair
+ "&postcode=" + $F('postcode') 
+ "&country=" + $F('country') 
+ "&telephone=" + $F('telephone') 
+ "&password=" + $F('password-new') 
+ "&confirmation=" + $F('password-confirm') 
+ "&company=" + $F('company') 
+ "&suburb=" + $F('suburb') 
+ "&zone_country_id=" + $F('country') 
+ "&email_format=HTML" 
+ "&action=process" 
,

			 onSuccess:  accountCreateSuccess,
			   onFailure: function(){ alert('create_account failed'); checkoutLock(0); }

});




}



function requestAccountUpdate(){
    gender = getAccountGender();
    statePair = getAccountStatePair();
    checkoutLock(1);
    new Ajax.Request('index.php?main_page=ajax'


, {

method:'post',
parameters:'&rs=change_address' 
+ "&email_address=" + $F('email-address') 
+ "&gender=" + gender 
+ "&firstname=" + $F('firstname') 
+ "&lastname=" + $F('lastname') 
+ "&street_address=" + $F('street-address') 
+ "&city=" + $F('city') 
+ statePair
+ "&postcode=" + $F('postcode') 
+ "&country=" + $F('country') 
+ "&telephone=" + $F('telephone') 
+ "&password=" + $F('password-new')
+ "&confirmation=" + $F('password-confirm')
+ "&company=" + $F('company')
+ "&suburb=" + $F('suburb')
+ "&zone_country_id=" + $F('country')
+ "&email_format=HTML"
+ "&addressType=sendto"
+ "&action=process"
			       + "&shippingSame="+ $F('shippingSame') // we neeed to know if we are duplicating the info here or not
,
			     
			onSuccess: accountCreateSuccess,
			       onFailure: function(){ alert('change_address failed') ;
			       checkoutLock(0);}
			 
		     });
                       


}


function requestBillingAccountUpdate(){

    gender = getBillingAccountGender();
    statePair = getBillingAccountStatePair();

    checkoutLock(1);
new Ajax.Request('index.php?main_page=ajax'


, {

method:'post',
parameters:'&rs=change_address' 
//+ "&email_address=" + $F('email-address') 
+ "&gender=" + gender 
+ "&firstname=" + $F('bill_firstname') 
+ "&lastname=" + $F('bill_lastname') 
+ "&street_address=" + $F('bill_street-address') 
+ "&city=" + $F('bill_city') 
+ statePair
+ "&postcode=" + $F('bill_postcode') 
+ "&country=" + $F('bill_country') 
//+ "&telephone=" + $F('bill_telephone') 
//+ "&password=" + $F('password-new')
//+ "&confirmation=" + $F('password-confirm')
+ "&company=" + $F('bill_company')
+ "&suburb=" + $F('bill_suburb')
+ "&zone_country_id=" + $F('bill_country')
//+ "&email_format=HTML"
+ "&addressType=billto"
+ "&action=process"
,

onSuccess: accountCreateSuccess,
			   onFailure: function(){ alert('change_address failed') ; checkoutLock(0); }

});
                       


}



function clearBillingFields(){
//alert("inside clear billing");

clearBillingAccountGender();
clearBillingAccountStatePair();

$('bill_firstname').value = "";
$('bill_lastname').value = "";
$('bill_street-address').value = "";
$('bill_city').value = "";
$('bill_postcode').value = "";
$('bill_country').value = "";
$('bill_company').value = "";
$('bill_suburb').value = "";
$('bill_country').value = "";
$('bill_telephone').value = "";

}



function setAccountDetail(label, value)
{
	//alert(label);
	//alert(value);
    accountInfo[label] = value;
    missingField = 0;
    
    requiredInfo.each(function(reqdLabel){ 
			  //alert("testing : " + reqdLabel);
			  if($F(reqdLabel)){
			      //alert(reqdLabel + " found");
			  } else {
			      // alert(reqdLabel + " not found");
			      missingField = 1;

			  }
			  
		      });

    //alert("missingField = " + missingField + "\n" + filledFields.inspect());
  
  
  if(!($F('state')) && !($F('stateZone'))){
  
      missingField = 1;
      
  } 
   
  if(accountCreated == 0){
      if(missingField == 0 ){
	  requestAccountCreate();
      }  
  } else { // if the account is created then we should
            requestAccountUpdate();
  }
}


function setBillingAccountDetail(label, value)
{
//alert(label);
//alert(value);
accountInfo[label] = value;
missingField = 0;

requiredBillingInfo.each(function(reqdLabel){ 
//alert("testing : " + reqdLabel);
 if($F(reqdLabel)){
 //alert(reqdLabel + " found");
 } else {
// alert(reqdLabel + " not found");
 missingField = 1;

 }

});

//alert("missingField = " + missingField + "\n" + filledFields.inspect());


  

if(missingField == 0 ){


//if(accountCreated == 0){

//requestAccountCreate();

//} else {

requestBillingAccountUpdate();


//}

}

}

var checkoutTime=0;
var checkoutTimeInterval=300;
var checkoutTimeMax =  10000; //10 sec
function processCheckout(){
/* 	console.debug("Checking out" , checkoutLockCount); */
	
	//check the easy local stuff first...
	if ( typeof(check_form) =='function'){
		if (check_form() ==false){
			return false ; 
		}
	}

	
    
    
    	
	//start checking the stuff that we need external requests for... 
	$('error-output').innerHTML=('<p>Processing Your Request...</p>');
	
	//check if we are supposed to be locking..
	if (checkoutLockCount > 0){ /// some one said we shouldn't be checkout out... give them some time and then try again..
/* 		console.debug("checkoutTime",checkoutTime); */
		if ((checkoutTime=checkoutTime+checkoutTimeInterval)< checkoutTimeMax ){ //have we timed out ?
			setTimeout("processCheckout()", 300);
		}else{
			$('error-output').innerHTML=('<p>We are sorry, but your request can not be proccessed at this time, please try again later.</p>');
			checkoutTime=0;
		}
		return false;
	}
	checkoutTime=0; /// got out of the recusion loop!
	
	processShipping(); // might need to do this ...
	
	if ((accountCreated != 1 )){
	 //Element.scrollTo('error-output');	
	 $('error-output').innerHTML=('<p>Please verify your e-mail and shipping address and try again.</p>');
	 requestAccountCreate();
	 return false ;  // I hope nothing is leaving garbage in here.
    }
	// do some stuff for payment...
	$('cc_expires').value = document.checkout.cc_expires_month.value + document.checkout.cc_expires_year.value;
		
	var myform = document.forms.checkout;
	Element.extend(myform);
	Form.disable(myform);
	var params = 'rs=checkout_process&'+Form.serialize(myform);
	checkoutLock(1);
	new Ajax.Request('index.php?main_page=ajax_checkout_process',
		      
					 {
		      	evalScripts: true,
				parameters: params,
				onComplete: function(transport){
						   // Unlock every thing
						   Form.enable(myform);
						   checkoutLock(0);
					      },		 
				onSuccess:  function(transport){
					Element.update('error-output',"<p>"+transport.responseText+"</P>");
					//if everything went well, the *responseText* will, submit the form for us now...
					
					errorMsg ='';
					
					//Was there an Error Message wraped in a 'messageToStack' ?
					if (document.getElementById('messageToStack')){
						 errorMsg = document.getElementById('messageToStack').innerHTML;
					}
					
					//IF there was a redirection, try to guess the error from the URL
					if ((errorMsg =='') && document.getElementById('errorUrl')){
						 var errorUrl = (document.getElementById('errorUrl').innerHTML);
						 errorMsg=URLDecode(gup('.*_error',errorUrl));
						 if (errorMsg =='') errorMsg = "<p>There was an error processing your request, please check your information and try again. <!--"+ errorUrl + "--></p>";
					}
					
					//Display the error that we got.
					if(errorMsg!='') $('error-output').innerHTML = "&nbsp;<div class='checkoutErrorInner'>"+ errorMsg + "</div>";
					/* //What is the point of this ?!
					if (transport.responseText != '' ){
						 //we had an error
						 $('error-output').focus();
					}
					else{
						 alert('no error');
					}
					*/
			    }
		      }
		      
	  ); // End of new Ajax.Request ... 
     
     return false;
}

function gup( name ,tmpURL )
{
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  //var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}

function URLDecode(psEncodeString)
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

////******** TIME OUT STUFF *********////

function callInProgress (xmlhttp) {
     switch (xmlhttp.readyState) {
     case 1: case 2: case 3:
	  return true;
	  break;
// Case 4 and 0
     default:
	  return false;
	  break;
     }
}
function showFailureMessage() {
     //$('error-output').innerHTML='uh oh, it looks like the network is down. Try again shortly';
      Element.update('error-output','<div class="timeout-error">'+ timeOutErrorMsg +'</div>');
	  $('error-output').scrollIntoView();
      createCookie('checkoutTimedOut','1',1);
}

// Register global responders that will occur on all AJAX requests
Ajax.Responders.register(
     {
         onCreate: function(request) {
	       request['timeoutId'] = window.setTimeout(
		    function() {
// If we have hit the timeout and the AJAX request is active, abort it and let the user know
			 if (callInProgress(request.transport)) {
			      request.transport.abort();
			      showFailureMessage();
// Run the onFailure method if we set one up when creating the AJAX object
			      if (request.options['onFailure']) {
				   request.options['onFailure'](request.transport, request.json);
			      }
			 }
		    },
		    25000 // 25 seconds
		    );
	  },
	  onComplete: function(request) {
	       try{
		    transportStatusUnavailable = ((request.transport.status  == undefined) || (request.transport.status  == 0));
	       }
	       catch(err){
		    transportStatusUnavailable = true;
	       }
	       if ( transportStatusUnavailable  ){
		    showFailureMessage();
	       }
// Clear the timeout, the request completed ok
	       window.clearTimeout(request['timeoutId']);
	  },
          onFailure: function(request){
	       showFailureMessage();
	  }
	 
     });
