// JavaScript Document
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function displayadvsearch(){
        //alert("page load");
        if (  document.getElementById("adv-srch").checked )
          {
                //  alert("checked");
                document.getElementById("acco_adv_search").style.display = "";
                document.getElementById("simple_type").style.display = "none";
                //if advance search selected, unselecte simple subTypeName
                clearSelectBox(document.getElementById("simple_subTypeName"),true);
                //document.getElementById("lab-srch").nodeValue ="Hide Advanced Search";
          }

        if (document.getElementById("adv-srch").checked== false)
          {
                //    alert("UN checked");
                document.getElementById("acco_adv_search").style.display = "none";
                document.getElementById("simple_type").style.display = "";

                //if simple search selected, unselecte advance search option
                clearSelectBox(document.getElementById("adv_subTypeId"),false);
                clearSelectBox(document.getElementById("price_from"),true);
                clearSelectBox(document.getElementById("price_to"),true);
                clearSelectBox(document.getElementById("adv_amenityList"),false);
                clearSelectBox(document.getElementById("adv_affiliationList"),false);
                //document.getElementById("lab-srch").nodeValue ="Hide Advanced Search";
          }
}//end displayadvsearch(){

function displayconferenceadvsearch(){
    if (  document.getElementById("adv-srch").checked )
          {
                  document.getElementById("acco_adv_search").style.display = "";
                  //document.getElementById("simple_type").style.display = "none";
          }
        if (document.getElementById("adv-srch").checked== false)
          {
			  	 
                  document.getElementById("acco_adv_search").style.display = "none";
                  //document.getElementById("simple_type").style.display = "";
                  clearSelectBox(document.getElementById("adv_subTypeId"),false);
          }
}

function displaytransportadvsearch(){
        //alert("page load");
        if (  document.getElementById("adv-srch").checked )
          {
                document.getElementById("acco_adv_search").style.display = "";
                document.getElementById("simple_type").style.display = "none";
                //if advance search selected, unselecte simple subTypeName
                clearSelectBox(document.getElementById("simple_subTypeName"),true);
                //document.getElementById("lab-srch").nodeValue ="Hide Advanced Search";
          }

        if (document.getElementById("adv-srch").checked== false)
          {
                document.getElementById("acco_adv_search").style.display = "none";
                document.getElementById("simple_type").style.display = "";

                //if simple search selected, unselecte advance search option
                clearSelectBox(document.getElementById("adv_subTypeId"),false);
                //document.getElementById("lab-srch").nodeValue ="Hide Advanced Search";
          }
}//end displaytransportadvsearch(){

//set the price_to $50 more (or one more selected index) than price_from
function setToPrice(from, to){
        var fromlength = from.length;
        var tolength = to.length ;
        to.disabled= false;

        if(from.options[0].selected || from.options[fromlength-1].selected){
           to.options[0].selected= true;
           to.disabled= true;
           return;
        }

        for (var i = 0; i < fromlength; i++) {
                //to.options[i].disabled=true;
                if(from.options[i].selected){
                        to.options[i].selected =true;
                        return;
                }
        }
}//end setToPrice()

//Unselect given select box.
function clearSelectBox(target, isSingleList){
        for (var i = 0; i < target.length; i++) {
                        target.options[i].selected =false;
        }
        //Force single list [0] to be selected since single list in IE isn't effected by above for loop
        //if(isSingleList ) target.options[0].selected =true;
        /*
        var detect = navigator.userAgent.toLowerCase();
        if(detect.indexOf('msie') != -1){
          target.options[0].selected =true;
        }
        */
}//end clearSelectBox(target)

        // used by search.jsp to select list items
function selectionChanged(thisElement, selectedIndex)
{
        //<%-- SRM 4/4/05 - With multiple subTypeId fields in the form, get the one that triggered the event --%>

        //<%-- If user clicked outside select element, and nothing's selected, return --%>
        if (selectedIndex == -1)
        {
                return;
        }

        //<%-- if selected a normal item(not a group header item), do nothing --%>
        if (!isNaN(thisElement.options[selectedIndex].value))
        {
                return;
        }

        //<%-- loop through the list --%>
        for (i=0;i<thisElement.options.length;i++)
        {
                //<%-- if this is a non-number subtypeId, which might be one of "hotel", "backpacker" ... --%>
                  if (isNaN(thisElement.options[i].value))
                  {
                          //<%-- keep looping the rest --%>
                          for (j = i+1; j<thisElement.options.length; j++)
                          {
                                  //<%-- until encountered the next non-number subtype Id --%>
                                  if (isNaN(thisElement.options[j].value))
                                  {
                                          i = j-1;
                                          break;
                                  }
                                  //<%-- make this group the same status as the non-numbered one --%>
                                  if (thisElement.options[i].selected)
                                  {
                                          thisElement.options[j].selected=thisElement.options[i].selected;
                                  }
                          }
                  }
        }
        // <%-- Now force a scroll to the top-most selected item, by toggling the selected state --%>
        var currentState = thisElement.options[selectedIndex].selected;
        thisElement.options[selectedIndex].selected = !currentState;
        thisElement.options[selectedIndex].selected = currentState;
}


	function setTypeId(){
		
		var form1 = document.searchaccom;
		var typeId = form1.typeId.value;
		
		var sTypeId = document.getElementById('adv_subTypeId');
		var tempTypeIdArray= new Array();
		for (i=0; i < sTypeId.length; i++) {
				if (sTypeId[i].selected) {
					if(contains(transportSubtype, sTypeId[i].value) ){
						tempTypeIdArray.push(7);   
					}
					if(contains(rentalSubtype, sTypeId[i].value) ){
					    tempTypeIdArray.push(8); 
					}
				}			
		}
		form1.typeId.value = unique(tempTypeIdArray).toString();
		if(form1.typeId.value.length==0){
			form1.typeId.value = "7,8";
		}
		return true;
	}
	/**
	 * Removes duplicates in the array 'a'
	 * 
	 */
	function unique(a) {
		tmp = new Array();
		for(i=0;i<a.length;i++){
			if(!contains(tmp, a[i])){
				tmp.length+=1;
				tmp[tmp.length-1]=a[i];
			}
		}
		return tmp;
	}
	
	/**
	 * Returns true if 's' is contained in the array 'a'
	 * 
	 */
	function contains(a, e) {
		for(j=0;j<a.length;j++)if(a[j]==e)return true;
		return false;
	}

function toggleBox(szDivID, iState) // 1 visible, 0 hidden
{
    if(document.layers)           //NN4+
    {
       document.layers[szDivID].visibility = iState ? "show" : "hide";
    }
    else if(document.getElementById)          //gecko(NN6) + IE 5+
    {
        var obj = document.getElementById(szDivID);
        obj.style.visibility = iState ? "visible" : "hidden";
    }
    else if(document.all)        // IE 4
    {
        document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
    }
}
function isObject(a) {
    return (a && typeof a == 'object') ;
}

//http://www.quirksmode.org/js/cookies.html
function createRoomCookie(name,value,days)
{
        if (days)
        {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/"; //path=/
}

function readCookie(name)
{
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++)
        {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
}


/*
* Tests if cookies are enabled. 
* by setting a temporary cookie and immediately trying to read it afterwards.
*/
function isCookieEnable() { 
	//var expDate = new Date(); 
	//valid one minute 
	//expDate.setTime( expDate.getTime() + ( 60 * 1000 ) ); 
	//expDate.setTime( expDate.getTime() + ( 60 * 1000 ) ); 
	//setCookie(tcname , "OK", expDate ); 
	var tcname = "testCookie";
	//valid 0.001 day
	createRoomCookie(tcname,"OK", 0.001 );
	
	//testing = getCookie( tcname ); 
	testing = readCookie(tcname);
	
	if ( testing == "OK" ) { 
		return true; 
	} else { 
		return false; 
	} 
}

//cookie array
function popupform(myform, windowname, x, y)
{
		if (! window.focus)return true;
		//window.open('', windowname, 'height="+y+",width="+x+",scrollbars=yes,resizable=yes');
		window.open('', windowname, 'height='+y+',width='+x+',scrollbars=yes,resizable=yes');
		myform.target=windowname;
		return true;
}
function popup(url,x,y){
	var iL = (screen.width/2) - (x/2);
	//var iT = (screen.height/2) - (y/2);
	var iT = 30;	
  dispalyWindow = window.open(url, "newWindow", "resizable=yes,status=0,scrollbars=yes,width="+x+",height="+y+",left="+iL+",top="+iT);
}

function addToFavorites(url, description) {
	if (window.external) { 
		window.external.AddFavorite(url, description);
	} 
	else { 
		alert('To bookmark this page, click Bookmarks | Bookmark This Page... \r\n or press Ctrl+D.'); 
	} 
} 

function runSlideShow() {
	// Set slideShowSpeed (milliseconds)
	var slideShowSpeed = 5000;
	// Duration of crossfade (seconds)
	var crossFadeDuration = 5;
	if (document.all) {
	document.images.SlideShow.style.filter="blendTrans(duration=2)";
	document.images.SlideShow.style.filter="blendTrans(duration=crossFadeDuration)";
	document.images.SlideShow.filters.blendTrans.Apply();
	}
	//alert(preLoad[j].src+' '+j+' '+p);
	document.images.SlideShow.src = preLoad[j].src;
	if (document.all) {
	document.images.SlideShow.filters.blendTrans.Play();
	}
	j = j + 1;
	if (j > (p - 1)) j = 0;
	t = setTimeout('runSlideShow()', slideShowSpeed);
}
function runSlideAndUrlShow() {
	// Set slideShowSpeed (milliseconds)
	var slideShowSpeed = 5000;
	// Duration of crossfade (seconds)
	var crossFadeDuration = 5;
	if (document.all) {
	document.images.SlideShow.style.filter="blendTrans(duration=2)";
	document.images.SlideShow.style.filter="blendTrans(duration=crossFadeDuration)";
	document.images.SlideShow.filters.blendTrans.Apply();
	}
	//alert(preLoad[j].src+' '+j+' '+p);
	document.images.SlideShow.src = preLoad[j].src;
	var obj = document.images.SlideShow.parentElement;
	obj.href = Url[j];
	if (document.all) {
		document.images.SlideShow.filters.blendTrans.Play();
	}
	j = j + 1;
	if (j > (p - 1)) j = 0;
	t = setTimeout('runSlideShow()', slideShowSpeed);
}
function isFlashInstalled(){
	//if flash install, do nothing
	if ((navigator.appName == "Microsoft Internet Explorer" &&
		navigator.appVersion.indexOf("Mac") == -1 &&   navigator.appVersion.indexOf("3.1") == -1) ||
	
		(navigator.plugins && navigator.plugins["Shockwave Flash"])
						   || navigator.plugins["Shockwave Flash 2.0"]){
		//alert(	navigator.plugins["Shockwave Flash"].description.toString()+' ------');
		return true;
	}
	//no flash installed, run javascript slideshow
	else {
		return false;
	}
}// end isFlashInstalled

/*
* @para aform form object
* return string date formate as '20061223'
*/
function formatCheckInDate(aform){
	var cDate = getSelectedValue(aform.checkinDate).toString();
	if (cDate.length ==1){
		cDate='0'+cDate;
	}
	var cMonth = getSelectedValue(aform.checkinMonth).toString();
	if (cMonth.length ==1){
		cMonth='0'+cMonth;
	}
	var cYear = getSelectedValue(aform.checkinYear).toString();
	var strDate = cYear+cMonth+cDate;
	//all dropdown have value, so assign value to startdate
	if(strDate.indexOf('NaN')<0){
		aform.startdate.value = strDate;	
	}
	var regionValue='';
	if(isObject(aform.locationId)){
		regionValue = getSelectedValue(aform.locationId).toString();
	}
	var townValue=aform.town.value;
	
	var searchKeyword='';
	if(isObject(aform.title)){
		searchKeyword = aform.title.value;
	}
	
	if( (isWhitespace(townValue) || (townValue =='City / Town')) 
		&& ( regionValue=='' || regionValue=='NaN') 
		&& (isWhitespace(searchKeyword) ) ){
		
		alert('Please indicate your desired location.');
		return false;
	}else{
		aform.action='/accommodation-newzealand/availability-results.php';
		return true;
	}
	
}

function isSelectRegion(aform){
	var regionValue='';
	if(isObject(aform.locationId)){
		regionValue = getSelectedValue(aform.locationId).toString();
	}
	if(  regionValue=='' || regionValue=='NaN' ){
		alert('Please indicate your desired location.');
		return false;
	}else{
		aform.action='/accommodation-newzealand/availability-results.php';
		return true;
	}
	
}

/* @para int numberMillis number of million second e.g 1000= 1 second */
function sleep(numberMillis){
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true){
		now = new Date();
		if (now.getTime() > exitTime)
		return;
	}
} 


/*
* refresh parent window with given url
*/
function targetopener(mylink, closeme, closeonly){
	if (! (window.focus && window.opener))return true;
	window.opener.focus();
	if (! closeonly)window.opener.location.href=mylink;
	if (closeme)window.close();
	return false;
}


/*
* check textbox length
* @param controledObj textarea object holding the text
* @param monitorObj span object to show how many characters left
* @param maxLength int maximum length of text of the textarea
*/
function checkLength(controledObj,monitorObj, maxLength){
    var currentlength = controledObj.value.length;
    var charleft = maxLength-currentlength;
	var maxLengthLessOne = maxLength-1;
    if (currentlength > maxLengthLessOne){
        controledObj.value = controledObj.value.slice(0, maxLengthLessOne);
    }
        //monitorObj.value=charleft;
		monitorObj.innerHTML ='<strong>'+charleft+'</strong>';
}


 /*
addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
*/
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

/* Create the new window */
function openInNewWindow(e) {
	var event;
	if (!e) event = window.event;
	else event = e;
	// Abort if a modifier key is pressed
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
		return true;
	}
	else {
		// Change "_blank" to something like "newWindow" to load all links in the same new window
	    var newWindow = window.open(this.getAttribute('href'), '_blank');
		if (newWindow) {
			if (newWindow.focus) {
				newWindow.focus();
			}
			return false;
		}
		return true;
	}
}

/*
Add the openInNewWindow function to the onclick event of links with a class name of "new-window"
*/
function getNewWindowLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// Change this to the text you want to use to alert the user that a new window will be opened
		//var strNewWindowAlert = " (opens in a new window)";
		// Find all links
		var links = document.getElementsByTagName('a');
		var objWarningText;
		var link;
		for (var i = 0; i < links.length; i++) {
			link = links[i];
			// Find all links with a class name of "non-html"
			if (/\bnon\-html\b/.test(link.className)) {
				// Create an em element containing the new window warning text and insert it after the link text
				//objWarningText = document.createElement("em");
				//objWarningText.appendChild(document.createTextNode(strNewWindowAlert));
				//link.appendChild(objWarningText);
				link.onclick = openInNewWindow;
			}
			if (/\bexternal\b/.test(link.className)){
				link.onclick = openInNewWindow;
			}
		}
		objWarningText = null;
	}
}

function checkEmailField(str){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)){
		return true;
	}
	return false;
}

function check101Login(){
	var msg = '';
	if(!checkEmailField(document.loginform.email.value)){
		msg += ' - Email.\n';
	}
	if(document.loginform.password.value == ''){
		msg += ' - Password.\n';
	}
	if(msg){
		alert('Warning! The following fields are incomplete.\n\n'+msg);
		return false;
	}
	return true;
}
function check101Registration(){
	var msg = '';
	if(!checkEmailField(document.registerform.email.value)){
		msg += 'Email Address.\n';
	}
	if(document.registerform.password.value == ''){
		msg += 'Password.\n';
	}
	if(document.registerform.password2.value == ''){
		msg += 'Confirm Password.\n';
	}
	if(document.registerform.password.value.length < 6){
		msg += 'Your password must be at least 6 characters long.\n';
	}
	//donot have confirmemail after login
	if (document.getElementById("confirmemail")!=null) {
		if(document.registerform.email.value != document.registerform.confirmemail.value){
			msg += 'Confirm email does not match Email Address.\n';
		}
	}
	if(document.registerform.password.value != document.registerform.password2.value){
		msg += 'Password 2 does not match Password.\n';
	}
	if(document.registerform.fname.value == ''){
		msg += 'First Name.\n';
	}
	if(document.registerform.lname.value == ''){
		msg += 'Last Name.\n';
	}
	if(document.registerform.city.value == ''){
		msg += 'City.\n';
	}
	//donot have confirmemail after login
	if (document.getElementById("acceptTerms")!=null) {
		if(!document.registerform.acceptTerms.checked){
			msg += 'You must accept the terms and conditions\n';
		}
	}
	if(msg){
		msg = 'Warning! The following fields are incomplete.\n\n'+msg;
		alert(msg);
		return false;
	}
	return true
}
function FlashNewWindow(url){
	 var newWindow = window.open(url, '_blank');
}
addEvent(window, 'load', getNewWindowLinks);

function checkAll(el, ids){
	var temp = new Array();
	temp = ids.split(':');
			
	for(var i=0;i<temp.length; i++){
		var box = document.getElementById("checkbox_"+temp[i]);
		if(el.checked){
			tick(box, true);
		}
		else{
			tick(box, false);
		}
	}
			
}
function tick(el, value){
	el.checked = value;
			
}
function checkOne(el, parentId){
			
	var parent = document.getElementById("checkbox_"+parentId);
	if(parent.checked){
			tick(parent, false);
	}
}
