/*
 * functions.js - skistays.com main JavaScript
 *
 * Copyright 2007 The Lodging Company
 */

var vpArrivalRE = /(\d+)[-\/](\d+)[-\/](\d+)/;
var is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );

function disclaimerPage(page) {
  var winWidth = 450;
  var winHeight = 50;
  OpenWin = this.open(page, "photoWindow", "top=10,left=10,width="+winWidth+",height="+winHeight+",toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no");
  // Add the following to the <body> in every page that appears in the pop up window
  // onload="self.focus();"
} // end function disclaimerPage

function mapPage(page) {
  var winWidth = 600;
  var winHeight = 480;
  OpenWin = this.open(page, "mapWindow", "top=10,left=10,width="+winWidth+",height="+winHeight+",toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,status=no");
  // Add the following to the <body> in every page that appears in the pop up window
  // onload="self.focus();"
} // end function mapPage

function photoPage(page) {
  var winWidth = 630;		// Start with size for large images,
  var winHeight = 520;		// and it will be resized if a small gallery opens.
  OpenWin = this.open(page, "photoWindow", "top=10,left=10,width="+winWidth+",height="+winHeight+",toolbar=no,menubar=no,location=no,scrollbars=no,resizable=yes,status=no");
  // Add the following to the <body> in every page that appears in the pop up window
  // onload="self.focus();"
} // end function photoPage

function actionTag( action ) {
	var qidx = action.indexOf( '?' );
	var path = action;
	if ( qidx >= 0 ) {
		path = action.substr( 0, qidx );
	}
	var tag = path.split( '/' ).pop();
	if ( path.lastIndexOf( '/' ) == path.length - 1 ) {
		tag = path.substr( 0, path.lastIndexOf( '/' ) ).split( '/' ).pop();
	}
	tag = tag.replace( /[^a-zA-Z0-9_]+/g, '_' );

	//alert( 'actionTag(): action = "' + action + '"; tag = "' + tag + '"' );

	return tag;
}

function popUp( action ) {
	var tag = actionTag( action );
	var height = 584;
	var width = 720;

	// Centre the pop-up within the parent window.
	var browser_top = window.screenY;
	var browser_left = window.screenX;
	var browser_height = window.innerHeight;
	var browser_width = window.innerWidth;
	var top = browser_top + Math.floor( ( browser_height - height ) / 2 );
	var left = browser_left + Math.floor( ( browser_width - width ) / 2 );

	var today = new Date;
	var popupName = "popUpAction_" + tag + today.getTime();

	var newWindow = window.open( action, popupName, "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width + ",toolbar=yes,menubar=yes,location=yes,status=yes,scrollbars=yes,resizable=yes" );
}

function adjustSideBar() {
	var spacerElem = document.getElementById( 'sideplaceholderspacer' );
	var sideBarElem = document.getElementById( 'sidecontent' );

	spacerElem.style.lineHeight = sideBarElem.clientHeight + "px;";
}

function gotoPage( pagename ) {
	document.location.href = '/' + pagename;
}

function gotoURL( url ) {
	document.location.href = url;
}

function galCheckOpener( redirURI ) {
	var redirect = true;
	if ( window.opener )
	{
		// Check path component of opener's location URL for "/.../b".
		var openerLocationPath = window.opener.location.pathname;
		if ( openerLocationPath.match( /\/[A-Za-z0-9_\-,]+\/b/ ) )
		{
			// Got a match--we're OK.
			redirect = false;
		}
	}

	// If there is no opener or it doesn't look like a property page, redirect to the property page.
	if ( redirect )
	{
		window.location.href = redirURI;
		return false;
	}
	else
	{
		return true;
	}
}

function vpSubmit( buildingId ) {
	// Get all the chunks of parameters (except 'p') into a single string.
	var frm = document.getElementById( 'vacationplanner' );
	var param_chunks = new Array();

	// This should be a for loop!  But the language won't allow it.
	param_chunks[ param_chunks.length ] = 'a' + frm.elements['a'].value;
	param_chunks[ param_chunks.length ] = 'c' + frm.elements['c'].value;
	param_chunks[ param_chunks.length ] = 'd' + frm.elements['d'].value;
	param_chunks[ param_chunks.length ] = 'k' + frm.elements['k'].value;
	param_chunks[ param_chunks.length ] = 'l' + frm.elements['l'].value;
	param_chunks[ param_chunks.length ] = 'm' + frm.elements['m'].value;
	param_chunks[ param_chunks.length ] = 'n' + frm.elements['n'].value;
	param_chunks[ param_chunks.length ] = 'r' + frm.elements['r'].value;
	param_chunks[ param_chunks.length ] = 's' + frm.elements['s'].value;
	param_chunks[ param_chunks.length ] = 'y' + frm.elements['y'].value;
	param_chunks[ param_chunks.length ] = 't' + frm.elements['t'].value;
	if ( buildingId && frm.elements['b'].value ) {
		param_chunks[ param_chunks.length ] = 'u' + frm.elements['u'].value;
		param_chunks[ param_chunks.length ] = 'p' + ( frm.elements['p'].value ? frm.elements['p'].value : '1' );
	}

	var params_string = param_chunks.join( '-' );

	var uri;
	if ( buildingId && frm.elements['b'].value ) {
		uri = '/' + params_string + '/b' + buildingId + '_.html';
	}
	else {
		var page = frm.elements['p'].value ? frm.elements['p'].value : '1';
		uri = '/' + params_string + '/p' + page + '_.html';
	}
	window.location.href = uri;
}

function vpResortsChange( frm ) {
	frm.elements['l'].value='';
	frm.elements['p'].value='';
	frm.elements['b'].value='';
	frm.elements['u'].value='';
}

function noItIsNotOctalThankYouVeryMuch( str ) {
	return str.replace( /^0+/, '' );
}

function genericArrivalChange(  datestr, inputYear, inputMonth, inputDay ) {
	var matches = datestr.match( vpArrivalRE );
	inputMonth.value = matches[1];
	inputDay.value = matches[2];
	inputYear.value = matches[3];

	var intYear = parseInt( noItIsNotOctalThankYouVeryMuch( inputYear.value ) );
	if ( intYear < 100 )
	{
		// ...because people still like their 2-digit years.
		// See you again in 2100. ;-)
		intYear += 2000;
		inputYear.value = intYear.toString();
	}
}

function vpArrivalChange( datestr ) {
	var frm = document.getElementById( 'vacationplanner' );
	genericArrivalChange( datestr, frm.y, frm.m, frm.d );
}

// Set current page in the vacation planner, and submit.
function vpSetPage( iPage ) {
	var vp_form = document.getElementById( 'vacationplanner' );
	vp_form.p.value = iPage.toString();
	vpSubmit();
}

function update_sortreverse( ctlReverse ) {
	var vp_form = document.getElementById( 'vacationplanner' );
	var split_re = /./g;
	var splt = vp_form.s.value.match( split_re );
	if ( ctlReverse.checked ) {
		splt[0] = 'D';
	} else {
		splt[0] = 'A';
	}

	vp_form.s.value = splt.join( '' );
	vpSubmit();
}

function update_sortorder( ctlSortOrder ) {
	var vp_form = document.getElementById( 'sortselect' );

	// Return to page 1.
	if ( vp_form.p ) {
		vp_form.p.setAttribute( 'value', '1' );
	}

		if ( vp_form.s ) {
			vp_form.s.setAttribute( 'value', ctlSortOrder.value );
		}
		else {
			var s_inp = document.createElement( 'input' );
			with ( s_inp ) {
			setAttribute( 'type', 'hidden' );
			setAttribute( 'name', 's' );
			setAttribute( 'value', ctlSortOrder.value );
			}
		vp_form.appendChild( s_inp );
		}
	vp_form.submit();
}

function showhideLinkFields( cbox_id, div_id ) {
	var cbox = document.getElementById( cbox_id );
	var div = document.getElementById( div_id );

	if ( cbox.checked ) {
		div.setAttribute( 'class', 'linkfields_shown' );
	}
	else {
		div.setAttribute( 'class', 'linkfields_hidden' );
	}
}

var origColor = [];
function lolightFormElement( elemid ) {
	var cell = document.getElementById( elemid + '_cell' );
	if ( cell ) {
		if ( origColor[ elemid ] ) {
			cell.style.borderColor = origColor[ elemid ];
			origColor[ elemid ] = null;
		}
		else {
			cell.style.borderColor = 'transparent';
		}
	}
}
function hilightFormElement( elemid ) {
	var cell = document.getElementById( elemid + '_cell' );
	if ( cell ) {
		if ( is_ie && !origColor[ elemid ] ) {
			origColor[ elemid ] = cell.currentStyle[ 'borderColor' ];
		}

		cell.style.borderColor = 'red';
	}
}

function isFilled( elemid ) {
	var elem = document.getElementById( elemid );
	if ( !elem || elem.value.length == 0 ) {
		return false;
	}
	else {
		return true;
	}
}

function detailsFormReset() {
	lolightFormElement( 'form_first_name' );
	lolightFormElement( 'form_last_name' );
	lolightFormElement( 'form_phone' );
	lolightFormElement( 'form_alt_phone' );
	lolightFormElement( 'form_country' );
	lolightFormElement( 'form_e_mail' );
}

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)

	if (str.indexOf(at)==-1){
		return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}

	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}

	if (str.indexOf(" ")!=-1){
		return false
	}

	return true
}

function detailsFormSubmit() {
	var valid = true;
	var msg = '';

	if ( !isFilled( 'form_first_name' ) ) {
		msg += 'Please provide a First Name.\n';
		valid = false;
		hilightFormElement( 'form_first_name' );
	}
	else {
		lolightFormElement( 'form_first_name' );
	}

	if ( !isFilled( 'form_last_name' ) ) {
		msg += 'Please provide a Last Name.\n';
		valid = false;
		hilightFormElement( 'form_last_name' );
	}
	else {
		lolightFormElement( 'form_last_name' );
	}

	if ( !isFilled( 'form_phone' ) && !isFilled( 'form_alt_phone' ) ) {
		msg += 'Please provide at least one Phone Number.\n';
		valid = false;
		hilightFormElement( 'form_phone' );
		hilightFormElement( 'form_alt_phone' );
	}
	else {
		lolightFormElement( 'form_phone' );
		lolightFormElement( 'form_alt_phone' );
	}

	if ( document.getElementById( 'form_country' ).value == 0 ) {
		msg += "Please select a Country.\n";
		valid = false;
		hilightFormElement( 'form_country' );
	}
	else {
		lolightFormElement( 'form_country' );
	}

	if ( !isFilled( 'form_e_mail' ) || !echeck( document.getElementById( 'form_e_mail' ).value ) ) {
		msg += "Please provide a valid email address.\n";
		valid = false;
		hilightFormElement( 'form_e_mail' );
	}
	else {
		lolightFormElement( 'form_e_mail' );
	}

	if ( msg.length > 0 ) {
		alert( msg );
	}
	return valid;
}

function addEvent( node, event, func ) {
	if ( node.attachEvent ) { // IE
		node.attachEvent( "on" + event, func );
	}
	else if ( node.addEventListener ) { // Gecko / W3C
		node.addEventListener( event, func, true );
	}
	else {
		node[ "on" + event ] = func;
	}
}

function rmvEvent( node, event, func ) {
	if ( node.detachEvent ) { // IE
		node.detachEvent( "on" + event, func );
	}
	else if ( node.removeEventListener ) { // Gecko / W3C
		node.removeEventListener( event, func, true );
	}
	else {
		node[ "on" + event ] = null;
	}
}

function vpAdvSearchClick() {
	var frm = document.getElementById( 'vacationplanner' );
	frm.setAttribute( 'action', '/advsearch' );
	frm.submit();
}

function vpAddAdvSearchLink( parentid ) {
	var parent = document.getElementById( parentid );

	if ( !parent ) {
		alert( 'Advanced search link is unavailable.' );
		return;
	}

	var link = document.createElement( 'span' );
	link.appendChild( document.createTextNode( '>> Advanced Search' ) );
	addEvent( link, 'click', vpAdvSearchClick );
	parent.appendChild( link );
}

function changeDatesShow( popid ) {
	var popup = document.getElementById( popid );

	if ( popup && popup.style ) {
		popup.style.visibility = 'visible';
		popup.style.display = 'block';
	}
	else {
		alert( 'No popup, "' + popid + '"' );
	}
}

function changeDatesApply( popid, formid, dateid, nightsid ) {
	var popup = document.getElementById( popid );
	var date = document.getElementById( dateid );
	var nights = document.getElementById( nightsid );
	var planner = document.getElementById( 'vacationplanner' );

	if ( planner ) {
		if ( date && nights ) {
			planner.elements['date'].value = date.value;
			planner.elements['n'].value = nights.value;

			if ( popup && popup.style ) {
				popup.style.visibility = 'hidden';
				popup.style.display = 'none';
			}
			else {
				alert( 'No popup, "' + popid + '"' );
			}

			planner.submit();
		}
		else {
			alert( 'No date, "' + dateid + '", or nights, "' + nightsid + '"' );
		}
	}
	else {
		alert( 'No planner, "' + 'vacationplanner' + '"' );
	}
}

function changeDatesCancel( popid, formid ) {
	var popup = document.getElementById( popid );
	var frm = document.getElementById( formid );

	if ( popup && popup.style ) {
		popup.style.visibility = 'hidden';
		popup.style.display = 'none';
	}
	else {
		alert( 'No popup, "' + popid + '"' );
	}

	if ( frm ) {
		frm.reset();
	}
	else {
		alert( 'No popup, "' + popid + '"' );
	}
}

