//global init
var clientSideValidation = true;
var currentBanner = Math.floor(4*Math.random()) + 1;
if (currentBanner > 4) {currentBanner = 4;}

function addEvent(obj, evType, fn){
	if (obj.addEventListener){ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

function dBanner() {
	if(document.getElementById('dashBannerContainer') && document.getElementById('dashBanner')){
		var element = document.getElementById('dashBanner');
		var target =  document.getElementById('dashBannerContainer');
		target.innerHTML = element.innerHTML;
		target.style.display = 'block'; 
		target.style.opacity = '1'; 
		resetReg3();
		showDBanner(currentBanner);
	}
}

function showDBanner(p, killTimer) {
	if(killTimer) {
		stopDBanner();
	}
	for (i = 1; i <= 4; i++) {
		if (p != i) {
			$('#dashbanner' + i).addClass('hidden');
		}
	}

	$('#dashbanner' + p).removeClass('hidden');
	
	++currentBanner;
	if (currentBanner > 4) {currentBanner = 1;}
	
	if(!killTimer) {
		dashTimer = setTimeout("showDBanner(currentBanner)",5000);									
	}
}

function stopDBanner() {
	clearTimeout(dashTimer);
}

function hideDBanner() {
	document.getElementById('dashBannerContainer').style.display = 'none';
	document.getElementById('dashBannerContainer').innerHTML = '';
	if (document.getElementById('showFeatured')) {
		document.getElementById('showFeatured').style.display='inline';
		document.getElementById('hideFeatured').style.display='none';
	}
	resetReg3();
}

// ##########################################################################################################
// Form Validation
// ##########################################################################################################


function skipValidation()
{
	clientSideValidation = false;
}

function validateForm(f)  // remaining arguments are validation objects
{

  if( !clientSideValidation )
  	return true;

  for(var n=1;n<arguments.length;n++)
  {
	var d = arguments[n];
	var test = '#' + f.id.replace(/:/g,"\\:") + "\\:" + d.fieldName;
	var field = $('#' + f.id.replace(/:/g,"\\:") + "\\:" + d.fieldName);
	if( field.length == 0 )
		continue;
	var val = field.val();
	
	// Uncomment for testing
	//if( field.length != 1 )
	//{
	//  alert("Unknown or multiple fields: " + d.fieldName + "... skipping"); // dev code only
	//  continue;
	//}
	
	field = field[0];
	
	switch(d.validationType)
	{
		case "isPostalCode":
			if( !val.isBlank() && !val.isPostalCode() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;
		case "isZipCode":
			if( !val.isBlank() && !val.isZipCode() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;
		case "isNumber":
			if( !val.isBlank() && !val.isNumber() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;
		case "isDouble":
			if( !val.isBlank() && !val.isDouble() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;
		case "isRequired":
			if( val.isBlank() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;		
		case "isAlphaNumeric":
			if( !val.isBlank() && !val.isAlphaNumeric() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;		
		case "isSelected":
			if( field.type == "select-one" && field.selectedIndex == 0 )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;
		case "isEmail":
			if( !val.isBlank() && !val.isEmail() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;	
		case "isReferenceNumber":
			if( !val.isBlank() && !val.isReferenceNumber() )
			{
			  throwError(d,f);
			  return false; // do not submit form
			}
			break;	
			
		default:
		    // Uncomment for testing
			//alert("####DEBUG####\n\nUnknown validationType " + d.validationType + " on " + d.fieldName + "\n\nValidation will skip this item"); // dev code only
	}
  }
  return true;
}

function throwError(d,f)
{
	errorAlert(rawunescape(d.errorMessage),'error',f.id + ":" + rawunescape(d.fieldName))
	window.scrollTo(0,0); // reset view
}


// ##########################################################################################################
// END -- Form Validation
// ##########################################################################################################

// ##########################################################################################################
// Error Handling
// ##########################################################################################################


var cachedErrorMessage = "";
var cachedErrorField = undefined;
var cachedErrorType = "";
var cachedSuccessMessage = "";
var cachedSuccessType = "";

function successAlert(message,type) {
	if( type == undefined )
	  type = 'success';
	  
	cachedSuccessMessage = message;
	cachedSuccessType = type;
	_successAlert();
}

function _successAlert() {
	if( cachedSuccessMessage != "" ) {
	  var mainContent = $('#accordion');
	  if( mainContent.length == 0 )
	    mainContent = $('#popupContent');
	  if( mainContent.length == 0  )
	    mainContent = $('#genericContent');
	  if( mainContent.length == 0) 
	  	mainContent = $('.contentHolder:first');
	  if( mainContent.length == 0) 
	  	mainContent = $('#emailResults');
      if( mainContent.length == 0) 
	  	mainContent = $('form');
	  
	  if( mainContent.length > 0 ) {
		clearAlert();
		var html = "<div class='message msgSuccess'><fieldset><p><code><span>*</span></code>" + cachedSuccessMessage + "</p></fieldset></div>";
		mainContent.before(html);
	  }
	}
}

function errorAlert(message,type,field,globalErrorMessage)
{
	if( type == undefined )
	  type = 'success';

	cachedErrorMessage = message;
	cachedErrorField = field;
	cachedErrorType = type;
	cachedGlobalErrorMessage = globalErrorMessage;
	_errorAlert();
}


function _errorAlert()
{
	if( cachedErrorMessage != "" )
	{
	  var mainContent = $('#accordion');
	  if( mainContent.length == 0 )
	    mainContent = $('#popupContent');
	  if( mainContent.length == 0  )
	    mainContent = $('#genericContent');
	  if( mainContent.length == 0) 
	  	mainContent = $('.contentHolder:first');
	  if( mainContent.length == 0) 
	  	mainContent = $('#emailResults');
      if( mainContent.length == 0) 
	  	mainContent = $('form');
	  
	  if( mainContent.length > 0 )
	  {
		clearAlert();
		//var html = "<div class='messageBox " + cachedErrorType + "'>" + rawunescape(cachedErrorMessage) + "</div>";
		var html = "<div class='message msgErr'><fieldset><p><code><span>x</span></code>" + cachedGlobalErrorMessage + "</p></fieldset></div>";
		mainContent.before(html);
		
		if( cachedErrorField != undefined )
		{
			$('#'+cachedErrorField.replace(/:/g,"\\:")).addClass('inputErr');
			$('#'+cachedErrorField.replace(/:/g,"\\:")).after('<div class="blah"><label id="postCodeFieldHelp" class="error" for="postCode"><code class="error"><span>x </span></code>' + rawunescape(cachedErrorMessage) + '</label></div>');
		}
		
		/* Track validation Errors */
		trackClientError(this,cachedErrorField.toLowerCase(),rawunescape(cachedErrorMessage).toLowerCase());
	  }
	  else
	  	alert(cachedErrorType + "\n\n" + rawunescape(cachedErrorMessage)); // should never be called
	}
}

function clearAlert()
{
	$('.message').remove();
	$('.inputErr').removeClass('inputErr');
	$('.blah').remove();
}

// UTILS

function rawunescape(str)
{
  str = str.replace(/\+/g, "%20");
  str = unescape(str);
  return(str);
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

// Helper Functions for Validation, etc

String.prototype.isPostalCode = function()
{
  var pc = this.replace(/ /,"");
  if( pc.search(/^([a-z]\d){3}$/i) == -1 )
    return false;
  else
    return true;
}

String.prototype.isZipCode = function()
{
  var pc = this.replace(/ /,"");
  if( pc.search(/^[0-9]{5}(\-[0-9]{4})?$/i) == -1 )
    return false;
  else
    return true;
}


String.prototype.isBlank = function()
{
	var s = this.replace(/ /g,"");
	if( s == "" )
	  return true;
	else
	return false;
}

String.prototype.isNumber = function()
{
	if( this.search(/^ *\d+ *$/) == -1 )
	  return false;
	else
  	  return true;
}

String.prototype.isDouble = function()
{
	var s = this.replace(/ /g,"");
	if(GLOBALOBJ.locale == 'fr')
		s = s.replace(/\,/g,".");
	var r = Number(s);
	if( r == s )
	  return true;
	else
  	  return false;
}

String.prototype.isAlphaNumeric = function()
{
  s = $.trim(this);
  if( s.search(/^[\da-zA-Z ]+$/) == -1 )
    return false;
  return true;
}

String.prototype.isEmail = function()
{
	if( this.search(/@/) == -1 )
	  return false;
	else
  	  return true;
}

String.prototype.isReferenceNumber = function()
{
	if( this.search(/[\%\*]/) < 0 )
	  return true;
	else
  	  return false;
}


function hideDiv(id)
{
	document.getElementById(id).style.display == 'none';	
}

function showDiv(id)
{
	document.getElementById(id).style.display == '';	
}

// ##########################################################################################################
// Popup Windows
// ##########################################################################################################

var popField = "";
var popWin = null;
var popLink = null;

function popupWin(link,definitionLabel,extraParam,field,winname)
{
  popLink = link;

  if( popWin && !popWin.closed )
    popWin.close();

  popField = field;
  
  if( winname == undefined )
  	winname = "pool_popWin" + Math.floor(Math.random()*10000);

  if( extraParam == undefined )
  	extraParam = "";
  	
  GLOBALOBJ.segment ='personal';
  	
  // Build URL  (popupApp_findacity.pg?portal=personalPopup&_eventName=show_defaultPage)
  url = GLOBALOBJ.contextPath + "/" + definitionLabel + "?" + GLOBALOBJ.segment + "Popup"; // + "&language=" + GLOBALOBJ.locale;
  if( extraParam != "" )
    url += "&" +  extraParam;
  
  popWin = window.open(url,winname,"width=705,height=600,scrollbars=1");
  if( popWin )
	  popWin.focus();
}

function popupWinWithParamArray(link,definitionLabel,extraParam,field,winname)
{
  popLink = link;

  if( popWin && !popWin.closed )
    popWin.close();

  popField = field;
  
  if( winname == undefined )
  	winname = "pool_popWin" + Math.floor(Math.random()*10000);

  if( extraParam == undefined )
  	extraParam = "";
  	
  GLOBALOBJ.segment ='personal';
  	
  // Build URL  (popupApp_findacity.pg?portal=personalPopup&_eventName=show_defaultPage)
  url = GLOBALOBJ.contextPath + "/" + definitionLabel + "?" + GLOBALOBJ.segment + "Popup"; // + "&language=" + GLOBALOBJ.locale;
  
  if( extraParam != undefined ) {
	  for(i=0; i<extraParam.length; i++) { 
		  url += "&" +  extraParam[i];
	  }  
  }
  popWin = window.open(url,winname,"width=705,height=600,scrollbars=1");
  if( popWin )
	  popWin.focus();
}

function paymentPageInit(value) {
	
	if (value=='0')
	{				
	        	$('.creditCardInfoSection').hide();
	        	$('.cvvSection').hide();
				$('.storedBillingAddress').hide();
				$('.newBillingAddress').hide();				
	}
	else if(value=='1'){
        		$('.creditCardInfoSection').hide();
        		$('.cvvSection').show();
				$('.storedBillingAddress').show();
				$('.newBillingAddress').hide();	
	}
	else if(value=='2'){
	        	$('.creditCardInfoSection').show();
	        	$('.cvvSection').hide();
				$('.storedBillingAddress').hide();
				$('.newBillingAddress').show();	
	}
	else{
		        $('.creditCardInfoSection').hide();
		        $('.cvvSection').hide();
				$('.storedBillingAddress').hide();
				$('.newBillingAddress').hide();	
	
	}

}

function popupReturn(val,closewin)
{
  if( !$.browser.safari )
  {
	  window.opener._popupReturn(val);
	  if( closewin == undefined || closewin == true )
		  window.close();
  }
  else
  {
    var msg = "Attention: Safari users.<br/>Due to technical limitations, some functionality is not available.<br/>Please copy and paste displayed result in appropriate field.";
    if( GLOBALOBJ.locale == "fr" ) {
      msg = "Attention : Utilisateurs de Safari.<br/>En raison d'inconv&eacute;nients techniques, certaines fonctionnalit&eacute;s ne sont pas disponibles.<br/>Veuillez copier et coller le r&eacute;sultat dans le champ appropri&eacute;.";
     }
	errorAlert(msg,"warning");
  }
}

function typeOf(value) 
{
    var s = typeof value;
    if (s == 'object') 
    {
        if (value) 
        {
            if (typeof value.length == 'number' && !(value.propertyIsEnumerable('length'))) 
            	s = 'array';
        } 
        else 
            s = 'null';
    }
    return s;
}

function _popupReturn(val)
{
  var f = $(popLink).parents("form");
   
  if( f.length != 1 )
    return;
  f = f[0];
  
  
  if( typeof(val) == "string" )
  {
    $('#' + f.id.replace(/:/g,"\\:") + "\\:" + popField).val(val);
  }
  else if( typeOf(val) == 'array' && typeOf(popField) == 'array'  )
  {
  	for (var i=0; i< val.length; i++)
  		$('#' + f.id.replace(/:/g,"\\:") + "\\:" + popField[i]).val(val[i]);
  }
  else // is an object
  {
	$('#' + f.id.replace(/:/g,"\\:") + "\\:" + popField).val(val);
  }
  // reset
  popField = "";
}



// ##########################################################################################################
// END -- Popup Windows
// ##########################################################################################################

/************************************************************************************************************
 * Auto Scroll functionality - Start																		*
 ***********************************************************************************************************/
function getScrolling() {
	var x = 0;
	var y = 0;
	var enableAutoScroll = document.getElementById("enableAutoScroll");
	if (enableAutoScroll != null && enableAutoScroll.value > 0) {
		if (self.pageXOffset || self.pageYOffset) {
			x = self.pageXOffset;
			y = self.pageYOffset;
		} else if ((document.documentElement && document.documentElement.scrollLeft) || (document.documentElement && document.documentElement.scrollTop)) {
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		} else if (document.body) {
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		}
	}
	return x + "," + y;
}

function applyAutoScroll(component, offsetX, offsetY) {
	var scrollX = document.getElementById('scrollX');
	var scrollY = document.getElementById('scrollY');
	if (component != null) {
		var componentX = 0;
		var componentY = 0;
		while(component != null){
			componentX += component.offsetLeft;
			componentY += component.offsetTop;
    		component = component.offsetParent;
		}
		window.scrollTo(componentX + offsetX, componentY + offsetY);
	} else if (scrollX != null && scrollY != null) {
		window.scrollTo(scrollX.value, scrollY.value);
	}
}
/************************************************************************************************************
 * Auto Scroll functionality - End																			*
 ***********************************************************************************************************/

function bookmarkThisPage(url, title){

            if (navigator.appName == "Microsoft Internet Explorer") {
                if (parseInt(navigator.appVersion) >= 4){
                                    window.external.AddFavorite(url, title);
                        } else {
                                    alert("Internet Explorer 4 or higher needed to use this feature.");
                        }
            } else {
                        if (window.sidebar) { // Mozilla Firefox Bookmark              
							window.sidebar.addPanel(title, url,"");
						}
            } 
}


