/**
* This script will stop/minimize cases of duplicates caused by 
* multiple clicks or page reloads
* Dependencies: 
*	/support/scripts/cookies.js
*/
//-----------------------Strings
//English
var msg_wait = "Please wait! Your information is being processed.";
var msg_error = "An error has occurred.";
var msg_retry = " Do you want to retry?";
var msg_noretry = " Please try again later.";
var msg_req_generic_err = "Please provide information for all required fields. Thank You!";
//-----------------------Configuration
var maxWait = 10000; //wait for 10 seconds before timing out
// -- No changes required beyond this point
var currentWait = 1000; //millisec
var minWait = 1000;		
var maxRetry=0; //set this to 0 if you want to disable the retry option
var successOnTimeout = false;
var currentRetry=0;
var successCookieName = "rSucc";
var errCookieName = "rErr";
var timeStamp = (new Date()).getTime();
var formObj;
var submitted = false;
var timeOutId;
var frmResults; 
//When there is a group of radio buttons we don't want to test each of them
var skipElements = ""; //keeping a list of elements needs to be ignored
var newBody = "";
// - Validate the fields for required
// - More details will be posted on wiki
function autoValidate(form) {
	for (var i=0;i<form.elements.length;i++) {
		var el = form.elements[i];
		if (el.name && skipElements.indexOf("," + el.name + ",") == -1) {			
			var elValue = getElementValue(form,el.name); 
			var title = getElementTitle(el);
			if (isRequired (el.name) && !elValue) {
				if (!title) {
					alert(msg_req_generic_err);
				}
				else {
					alert("'" + title + "' is required.");
				}
				return false;
			}
			if (elValue && addToBody(el.name)) {
				newBody = newBody + getElementTitle(el) + ":" + elValue + "\n";
			}
		}	
	}
	alert("newBody=" + newBody);
	return true;
}			
// this method should take care of the form submission process
function submitEmailForm(form) {
	formObj = form; //set the global form object
	if (validBrowser()) {
		handlePost();				
	}	
	if (!submitted) {
	  form.submit();
	  //Make sure to disable form elements after posting other wise the browser ignores disabled items
	  handleFormElements(true);
	  return true;	
	}
	else {
		alert(msg_wait); //Wait message in English
	}
	return false;
}

function handlePost() {	
	document.domain = "apple.com"; //this is required to trap errors from the depot/request form
	if (frmResults != null) {
		submitted = true;
		return false;
	}
	//insert a iFrame into the document model
	frmResults = insertHiddenIFrame("frmResults");
	
	var fld = document.createElement("input");
	fld.setAttribute("type","hidden");
	fld.setAttribute("value",timeStamp);	
	fld.setAttribute("name","clientTimeStamp");
	formObj.appendChild(fld);

	formObj.target = "frmResults"; //set the target 	
	if (!cookieExists(successCookieName)) {
		timeOutId = window.setTimeout("checkForCookie()",minWait);			
	}
	else {
		handleSuccess();
	}
}

function handleSuccess() {
	self.window.location.href = formObj.returnurl.value;
}
/*
reason - "timeout" or "serverError"
*/
function handleError(reason) {		
	var retry = null;
	if (timeOutId) {
		window.clearTimeout(timeOutId);
	}
	if (reason == "timeout") {
		if (maxRetry > 0) {
			retry = confirm(msg_error + msg_retry);
		}
		else {
			if (successOnTimeout) {
				handleSuccess();return;
			}
			else {
				alert(msg_error + msg_noretry);
			}
		}
	}else {
		var errors= getErrors(frmResults);
		if ( errors != null  ) {
			alert(errors);
		}
		else { //if we can't get error data from the iFrame just show a generic error message
			alert(msg_error + msg_noretry);
		}
	}
	submitted = false;
	if (frmResults != null) {
		frmResults.parentNode.removeChild(frmResults);
		frmResults = null;
	}
	
	currentWait = minWait; //reset the counter
	handleFormElements(false); //unlock elements	
	if (retry) {
		if (currentRetry < maxRetry) {
			currentRetry++;
			submitEmailForm(formObj);
		}
		else {
			alert(msg_error + msg_noretry);
			currentRetry = 0;
		}
	}	
}

/**
* lock == true will disable all elements , false will do the opposite
*/
function handleFormElements(disable) {
	if (formObj.elements && formObj.elements.length > 0) {
		var len = formObj.elements.length;
		for (var i=0;i<len;i++) {
			try {
				var e = formObj.elements[i];
				var t = e.getAttribute("type");
				if (t!=null) {
					t= t.toUpperCase();
					if (t == "SUBMIT" || t =="BUTTON") {						
						e.disabled=disable;
					}
					else if (t == "TEXT") {
						e.readonly = disable;
					}
				}
			}catch (e) { return;}
		}		
	}
}

function checkForCookie() {				
	if (cookieExists(errCookieName)){
		handleError("serverError"); //the backend server reported error
	}
	else if (cookieExists(successCookieName)){
		handleSuccess();
	}
	else if (currentWait <= maxWait) {
		currentWait += minWait;
		timeOutId = window.setTimeout("checkForCookie()",minWait);
	}
	else {
		handleError("timeout"); 
	}	
}

function cookieExists(cookieName) {
	try {
		var ck = getCookie(cookieName);
		if ( ck == null || ck != timeStamp){
			return false;
		}
		return true;
	}catch (e) {
		return false;
	}
}

function getErrors(iframe){
	try {
		var e =iframe.contentDocument.getElementById("errorItems") ;
		if (e != null && e.childNodes.length > 0 && e.childNodes[0].innerHTML) {			
			return e.childNodes[0].innerHTML.replace(/<BR>/gi,"\n");
		}
	}catch (e) {
		//alert(e);
		return null;
	}	
}

function insertHiddenIFrame(iframeId) {
	if (document.getElementById && document.getElementById("iframeId") != null) {
		return false; //already exists
	}
	var i = document.createElement("iframe");
	i.setAttribute("name",iframeId);
	i.setAttribute("id",iframeId);
	i.setAttribute("class","zero");
	i.setAttribute("height","0");
	i.setAttribute("width","0");
	i.setAttribute("src","");			
	document.documentElement.appendChild(i);
	return i;
}

function validBrowser() {
	var browser = new BrowserDetect();
	if (browser.isDOM1 && !browser.isIEMac) {
		return true;
	}
	return false;
}

function getElementTitle(element) {
	if (!element) return null;
	if (element["title"]) {
		return element["title"];
	}
	else if (element["name"]) {
		return element["name"];
	}
	return null;
}
//Returns null if 
// - text box doesn't have any value
// - drop down selected Index is set to 0
// - radio button group has not checked item
// - check box is not checked
// Pass the form object and the elementName
// Otherwise return the required value for the field
function getElementValue(form,elName) {
	var element = form[elName];
	if (element.length) { //radio button group 
		if (element.options || element.selectedIndex) {
			return (element.selectedIndex > 0 ? (element.options[element.selectedIndex].value)  : null);
		}
		else if (element.length > 0 && element[0]["type"] && (element[0]["type"]).toLowerCase() == "radio" ) { //radio buttons with a common name
			skipElements = "," + elName + ",";
			var rdValue = null;
			for (var i=0;i < element.length; i++) {
				var el = element[i];
				if (el.checked) { 
					rdValue = el.value;
					break;
				}							
			}
			return rdValue; //return for a radio button group
		}
	}
	else {
		var t = element["type"];
		var v = element.value;
		//This is a drop down					
		t = t.toLowerCase();
		if ( (t == "text" || t == "textarea") && !v) {
			return null;				
		}
		else if ( (t =="checkbox" || t == "radio") && !element.checked) {
			return null;
		}
		return v;
	}	
	return null; //just in case no value could be detected
}

function isRequired(elName) {
	if (elName && elName.indexOf("req_") == 0) {
		return true;
	}
	return false;
}

function addToBody(elName) {
	if (elName && elName.lastIndexOf("_addToBody") == (elName.length - 10) ) {
		return true;
	}
	return false;
}
// Browser Detect  v2.1.6
// documentation: http://www.dithered.com/javascript/browser_detect/index.html
// license: http://creativecommons.org/licenses/by/1.0/
// code by Chris Nott (chris[at]dithered[dot]com)


function BrowserDetect() {
   var ua = navigator.userAgent.toLowerCase(); 

   // browser engine name
   this.isGecko       = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
   this.isAppleWebKit = (ua.indexOf('applewebkit') != -1);

   // browser name
   this.isKonqueror   = (ua.indexOf('konqueror') != -1); 
   this.isSafari      = (ua.indexOf('safari') != - 1);
   this.isOmniweb     = (ua.indexOf('omniweb') != - 1);
   this.isOpera       = (ua.indexOf('opera') != -1); 
   this.isIcab        = (ua.indexOf('icab') != -1); 
   this.isAol         = (ua.indexOf('aol') != -1); 
   this.isIE          = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1) ); 
   this.isMozilla     = (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length);
   this.isFirebird    = (ua.indexOf('firebird/') != -1);
   this.isNS          = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && !this.isOpera && !this.isSafari && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
   
   // spoofing and compatible browsers
   this.isIECompatible = ( (ua.indexOf('msie') != -1) && !this.isIE);
   this.isNSCompatible = ( (ua.indexOf('mozilla') != -1) && !this.isNS && !this.isMozilla);
   
   // rendering engine versions
   this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
   this.equivalentMozilla = ( (this.isGecko) ? parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) ) : -1 );
   this.appleWebKitVersion = ( (this.isAppleWebKit) ? parseFloat( ua.substring( ua.indexOf('applewebkit/') + 12) ) : -1 );
   
   // browser version
   this.versionMinor = parseFloat(navigator.appVersion); 
   
   // correct version number
   if (this.isGecko && !this.isMozilla) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('/', ua.indexOf('gecko/') + 6) + 1 ) );
   }
   else if (this.isMozilla) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) );
   }
   else if (this.isIE && this.versionMinor >= 4) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
   }
   else if (this.isKonqueror) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
   }
   else if (this.isSafari) {
      this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('safari/') + 7 ) );
   }
   else if (this.isOmniweb) {
      this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('omniweb/') + 8 ) );
   }
   else if (this.isOpera) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera') + 6 ) );
   }
   else if (this.isIcab) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab') + 5 ) );
   }
   
   this.versionMajor = parseInt(this.versionMinor); 
   
   // dom support
   this.isDOM1 = (document.getElementById);
   this.isDOM2Event = (document.addEventListener && document.removeEventListener);
   
   // css compatibility mode
   this.mode = document.compatMode ? document.compatMode : 'BackCompat';

   // platform
   this.isWin    = (ua.indexOf('win') != -1);
   this.isWin32  = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1) );
   this.isMac    = (ua.indexOf('mac') != -1);
   this.isUnix   = (ua.indexOf('unix') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
   this.isLinux  = (ua.indexOf('linux') != -1);
   
   // specific browser shortcuts
   this.isNS4x = (this.isNS && this.versionMajor == 4);
   this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
   this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
   this.isNS4up = (this.isNS && this.versionMinor >= 4);
   this.isNS6x = (this.isNS && this.versionMajor == 6);
   this.isNS6up = (this.isNS && this.versionMajor >= 6);
   this.isNS7x = (this.isNS && this.versionMajor == 7);
   this.isNS7up = (this.isNS && this.versionMajor >= 7);
   
   this.isIE4x = (this.isIE && this.versionMajor == 4);
   this.isIE4up = (this.isIE && this.versionMajor >= 4);
   this.isIE5x = (this.isIE && this.versionMajor == 5);
   this.isIE55 = (this.isIE && this.versionMinor == 5.5);
   this.isIE5up = (this.isIE && this.versionMajor >= 5);
   this.isIE6x = (this.isIE && this.versionMajor == 6);
   this.isIE6up = (this.isIE && this.versionMajor >= 6);
   
   this.isIE4xMac = (this.isIE4x && this.isMac);
   this.isIEMac = (this.isIE && this.isMac);
}
