
// From toggle.js

/** Toggle Functions
  * Helper functions to toggle visibility and/or images.  
  * Toggling is fun!
  * @author verysimple, inc. <www.verysimple.com>
  */

/** Toggles the visibility of the given tag
  * @param tagid the id of the dom item to toggle
  * @return void
  */
function toggle(tagid)
{
	var divtag = getDiv(tagid);
	
	divtag.style.display = (divtag.style.display == 'none') ? '' : 'none';

}

/** Toggles an image between two graphics
  * @param tagid the id of the dom item to toggle
  * @param url1 first of the two image rls being toggled
  * @param url2 second of the two image rls being toggled
  * @return void
  */
function toggleImage(tagid,url1,url2)
{
	var img = getDiv(tagid);
	
	// we have to get the end of the scr string because the browser may
	// report back to us the full url & we won't get a match
	if (img.src.substr(img.src.length-url1.length,url1.length) == url1)
	{
	    img.src = url2;
	}
	else
	{
	    img.src = url1
	}
	
}

/** Sets an objects visibility to visible
  * @param tagid the id of the dom item to toggle
  * @return void
  */
function show(tagid) {
	var divtag = getDiv(tagid);
	divtag.style.display = '';
}
function showObj(tagid) {
	var divtag = getDiv(tagid);
	divtag.style.display = '';
}

/** Sets an objects visibility to hidden
  * @param tagid the id of the dom item to toggle
  * @return void
  */
function hide(tagid) {
	var divtag = getDiv(tagid);
	divtag.style.display = 'none';
}
function hideObj(tagid) {
	var divtag = getDiv(tagid);
	divtag.style.display = 'none';
}


/** Returns the dom object given the id string
  * @param tagid the id of the dom item to toggle
  * @return object
  */
function getDiv(tagid)
{

	if (document.getElementById)
	{
		return document.getElementById(tagid);
	}

	return document.all(tagid);

}


function checkEmail(email) {
	if (email != "" && email.match(/[A-z0-9\.\_\-]{1,}\@[A-z0-9\.\-]{1,}\.[A-z]{2,6}/)) {
		return true;
	} else {
		alert('Please enter a valid e-mail address. We’ll need it to communicate with you about your order. Also, when you visit us again, you’ll need it to access your account.');
		return false;
	}
}





/* returns true if form is valid.  shows alert and returns false if not
 *
 * @param Form frm the form object to be validated
 * @returns boolean true if form is valid
 */
function checkForm(frm) {
    if (frm.StartDate.value == '') {
        alert('Please specify the start date of your ski trip');
        return false;
    }
    // check that the date seems to be valid
	if (isDate(frm.StartDate.value)) {
		datesList = frm.StartDate.value.split(/[\/\-]/);
		y = datesList[2];
		m = datesList[0] - 1;
		d = datesList[1];
		trip_date = new Date();
		trip_date.setDate(d);
		trip_date.setMonth(m);
		trip_date.setFullYear(y);
		today = new Date();
		if (compareDates(today, trip_date) < 1)  {
			alert('Please choose a start date after today.');
			return false;
		}
	} else {
		alert('Please specify a valid start date for your trip, formatted as MM/DD/YYYY');
		return false;
	}
    return true;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}


 
/* results ready to display
 */
function displayResults() {
    document.forms[0].submit();
}

/* allow back-end to locate tickets
 */
function processSearch() {
    setTimeout('displayResults()', 1000);
}

/* compares two given javascript date objects
 *
 * @param date date1
 * @param date date2
 * @return int -1 if date1 > date2 || 0 if dates are equal || 1 if date1 < date2
 */
function compareDates(date1, date2) {

	var year1 = date1.getYear();
	var year2 = date2.getYear();
	var month1 = date1.getMonth();
	var month2 = date2.getMonth();
	var day1 = date1.getDate();
	var day2 = date2.getDate();

	if (year1 > year2) {
		return -1;
	}
	if (year2 > year1) {
		return 1;
	}

	//years are equal
	if (month1 > month2) {
		return -1;
	}
	if (month2 > month1) {
		return 1;
	}

	//years and months are equal
	if (day1 > day2) {
		return -1;
	}
	if (day2 > day1) {
		return 1;
	}

	//days are equal
	return 0;

}


// global var so the readystate has access to it
var reloadResortListForm;

function reloadResortList(frm)
{
    // build the url for the ajax post
    url = '/index_js.php?RegionCatId=' + frm.RegionCatId.value;
    
    // set the global var so onreadystate has scope without having to hunt it down
    reloadResortListForm = frm;
    
    // start the request
    startRequest(url, onResortReadyStatusChange)
}


function startRequest(url, readyStateHandler)  {
	req = false;
    if(window.XMLHttpRequest)  {
        // native XMLHttpRequest object
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    } else if (window.ActiveXObject) {
        // IE/Windows ActiveX version
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
    
	if(req)  {
		req.onreadystatechange = readyStateHandler;
		req.open("GET", url, true);
		req.send("");
	} else {
        appendStatus('Browser does not support HTTP_POST', false, true);
	}
}

function onResortReadyStatusChange() {
    // only if req shows "loaded"
    if(req.readyState == 1) { 
        showStatus("Loading...", true, false);
        return;
    } 
    
    if (req.readyState == 4) {
        // make sure status is ok
        if (req.status != 200) {
             appendStatus('Unable to connect to server. Status ' + req.status + ': ' + req.statusText, false, true);
             return;
		}
        resorts = null;
        // index_js returns JSON.  try to parse it
        try {
            resorts = JSON.parse(req.responseText);
        } catch(e) {
            appendStatus('Error parsing JSON response', false, true);
            return;
        }
        // check if index_js returned a JSONError
        if (resorts.name == 'JSONError') {
            appendStatus('Unexpected results: ' + resorts.message, false, true);
            return;
        }
        // everything looks good.  rebuild the dropdown list
        selected = '';
        if (reloadResortListForm.RegionCatId.options[reloadResortListForm.RegionCatId.selectedIndex].value != 'X_0') {
            selected = trim(reloadResortListForm.RegionCatId.options[reloadResortListForm.RegionCatId.selectedIndex].text);
        }
        reloadResortListForm.ResortGroup.options.length = 0;
        reloadResortListForm.ResortGroup.options[0] = new Option('All ' + selected + ' Resorts', '', true, false);
        for (i = 0; i < resorts.length; i++) {
            reloadResortListForm.ResortGroup.options[i+1] = new Option(resorts[i].ResortGroup, resorts[i].ResortGroup, true, false);
        }
        hideStatus();
    }
}

function trim(str) {
	// replace null at the beginning of string.  IE thinks &nbsp; is a null character
	while (Asc(str.substr(0,1)) == 0 && str.length > 1) {
		str = str.substr(1);
	}
	return str.replace(/^\s*|\s*$/g,"");
}

function Asc(string) {
	var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";
	var loAZ = "abcdefghijklmnopqrstuvwxyz";
	symbols += loAZ.toUpperCase();
	symbols += "[\\]^_`";
	symbols += loAZ;
	symbols += "{|}~";
	var loc;
	loc = symbols.indexOf(string);
	if (loc > -1) { 
		Ascii_Decimal = 32 + loc;
		return (32 + loc);
	}
	return (0);
}

var persisted = false;

function showStatus(msg, show_animation, persist) {
    reloadResortListForm.ResortGroup.options.length = 0;
    reloadResortListForm.ResortGroup.options[0] = new Option(msg, '0', true, false);
    reloadResortListForm.ResortGroup.options[1] = new Option('All Resorts', '0', true, false);
    return false;
}

function appendStatus(msg, show_animation, persist) {
    showStatus(msg, show_animation, persist);
}

function hideStatus() {
}



function fixIeDropDown(sBox){
	var sBox = (typeof sBox == "string") ? document.getElementById(sBox) : sBox;

	// THIS FUNCTION IS ONLY CONCERNED WITH INTERNET EXPLORER NON-MULTIPLE SELECT NODES THAT HAVE A SPECIFIC WIDTH DEFINED
	if(!sBox.attachEvent || navigator.userAgent.indexOf("Opera") > -1 || sBox.multiple || sBox.currentStyle.width == "auto") { return; }

	var body = document.getElementsByTagName("body").item(0);

	var si = sBox.selectedIndex;

	var clone = sBox.cloneNode(true);
	clone.style.position = "absolute";
	clone.style.visibility = "hidden";
	clone.style.width = "auto";
	body.appendChild(clone);

	clone._initialOffsetWidth = sBox.offsetWidth;
	clone._initialOffsetHeight = sBox.offsetHeight;
	clone._autoWidth = clone.offsetWidth;

	clone = body.removeChild(clone);
	clone.style.visibility = "visible";
	clone.style.width = clone._initialOffsetWidth + "px";

	var span = document.createElement("span");
	span._isIeDropDownContainer = true;
	span.style.position = "relative";
	span.style.width = clone._initialOffsetWidth + "px";
	span.style.height = clone._initialOffsetHeight + "px";
	span.style.marginBottom = "-4"; //hmm...quirky...
	span.appendChild(clone);

	if (sBox.parentNode._isIeDropDownContainer){
		sBox.parentNode.parentNode.replaceChild(span, sBox.parentNode);
	}else{
		sBox.parentNode.replaceChild(span, sBox);
	}

	if (clone._autoWidth > clone._initialOffsetWidth){
		var expand = function(){
			event.srcElement.parentNode.style.zIndex = 1;
			event.srcElement.style.width = "auto";
			if (event.srcElement.offsetWidth > event.srcElement._initialOffsetWidth){
				event.srcElement.style.width = "auto";
			}else{
				event.srcElement.style.width = event.srcElement._initialOffsetWidth + "px";
			}
		};
		var contract = function(){
			event.srcElement.parentNode.style.zIndex = 0;
			event.srcElement.style.width = event.srcElement._initialOffsetWidth + "px";
		};
		clone.attachEvent("onactivate", expand);
		clone.attachEvent("ondeactivate", contract);
		clone.attachEvent("onchange", contract);
	}
	clone.selectedIndex = si;
}

