// First of all, make sure prototype framework is included
 if(!(window.Prototype && window.Prototype.Version)){
 	document.write('<script type=\"text/javascript\" src=\"/scripts/prototype-1.6.0.3.js\"></script>');
 }
 
 // CONSTANT: this is the array keys used in the PHP CIS_Customer class that needs to create or update an customer record based on an array
 var customerAttribNames = new Array(
								 	'customer_id',
								 	'title',
								 	'first_name',
								 	'family_name',
								 	'street1',
								 	'street2',
								 	'suburb',
								 	'state',
								 	'postcode',
								 	'country',
								 	'phone_home',
								 	'phone_work',
								 	'phone_mobile',
								 	'fax',
								 	'email',
								 	'gender',
								 	'dob',
								 	'mail_consent',
								 	'email_consent',
								 	'passport_no',
								 	'last_update'
 								);
 
 // CONSTANT: this is the array keys used in the PHP CIS_CustomerAuthencitation class that needs to create or update an customer authentication record based on an array		
 var customerAuthNames = new Array(
 									'auth_id',
								 	'username',
								 	'password',
								 	'customer_id',
								 	'status',
								 	'last_updated'
 								);
 
/*
 * This function goes to the backend and fatch all CIS mailling list in an associative array
 * array(event_id => event_typename);
 * if addtional arguments is passed as true. only active mailling list will be fatched back 
 */						
function getCISSubs(){
	var postStr = '';
	var retVal = '';
	if(arguments[1] == true){
		var postStr = 'active_only=true';
	}
	new Ajax.Request("/intrepidmembers/scripts/ajax/get_cis_subs.php",{ method: 'post',
					parameters: postStr,
					asynchronous: false, // have to make the call synchronous, otherwise it will return the retVal as its default value (pain in the ass)
					onFailure: function(){ retVal=false;},
					onSuccess: function(request){
					 	retVal = request.responseText.evalJSON(true);
					 	}
					});
	return retVal;
}

 /*
  * simple ajax call that insert/update an cusotmer into the DB
  * parameter:
  * customerAttributes - an associatve array key by customer attributes name defined in constant customerAttribNames and valued by the actual value(string)
  * return: true or false
  */
function saveCustomer(customerAttributes){
	var retVal = [false,"System Error"];
	var attribStr = Object.toJSON(customerAttributes);
	var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/update_customer.php",{ method: 'post',
					parameters: 'customerStr='+attribStr,
					asynchronous: false,
					onFailure: function(){ retVal=false;},
					onSuccess: function(request){
					 	retVal = eval(request.responseText);
					 	}
					});
	return retVal;
}

 /*
  * simple ajax call that insert/update an cusotmer authentication record into the DB
  * parameter:
  * authAttributes - an associatve array key by customer authentication name defined in constant customerAuthNames and valued by the actual value(string)
  * dbUsername,dbPassword,oldPassword - are passed for authentication
  * return: true or false
  */
function saveAuth(authAttributes,oldPassword){
	var attribStr = Object.toJSON(authAttributes);
	var retVal = [false,"System Error"];
	var oldPasswordBit = '';
	if(oldPassword){
		oldPasswordBit = '&old_password='+escape(oldPassword);
	}
	var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/update_auth.php",{ method: 'post',
					parameters: 'authStr='+attribStr+oldPasswordBit,
					asynchronous: false,
					onFailure: function(){ retVal=false;},
					onSuccess: function(request){
					 	retVal = eval(request.responseText);
					 	}
					});
	return retVal;
}

 /*
  * simple ajax call that insert/update an customer_event subscription record into the DB
  * parameter:
  * customer_id - identify which customer the subscritpion events belong to
  * customerSubsStatus - an associatve array key by event_id and valued by the status(string)
  * return: true or false
  */
function saveSubscriptionStatus(customer_id,customerSubsStatus,unsubReasons){
	 var subStatusStr = Object.toJSON(customerSubsStatus);
	 var unsubReasonsBit = '';
	 if(unsubReasons){
	 	var unsubReasonStr = Object.toJSON(unsubReasons);
		unsubReasonsBit = '&unsub_reasons='+unsubReasonStr;
	 }
	 
	 var retVal = false;
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/save_subs.php",{ method: 'post',
				parameters: 'sub_status='+subStatusStr+'&customer_id='+customer_id+unsubReasonsBit,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}

/*
 * simple ajax call that insert/update an customer_event Brochure request record into the DB
 * parameter:
 * customer_id - identify which customer the subscritpion events belong to
 * brox1, brox2 are the cis brochure event id
 * return: true or false
 */
function saveBroxRequest(customer_id, brox1, brox2){
	 var retVal = false;
	 var postStr = 'customer_id='+customer_id+'&brox1='+brox1+'&brox2='+brox2
	 if(!brox2){
	 	postStr = 'customer_id='+customer_id+'&brox1='+brox1;
	 }
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/save_brox_request.php",{ method: 'post',
				parameters: postStr,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}


 /*
  * simple ajax call that insert/update customer enquiry event into DB and send the enquiry to the store
  * parameter:
  * customer_id - identify which customer the subscritpion events belong to
  * enq - details of the enquiries
  * contact - prefered contact method
  * return: true or false
  */
function saveSendEnquiry(customer_id,enq,contact){
	 var retVal = false;
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/save_send_enquiry.php",{ method: 'post',
				parameters: 'customer_id='+customer_id+'&enq='+enq+'&contact='+contact,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}

 /*
  * simple ajax call that insert/update customer travel preference pesudo event into DB
  * parameter:
  * customer_id - identify which customer the travel preference events belong to
  * prefArr - array keyed by preference question, valued by preference answer
  * return: true or false
  */
function saveTravelPref(customer_id,prefArr){
	 var retVal = false;
	 var prefStr = Object.toJSON(prefArr);
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/save_travel_pref.php",{ method: 'post',
				parameters: 'pref_str='+prefStr+'&customer_id='+customer_id,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}


 /*
  * simple ajax call that insert/update customer soe pesudo event into DB
  * parameter:
  * customer_id - identify which customer the soe event belongs to
  * soe - source of enquiry upon first contact
  * return: true or false
  */
function saveSoe(customer_id,soe){
	 var retVal = false;
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/save_soe.php",{ method: 'post',
				parameters: 'customer_id='+customer_id+'&soe='+soe,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}

 /*
  * simple ajax call that set the client country which will drop the correct _INT_CURRENCY and _INT_COUNTRY cookie
  */
function setClientCountry(country){
	 var httpObj = new Ajax.Request("/includes/country/setCountry.php",{ method: 'post',
				parameters: 'country='+country+'&setCountry=true',
				asynchronous: false
				});
}

 /*
  * simple ajax call that register an customer, which involves insert/update customer 
  * record in customer table and insert Authentcation detail in authentication table
  * parameter:
  * customerAttributes - an associatve array key by customer attributes name defined in constant customerAttribNames 
  *                      and valued by the actual value(string)
  * authAttributes - an associatve array key by customer authentication name defined in constant customerAuthNames 
  *                      and valued by the actual value(string)
  * return: true or false
  */
function registerCustomer(authAttributes,customerAttributes){
	 var authStr = Object.toJSON(authAttributes);
	 var custStr = Object.toJSON(customerAttributes);
	 var retVal = false;
	 	
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/register_customer.php",{ method: 'post',
				parameters: 'auth_str='+authStr+'&cust_str='+custStr,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}


 /*
  * simple ajax call that reset a password for an customer
  * parameter:
  * username - username in auth table
  * return: [true,'message'] or [false, 'message']
  */
function resetPassword(username){
	 var retVal = false;
	 	
	 var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/reset_n_send_password.php",{ method: 'post',
				parameters: 'username='+username,
				asynchronous: false,
				onFailure: function(){retVal=false;},
				onComplete: function(request){
					retVal = eval(request.responseText);
					}
				});
	return retVal;
}

/*
 * This function authtenticate a CIS customer.
 * param username, password
 * param passwordHashed. set to true if the password passed to this function is sha1 hashed
 * param validateOnly set to true if only validating the credentials stored in the cookie
 * param persistent, set to true if user require persistent login
 * return [true, {customer profile in object literal notation}] upon success
 * return [false,error message] upon failure
 */
function cisAuthenticate(username,password,passwordHashed,validateOnly,persistent){
   	var postStr = 'username='+escape(username)+'&password='+escape(password)+'&loose=true';
    if(passwordHashed){
    	postStr += '&passwordHashed='+passwordHashed;
    }
    if(validateOnly){
    	postStr += '&validate_only='+validateOnly;
    }
    if(persistent){
    	postStr += '&persistent='+persistent;
    }
    	
    var retVal;
	var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/authenticate.php",{ 
					method: 'post',
					parameters: postStr,
					asynchronous: false,
					onFailure: function(){ retVal=[false];},
					onSuccess: function(request){
					 	retVal = eval(request.responseText);
					 }
				});
	return retVal;
}
    
function cisLogout(){
    var retVal;
    var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/logout.php",{ 
		asynchronous: false,
		onFailure: function(){ retVal=[false];},
		onSuccess: function(request){
			retVal = eval(request.responseText);
		}
	});
	return retVal;
}


/*
 * This function maps the current customer detail defined on the page to an formatted associative array
 * array(attribute_name => attribute_value) and return it
 * parameter: customerHTMLElements - an array of html elements that represents the customer attributes
 */
function mapCustomerDetails(customerHTMLElements){
	var retArr = new Object();
	customerHTMLElements.each(function(e){
		for(var j in customerAttribNames){
			if(e.name == customerAttribNames[j]){
				if(e.type == 'radio' || e.type == 'checkbox'){
					if(e.checked){
						retArr[e.name] = $F(e); 
					}
				}else{
					retArr[e.name] = $F(e).replace(/[#%?&]/g, " "); // replace special characters as they will corrupt the object literal string
					/* an IE8 bug at the time (2010-02-26). refers to http://blogs.msdn.com/jscript/archive/2009/06/23/serializing-the-value-of-empty-dom-elements-using-native-json-in-ie8.aspx */
					if($F(e) == 'null'){
						retArr[e.name] = null;
					}
				}
			}
		}
	});
	
	return retArr;
}

/*
 * This function maps the current subscription status defined on the page to an formatted associative array
 * array(event_id => status) and return it
 * parameter: subsHTMLElements - an array of html elements that represents the subscription status
 * parameter: sTrim,eTrim(optional) - how many char need to be trimmed at the start and end of the name attribute of each elements
 */
function mapSubsStatus(subsHTMLElements, sTrim, eTrim){
	var retArr = new Object();
	if(sTrim == undefined){
		sTrim = 0;
	}
	if(eTrim == undefined){
		eTrim = 0;
	}
	subsHTMLElements.each(function(e){
		var event_id = e.name.substr(sTrim,(e.name.length - eTrim));
		if(e.checked){
			retArr[event_id] = $F(e);
		}
	});
	return retArr;
}

/*
 * This function maps the current unsub reason on the page to an formatted associative array
 * array(event_id => array()) and return it
 * parameter: unsubsReasonHTMLElements - an array of html elements that represents the unsubscribe reason
 * parameter: sTrim,eTrim(optional) - how many char need to be trimmed at the start and end of the name attribute of each elements
 */
function mapUnsubReasons(unsubsReasonHTMLElements, sTrim, eTrim){
	var retArr = new Object();
	if(sTrim == undefined){
		sTrim = 0;
	}
	if(eTrim == undefined){
		eTrim = 0;
	}
	unsubsReasonHTMLElements.each(function(e){
		var event_id = e.name.substr(sTrim,(e.name.length - eTrim));
		if(e.checked){
			if(retArr[event_id] == undefined){
				retArr[event_id] = [];
			}
			retArr[event_id].push($F(e));
		}
	});
	return retArr;
}

/*
 * This function maps the current authentication defined on the page to an formatted associative array
 * array(event_id => status) and return it
 * parameter: authHTMLElements - an array of html elements that represents the authentication detail
 */
function mapAuthStatus(authHTMLElements){
	var retArr = new Object();
	
	authHTMLElements.each(function(e){
		for(var j in customerAuthNames){
			if(e.name == customerAuthNames[j]){
				retArr[e.name] = escape($F(e));
			}
		}
	});
	return retArr;
}


/* -------------- Utility functions ----------------- */

// validate the customer object against the minimum data requirement
function hasCustomerMinData(){
	var valid = true;
	
	 //CONST: minimum data requirement for customer
	 function minData(){
	 	this.required=['first_name','family_name','street1','email','dob_day','dob_month','dob_year'];
	 	this.atLeastOneGrp_1=['suburb','state','postcode'];
	 	this.atLeastOneGrp_2=['genderfemale','gendermale'];
	 }
	 
	 var minDataReq = new minData();

	$$('.validation_msg').each(function(e){
		e.style.display = 'none';
	});
	
	// bloody IE hack to get_around duplicate "country" id
	$$('.cis_country').each(function(e){
		if(!$F(e)){
			valid = false;
			e.style.background = '#FFDDCC';
			e.enable();
			e.focus();
			e.siblings().each(function(x){
				if(x.hasClassName('validation_msg')){
					x.style.display='inline';
				}
			});
		}else{
			e.style.background = '';
		}
	});

	for(var i in minDataReq.required){
		if(typeof(minDataReq.required[i]) == 'string'){
			if(!$F($(minDataReq.required[i]))){
				valid = false;
				$(minDataReq.required[i]).siblings().each(function(e){
					if(e.hasClassName('validation_msg')){
						e.style.display='inline';
					}
				});
				$(minDataReq.required[i]).style.background = '#FFDDCC';
				$(minDataReq.required[i]).enable();
				$(minDataReq.required[i]).focus();
			}else{
				$(minDataReq.required[i]).style.background = '';
			}
		}
	}
	
	// validate atLeastOneGrp_1 array
	var grp1Valid = false;
	var grp1ValidMsg;
	for(var i in minDataReq.atLeastOneGrp_1){
		if(typeof(minDataReq.atLeastOneGrp_1[i]) == 'string'){
			if(!$F($(minDataReq.atLeastOneGrp_1[i])) && grp1Valid == false){
				$(minDataReq.atLeastOneGrp_1[i]).siblings().each(function(e){
					if(e.hasClassName('validation_msg')){
						grp1ValidMsg = e;
					}
				});
			}else{
				grp1Valid = true;
			}
		}
	}
	// hacky piece of code that fix the highlight problem
	for(var i in minDataReq.atLeastOneGrp_1){
		if(typeof(minDataReq.atLeastOneGrp_1[i]) == 'string'){
			if(grp1Valid){
				$(minDataReq.atLeastOneGrp_1[i]).style.background = '';
			}else{
				grp1ValidMsg.style.display='inline';
				$(minDataReq.atLeastOneGrp_1[i]).style.background = '#FFDDCC';
				$(minDataReq.atLeastOneGrp_1[i]).enable();
				$(minDataReq.atLeastOneGrp_1[i]).focus();
			}
		}
	}
	
	// validate atLeastOneGrp_2 array
	var grp2Valid = false;
	var grp2ValidMsg;
	for(var i in minDataReq.atLeastOneGrp_2){
		if(typeof(minDataReq.atLeastOneGrp_2[i]) == 'string'){
			if($(minDataReq.atLeastOneGrp_2[i]).checked == false && grp2Valid == false){
				$(minDataReq.atLeastOneGrp_2[i]).siblings().each(function(e){
					if(e.hasClassName('validation_msg')){
						grp2ValidMsg = e;
					}
				});
			}else{
				grp2Valid = true;
			}
		}
	}
	if(grp2Valid == false){
		grp2ValidMsg.style.display = 'inline';
	}
	
	if(!grp1Valid || !grp2Valid){
		valid = false;
	}
	return valid;
}

// validate authtication details
function validateAuth(type){
	var required;
	if(type == 'register'){
		required=['username','password','password_2'];
	}else{
		required=['username','old_password'];
	}
	
	$$('.validation_msg_auth').each(function(e){
		e.style.display = 'none';
	});
	
	var valid = true;
	for(var i in required){
		if(typeof(required[i]) == 'string'){
			if(!$F($(required[i]))){
				valid = false;
				$(required[i]).siblings().each(function(e){
					if(e.hasClassName('validation_msg_auth')){
						e.style.display='inline';
					}
				});
				
				// hacky hacky hacky!!!
				if(required[i] == 'old_password'){
					if($('change_password_box')){$('change_password_box').checked = true};
					if($('current_pw_div')){$('current_pw_div').show();}
					if($('new_pw_div')){$('new_pw_div').show();}
					if($('new_pw2_div')){$('new_pw2_div').show();}
				}
				
				$(required[i]).style.background = '#FFDDCC';
				$(required[i]).enable();
				$(required[i]).focus();
			}else{
				$(required[i]).style.background = '';
			}
		}
	}
	
	// check if confirmed password matched
	if($F($('password')) || $F($('password_2'))){
		if($F($('password'))!= $F($('password_2'))){
			$('password_2').style.background = '#FFDDCC';
			$('password').style.background = '#FFDDCC';
			
			if($('change_password_box')){$('change_password_box').checked = true};
			if($('current_pw_div')){$('current_pw_div').show();}
			if($('new_pw_div')){$('new_pw_div').show();}
			if($('new_pw2_div')){$('new_pw2_div').show();}
			$('password_not_match').show();
			$('password').focus();
			valid = false;
		}else{
			$('password_2').style.background = '';
			$('password').style.background = '';
			
			$('password_not_match').hide();
		}
	}
	
	// validate username(email) field
	if(!usernameEmailValidation($F($('username')))){
		$('username').style.background = '#FFDDCC';
		$('username').focus();
		$('username_validaton_msg').show();
		valid = false;
	}else{
		$('username').style.background = '';
		$('username_validaton_msg').hide();
	}
	
	return valid;
}

/* need to improve this function */
function usernameEmailValidation(str){
	return (str.indexOf("@") > 0 && str.indexOf(".") > 0)
}

// check if an object is empty
function isObjectEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

//confirm exist is isPageDirty is defined
function confirmExit(){
      if(typeof isPageDirty == 'function') {
      	if(isPageDirty()){
      		return "You have unsaved changes.";
      	}
      }
}



/*
 * omniture tracking for subscription on subscription page
 * - not tracking unsubscribe
 * - track express weekly and monthly subscription under one event
 */
function trackSubs(subEvents){
	var actionsStr = '';
	var googleAdSubExpress = false;
	var googleAdSubSpecials = false;
	
	for(var i=0; i < subEvents.length; i++){
		// General mailing list (event1)
		if(subEvents[i] == 2763){
			actionsStr += (actionsStr == '' ? 'event1' : ',event1');
			googleAdSubSpecials = true;
		}
		// Express weekly/monthly. should be safe since you can only subscribe to one of them
		if(subEvents[i] == 397 || subEvents[i] == 3472){
			actionsStr += (actionsStr == '' ? 'event5' : ',event5');
			googleAdSubExpress = true;
		}
	}
	// assign all subscribe event to omniture
	s.events = s.events? s.events+','+actionsStr : actionsStr ;
	
	/* Google Ad Conversion */
	if(googleAdSubExpress){
		$('googleAd_express_sub').src = "/sharedcontent/googleAd/track_express_sub.php";
	}
	if(googleAdSubSpecials){
		$('googleAd_specials_sub').src = "/sharedcontent/googleAd/track_specials_sub.php";
	}
}

 /*
 * omniture tracking for subscription upon registration
 * - not tracking unsubscribe
 * - track express weekly and monthly subscription under one event
 */
function trackRegSubs(subEvents){
	var actionsStr = '';
	var googleAdSubExpress = false;
	var googleAdSubSpecials = false;
	
	for(var i in subEvents){
		// General mailing list (event1)
		if(i == 2763){
			actionsStr += (actionsStr == '' ? 'event1' : ',event1');
			googleAdSubSpecials = true;
		}
		// Express weekly/monthly. should be safe since you can only subscribe to one of them
		if(i == 397 || i == 3472){
			actionsStr += (actionsStr == '' ? 'event5' : ',event5');
			googleAdSubExpress = true;
		}
	}
	// assign all subscribe event to omniture, append registration event in the end
	s.events = s.events? s.events+','+actionsStr : actionsStr;
	
	/* Google Ad Conversion */
	if(googleAdSubExpress){
		$('googleAd_express_sub').src = "/sharedcontent/googleAd/track_express_sub.php";
	}
	if(googleAdSubSpecials){
		$('googleAd_specials_sub').src = "/sharedcontent/googleAd/track_specials_sub.php";
	}
}

/*
 * track brochure request in omniture
 */
function trackMailBrox(){
	s.events = s.events? s.events+',event7' : 'event7' ;
	
	/* Google Ad Conversion */
	$('googleAd_brox').src = "/sharedcontent/googleAd/track_brox.php";
}

/*
 * track registration in omniture
 */
function trackRegistration(){
	s.events = s.events? s.events+',event13' : 'event13' ;
}

/* 
 * fire the omniture tracking, global var s need to initialised for this function to work
 */
function fireOmnitureTracking(){
	var s_code=s.t();
	if(s_code){
		document.write(s_code);
	}
}

/*
 * check is username exists in the customer.active_authentications table
 */
function isDupUsername(username){
	var retVal = false;
	if(username){
		var httpObj = new Ajax.Request("/intrepidmembers/scripts/ajax/check_dup_username.php",{ method: 'post',
			parameters: 'username='+username,
			asynchronous: false,
			onFailure: function(){retVal=false;},
			onComplete: function(request){
				retVal = eval(request.responseText);
				}
			});
	}
	return retVal;
}