var params='';
var lang;
var url;
function changeCombo(combo,index) {
    params="";
    loading('loading','search_query');
    //var q_freetext = document.getElementById('freetext').value;
    var q_freetext = document.getElementById('q_freetext').value;
    if(q_freetext)params += 'q_freetext='+q_freetext+'&';
    var q_tag = document.getElementById('q_tag').value;
    if(q_tag)params += 'q_tag='+q_tag+'&';
    /*var q_pricemin = document.getElementById('q_pricemin').value;
    if(q_pricemin)params += 'q_pricemin='+q_pricemin+'&';
    var q_pricemax = document.getElementById('q_pricemax').value;
    if(q_pricemax)params += 'q_pricemax='+q_pricemax+'&';*/
    var type = document.getElementById('type').options[document.getElementById('type').selectedIndex].value;
    if(combo.name=='q_type' && !type){updatePage(index);return false}
    else if(type)params += 'q_type='+type+'&';
    var topic = document.getElementById('topic').options[document.getElementById('topic').selectedIndex].value;
    if(combo.name=='q_theme' && !topic){updatePage(index);return false}
    else if(topic)params += 'q_theme='+topic+'&';
    var venue = document.getElementById('venue').options[document.getElementById('venue').selectedIndex].value;
    if(combo.name=='q_venue' && !venue){updatePage(index);return false}
    else if(venue)params += 'q_venue='+venue+'&';
    /*var continent = document.getElementById('continent').options[document.getElementById('continent').selectedIndex].value;
    if(combo.name=='q_continent' && !continent){updatePage(index);return false}
    else if(continent)params += 'q_continent='+continent+'&';
    var country = document.getElementById('country').options[document.getElementById('country').selectedIndex].value;
    if(combo.name=='q_country' && !country){updatePage(index);return false}
    else if(country)params += 'q_country='+country+'&';
    var region = document.getElementById('region').options[document.getElementById('region').selectedIndex].value;
    if(combo.name=='q_region' && !region){updatePage(index);return false}
    else if(region)params += 'q_region='+region+'&';
    var subregion = document.getElementById('subregion').options[document.getElementById('subregion').selectedIndex].value;
    if(combo.name=='q_subregion' && !subregion){updatePage(index);return false}
    else if(subregion)params += 'q_subregion='+subregion+'&';
    var city = document.getElementById('city').options[document.getElementById('city').selectedIndex].value;
    if(combo.name=='q_city' && !city){updatePage(index);return false}
    else if(city)params += 'q_city='+city+'&';*/
    //params +='1=1';
    updatePage(index);
}
function changeAdvContents(id,index){
	var fvalue=document.getElementById(id);
	var oldval=document.getElementById(id+'old');
	if(fvalue.value && fvalue.value.length>2 && fvalue.value!=oldval.value){
		params="";
	    loading('loading','search_query');
	    var q_freetext = document.getElementById('q_freetext').value;
	    if(q_freetext)params += 'q_freetext='+q_freetext+'&';
	    var type = document.getElementById('type').options[document.getElementById('type').selectedIndex].value;
	    if(type)params += 'q_type='+type+'&';
	    var topic = document.getElementById('topic').options[document.getElementById('topic').selectedIndex].value;
	    if(topic)params += 'q_theme='+topic+'&';
	    var q_tag = document.getElementById('q_tag').value;
	    if(q_tag)params += 'q_tag='+q_tag+'&';
	    //params +='1=1';
	    updatePage(index);
	}
}
function updatePage(index){
	if(index){
	    var myRequest = new ajaxObject('/component/query/index-ajax.jhtml', processFirstTabData ,'search_query');
	    myRequest.update(params,'GET');
	}else{
    var myRequest = new ajaxObject('/component/query/advanced-ajax.jhtml', processFirstTabData ,'search_query');
    myRequest.update(params,'GET');
    myRequest = new ajaxObject('/component/query/small-ajax.jhtml', processData,'small_query');
    myRequest.update(params,'GET');}
}

function getParams(){
    return params;
}
function getY( oElement ){var iReturnValue = 0;while( oElement != null ) {iReturnValue += oElement.offsetTop;oElement = oElement.offsetParent;}return iReturnValue;} function getX( oElement){var iReturnValue = 0;while( oElement != null ){iReturnValue += oElement.offsetLeft;oElement = oElement.offsetParent;}return iReturnValue;}
function loading(load,container,width) {
    var loading = document.getElementById(load);
    var data = document.getElementById(container);
    if(loading && data){
    loading.style.height = data.offsetHeight+'px';
    loading.style.left = getX(data) + 'px';
    loading.style.top = getY(data) + 'px';

    if(width)loading.style.width= width;
    else loading.style.width= data.offsetWidth+'px';
    loading.style.display = 'block';}
}

function processFirstTabData(responseText, responseStatus,responseXML,container) {
  if (responseStatus==200) {
    document.getElementById(container).innerHTML = responseText;
    buildcombo();
  } else {
    //alert(responseStatus + ' -- Error Processing Request');
  }
}

var map;
var geocoder;
var baseIcon;
var gmarkers=[];
var accomarkers=[];
var bounds;
var autoadjust=false;
var changeUrl=true;
        
function load() {
    if(document.getElementById("map")){
        map = new google.maps.Map2(document.getElementById("map"));
        var customUI = map.getDefaultUI();
        map.setUI(customUI);
        if(changeUrl==true){
        	url='/component/map/advanced-ajax.jx?map_height='+map.getSize().height+'&map_width='+map.getSize().width;
        }
        geocoder = new google.maps.ClientGeocoder();
        //map.addControl(new google.maps.SmallMapControl());
        map.setCenter(new google.maps.LatLng(20.00, 0.0), 2);
        //map.addMapType(G_PHYSICAL_MAP);
        
        var mt = map.getMapTypes();
        // Overwrite the getMinimumResolution()
        for (i=0; i < mt.length; i++) {
          mt[i].getMinimumResolution = function() {return 2;}
          
        }
        
        //map.disableDoubleClickZoom();
        
        //map.addControl(new google.maps.LargeMapControl());
        //map.addControl(new google.maps.MapTypeControl());
        map.setMapType(G_HYBRID_MAP) ;
        //map.addControl(new google.maps.OverviewMapControl);
        
        // when zoomed in call this function
        google.maps.Event.addListener(map, "zoomend",
		    function() { zoomed(); }
	    );
	    // when moved call this function
        google.maps.Event.addListener(map, "dragend",
		    function() { moveed(); }
	    );
        // Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
        baseIcon = new google.maps.Icon();
        //baseIcon.shadow = "/icons/map/marker_shadow.png";
        //baseIcon.iconSize = new google.maps.Size(14, 29);
        //baseIcon.shadowSize = new google.maps.Size(34, 31);
        baseIcon.iconAnchor = new google.maps.Point(9, 20);
        baseIcon.infoWindowAnchor = new google.maps.Point(9, 2);
        baseIcon.infoShadowAnchor = new google.maps.Point(18, 25);
        //var myRequest = new ajaxObject('/component/map/advanced-ajax.jx', processMapData);
        //myRequest.update('','GET');
    }
}
    
function processMapData(responseText, responseStatus,responseXML) {
  var count = 0;var sincol='FF5A00';
  if(typeof(markercoloursin) !== 'undefined' && markercoloursin) sincol=markercoloursin;
  if (responseStatus==200) {
    var mapnode = responseXML.documentElement.getElementsByTagName("map").item(0);
    bounds = new GLatLngBounds();
    if(mapnode.getElementsByTagName("point").item(0)){
        var point = mapnode.getElementsByTagName("point");
        for (var i = 0; i < point.length; i++) {
                var cnt = getInnerText(point[i].getElementsByTagName("count").item(0));
                var lat = getInnerText(point[i].getElementsByTagName("latitude").item(0));
                var lng = getInnerText(point[i].getElementsByTagName("longitude").item(0));
                var opt = "<p> There Are <b>"+cnt+"</b> Accommodations in this region</p>"
                //new AccoMarker(cnt, opt, lat,lng,'/icons/map/marker_more.png',issmallmap);
                //count=count+cnt*1;
                var loct = new GLatLng(lat,lng);
                var marker = cm_createMarker(loct,cnt,opt,0,issmallmap);
      	      	map.addOverlay(marker);
      	      	bounds.extend(loct);
                gmarkers.push(marker);accomarkers.push(marker);bounds.extend(loct);
                count=count+cnt*1;
        }
    }
    if(mapnode.getElementsByTagName("accommodation").item(0)){
        var point = mapnode.getElementsByTagName("accommodation");
        for (var i = 0; i < point.length; i++) {
                var lat = getInnerText(point[i].getElementsByTagName("latitude").item(0));
                var lng = getInnerText(point[i].getElementsByTagName("longitude").item(0));
                var info = getInnerText(point[i].getElementsByTagName("info").item(0));
                new AccoMarker("1", info, lat,lng,'/component/map/icons/marker.png?c='+sincol,issmallmap);
                count=count+1;
        }
    }
    if(autoadjust){
    	if(map.getBoundsZoomLevel(bounds) >= 16) map.setZoom(16); else map.setZoom(map.getBoundsZoomLevel(bounds));
    	map.setCenter(bounds.getCenter());autoadjust=false;}
    if(document.getElementById('loading'))
       document.getElementById('loading').style.display='none';
    if(document.getElementById('accocount')) document.getElementById('accocount').innerHTML=count;
  } else {}
}

function cm_createMarker(point, title, html, rank,issmallmap) {
	  var iconm = new GIcon(); var zoom=1;var col='FF8A00';var colact = 'FF0000';
	  if(typeof(markercolour) !== 'undefined' && markercolour) col=markercolour; if(typeof(markercolouract) !== 'undefined' && markercolouract) colact=markercolouract; if(issmallmap) zoom=0.7;
	  var imgsize=findImageSize(title);
	  iconm.image='/component/map/icons/marker.png?c='+col+'&zoom='+zoom+'&w='+imgsize;iconm.iconAnchor = new GPoint(16, 16);
	  var widt;var heigh;
	  if(issmallmap){widt=-20+findOff(title);heigh=-12}
	  else{widt=-16+findOff(title);heigh=-11}
	  var markerOpts = {};
	  markerOpts = {"icon": iconm, "clickable": true, "title": title+" Accommodation(s)", "labelText": title, "labelOffset": new GSize(widt, heigh)};
	  var newPoint = point;var marker = new LabeledMarker(newPoint, markerOpts);
	  google.maps.Event.addListener( marker, "click", function() {map.setCenter( point, map.getZoom() + 1 );});
	  GEvent.addListener(marker, "mouseover", function() { marker.setImage('/component/map/icons/marker.png?c='+colact+'&zoom='+zoom+'&w='+imgsize); });
	  GEvent.addListener(marker, "mouseout", function() { marker.setImage('/component/map/icons/marker.png?c='+col+'&zoom='+zoom+'&w='+imgsize); });
	  GEvent.addListener(marker, "infowindowclose", function() { marker.setImage('/component/map/icons/marker.png?c='+col+'&zoom='+zoom+'&w='+imgsize); });
	  return marker;
}

function findImageSize(count){ if(count<100) { return '1'; }else if(count<1000) {return '7';} else return '10';}
function findOff(count){if(count<10) return -4; else if(count<100) return -3;if(count<1000) return -1; else return 0;}

function zoomed(){
    if(!autoadjust){ for (var i=0;i<gmarkers.length;i++) { map.removeOverlay(gmarkers[i]); }
        gmarkers=[];accomarkers=[];
        var center = map.getCenter(); var span = map.getBounds().toSpan(); var zoom = map.getZoom();var latlngparams='';
        if(zoom>2){ latlngparams = "longMin="+map.getBounds().getSouthWest().lng()+"&longMax="+map.getBounds().getNorthEast().lng();
            latlngparams += "&latMin="+map.getBounds().getSouthWest().lat()+"&latMax="+map.getBounds().getNorthEast().lat(); if(getParams())latlngparams+='&' }
        var myRequest = new ajaxObject(url, processMapData); myRequest.update(latlngparams+getParams(),'GET'); } }

function moveed(){
    if(!autoadjust){
        for (var i=0;i<gmarkers.length;i++) {
            map.removeOverlay(gmarkers[i]);
        }
        gmarkers=[];
        accomarkers=[];
        var center = map.getCenter(); 
        var span = map.getBounds().toSpan(); 
        var zoom = map.getZoom();
        var latlngparams='';
    
        if(zoom>2){
            latlngparams = "longMin="+map.getBounds().getSouthWest().lng()+"&longMax="+map.getBounds().getNorthEast().lng();
            latlngparams += "&latMin="+map.getBounds().getSouthWest().lat()+"&latMax="+map.getBounds().getNorthEast().lat();
            if(getParams())latlngparams+='&'
        }
        
        //var myRequest = new ajaxObject('/component/map/advanced-ajax.jx', processMapData);
        var myRequest = new ajaxObject(url, processMapData);
        myRequest.update(latlngparams+getParams(),'GET');
    }
}

// for the Small directory map
var issmallmap=false;
function loadwithoutcontrols() {
    issmallmap=true;
    map = new google.maps.Map2(document.getElementById("map"));
    url='/component/map/advanced-ajax.jx?map_height='+map.getSize().height+'&map_width='+map.getSize().width;
    geocoder = new google.maps.ClientGeocoder();
    map.setCenter(new google.maps.LatLng(20.00, 0.0), 0);
    map.setMapType(G_HYBRID_MAP) ;
     
    // when zoomed in call this function
    google.maps.Event.addListener(map, "zoomend",
	    function() { zoomed(); }
	        );
    // when moved call this function
    google.maps.Event.addListener(map, "dragend",
	    function() { moveed(); }
	         );
	map.addControl(new google.maps.SmallZoomControl());
    //map.addControl(new ResetZoomControl());
	// Create a base icon for the small map
    baseIcon = new google.maps.Icon();
    //baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    //baseIcon.iconSize = new google.maps.Size(10, 20);
    //baseIcon.shadowSize = new google.maps.Size(20, 20);
    baseIcon.iconAnchor = new google.maps.Point(5, 20);
    baseIcon.infoWindowAnchor = new google.maps.Point(9, 2);
    baseIcon.infoShadowAnchor = new google.maps.Point(18, 25);
    if(document.getElementById('link')){
        var str = document.getElementById('link').href;
        if(str.indexOf('?')>0)params = str.substring(str.indexOf('?')+1);
        autoadjust=true;
        var myRequest = new ajaxObject(str, processMapData);
        myRequest.update('','GET');
    }
    else if(document.getElementById('latitude') && document.getElementById('longitude')){
        bounds = new GLatLngBounds();
        autoadjust=true;
        if(document.getElementById('latitude').value && document.getElementById('longitude').value){
            var pro = new AccoMarker("1", document.getElementById('address').innerHTML, document.getElementById('latitude').value,document.getElementById('longitude').value);
            map.setCenter(pro.location,15);}
        else{
            showAddress(document.getElementById('address').innerHTML);
            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());
        }
    }
}

// for the map advanced search page
function mapSearch(button){
    params="";
    autoadjust=true;
    loading('loading','map');
    var q_freetext = document.getElementById('q_freetext').value;
    if(q_freetext) params += 'q_freetext='+q_freetext+'&';
    var q_timemin = document.getElementsByName('q_timemin')[0].value;
    if(q_timemin) params += 'q_timemin='+q_timemin+'&';
    var q_timemax = document.getElementsByName('q_timemax')[0].value;
    if(q_timemax) params += 'q_timemax='+q_timemax+'&';
    var q_persons = document.getElementById('q_persons').value;
    if(q_timemax) params += 'q_persons='+q_persons+'&';
    params +='1=1';
    for (var i=0;i<gmarkers.length;i++) {
            map.removeOverlay(gmarkers[i]);
        }
    gmarkers=[]; 
    accomarkers=[];
    var myRequest = new ajaxObject(url, processMapData);
    myRequest.update(getParams(),'GET');
    button.disabled=false;
}

function getSimpleQueryMap(p,_url){
    params = p;
    autoadjust=true;
    changeUrl=false;
    url=_url;
    loading('loading','map');
    params +='1=1';
    for (var i=0;i<gmarkers.length;i++) {
        map.removeOverlay(gmarkers[i]);
    }
    gmarkers=[]; 
    accomarkers=[];
    var myRequest = new ajaxObject(url, processMapData);
    myRequest.update(getParams(),'GET');
    //button.disabled=false;
}

// Show the marker based on the address ... 
function showAddress(add) {
  geocoder.getLatLng(
    add,
    function(point) {
      if (point) {
        new AccoMarker("1",add,point.lat(),point,lng());
      } 
    }
  );
}

// on hover in query index page show marker 
var recentmarker;
function showhovermarker(id){
var ll=document.getElementById('latitude'+id);
var lnn=document.getElementById('longitude'+id);
if(ll && lnn && ll.value && lnn.value && parseInt(ll.value)!=0 && parseInt(lnn.value)!=0){
        for (var i=0;i<gmarkers.length;i++) {
            map.removeOverlay(gmarkers[i]);
        }
        recentmarker = new AccoMarker("1", "", ll.value,lnn.value,'/accommodation/icons/acco-add16.png');
    }
}
function removehovermarker(){
    if(recentmarker){
        map.removeOverlay(recentmarker.marker);
        gmarkers.pop();
        for (var i=0;i<gmarkers.length;i++) {
            map.addOverlay(gmarkers[i]);
        }
    }
}
//add bookmark
function addBookmark(e){
var myRequest = new ajaxObject(e.href,processData,"message");
    myRequest.update(getParams(),'GET');
    //document.getElementById("message").innerHTML = 'Bookmark saved sucessufuly !';
    //document.getElementById("message").style.display="";
    return false;
}
// Date Jquery 
//Date Function
function customRange(input) { 
        var min = new Date(); /*Set this to your absolute minimum date*/var max = new Date(); /*Set this to your absolute max date*/
        max.setMonth(max.getMonth() + 36); var dateMin = min; var dateMax = max; /*Set this to your absolute maximum date;*/ 
        var rng = 120; /*Set this to the range of days you want to restrict to*/ var diff = 1; /*Differnece between the dates*/
        if (input.id == "timemin" || input.id == "timeminprice") 
        {
        	var maxid= input.id=="timemin"?"#timemax":"#timemaxprice";
            if ($(maxid).datepicker("getDate") != null)
            {
                dateMax = $(maxid).datepicker("getDate");
                dateMax.setDate(dateMax.getDate() - diff);
                dateMin = $(maxid).datepicker("getDate");
                dateMin.setDate(dateMin.getDate() - rng);
                if (dateMin < min)
                {dateMin = min;}}}
        else if (input.id == "timemax" || input.id == "timemaxprice")
        {
        	var minid= input.id=="timemax"?"#timemin":"#timeminprice";
                if ($(minid).datepicker("getDate") != null)
                {
                        dateMin = $(minid).datepicker("getDate");
                        dateMin.setDate(dateMin.getDate() + diff);
                        var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(), dateMin.getDate() + rng);
                        if(rangeMax < dateMax)
                        { dateMax = rangeMax; }
                }else{ dateMin.setDate(dateMin.getDate() + diff);}}
        return {minDate: dateMin, maxDate: dateMax}; 
}

/********************* 
 *   Home page header image.. rotate!!
 * ******************/

//namespace
var tri = {
	newajax: {}, newmap: {}, newreviews: {}, page: {}, newsettings: {}, site: {}, newstrings: {}, newui: {},
	
	util: {
	initSearchSwap: function(){
		$(".input-keyword").each(function(){
	        var val = $(this).val();
	        var rel = $(this).attr("rel");
	        if(val == ""){ 
	        	$(this).addClass("default");
	        	$(this).val(rel);
	        }
	        else if(val != rel){
	        	$(this).removeClass("default");
			}
		});
		$(".input-keyword").focus(function(){
			var val = $(this).val();
			$(this).removeClass("default");	
			if($(this).attr("rel") == $(this).val()){
				$(this).val("");
			}
		});
		$(".input-keyword").blur(function(){
			var val = $(this).val();
			$(this).removeClass("default");
			if($(this).val() == ""){
				$(this).addClass("default");
				$(this).val($(this).attr("rel"));
			}
		});
		$('.input-keyword').keyup(function(e){
        	e = e || window.event;
        	var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        	if (keyCode == 13) {
        		tri.site.searchform.submit(e);
        	}
        });
	}
	}
	};

/*
 * HOMEPAGE
 */
tri.page.home = {
	init: function(){
		tri.page.home.initSwapImages();
		tri.util.initSearchSwap();
	},
	initSwapImages: function(){
		var swapduration = 8000;
		var timeout;

		$(window).load(function(){
		
			var layercount = 1;var maxlayercount = 1;

			function hideTwo(){
				
				if($('#layer'+(layercount+1)).length>0){
					$('#layer'+layercount).fadeOut(1500);
					timeout = setTimeout(hideTwo, swapduration);
					layercount++;
					maxlayercount =layercount;
				}else{
					$('#layer1').fadeIn(1500)
					setTimeout(function(){
						for (var i=2;i<maxlayercount;i++) {
							$('#layer'+i).css({display:'block'});
						}
					}, 1501);
					timeout = setTimeout(hideTwo, swapduration);
					layercount=1;
				}
			}
			timeout = setTimeout(hideTwo, swapduration);
		}); 
	}
};

/*
 * GLOBAL
 * advancedSearchForm, homeSearchForm, keywordSearchForm, refineSearchForm (aka sidebar)
 * noResults, 404error, error, secondary pages, etc.
 */
tri.site.searchform = {
    submit: function(e){
    	var formObj = $('form[name=searchform],form[name=refineSearchForm]');
    	if (e) formObj = $(e.target).parents('form');

    	// get keywords
    	var keywords = ($("input[name=q_freetext]", formObj).length > -1) ? $("input[name=q_freetext]", formObj).val() : "";
    	var defaultMessage = $("input[rel]", formObj).attr("rel");

    	if ($.trim(keywords) !="" && keywords!=defaultMessage) {
    		//keywords = "/keywords:" + encodeURIComponent(keywords);
    	}
    	else{
    		$("input[name=q_freetext]", formObj).val("");
    	}
    	formObj.submit();
    }
};


function chngdisp(layercnt){
	var i=2;
	for (i=2;i<=layercnt;i++) {
		$('#layer'+i).css({display:'block'});
	}
}
/*
 * init Functions
 

$(document).ready(function(){
	if ($("body.homePage").length > 0) tri.page.home.init();
});*/




// scrolling div
scrollStep=1; timerUp=""; timerDown=""; function toTop(id){document.getElementById(id).scrollLeft=0; } 
function scrollDivRight(id){clearTimeout(timerDown);document.getElementById(id).scrollLeft+=scrollStep;
if(document.getElementById(id).scrollLeft>=document.getElementById(id).scrollWidth-300)
document.getElementById("right").style.visibility='hidden';if(document.getElementById(id).scrollLeft>0 && document.getElementById(id).scrollWidth>300)
document.getElementById("left").style.visibility='visible';//alert(document.getElementById(id).scrollLeft);
timerDown=setTimeout("scrollDivRight('"+id+"')",10) } 
function scrollDivLeft(id){ clearTimeout(timerUp);document.getElementById(id).scrollLeft-=scrollStep;
if(document.getElementById(id).scrollLeft==0)document.getElementById("left").style.visibility='hidden';
if(document.getElementById(id).scrollLeft < document.getElementById(id).scrollWidth-300)document.getElementById("right").style.visibility='visible';
timerUp=setTimeout("scrollDivLeft('"+id+"')",10); } 
function toBottom(id){document.getElementById(id).scrollLeft=document.getElementById(id).scrollWidth;} 
function stopMe(){ clearTimeout(timerDown); clearTimeout(timerUp); }


// COLAPSABLE DIV
var timerlen = 5;var slideAniLen = 250;var timerID = new Array();var startTime = new Array();var obj = new Array();var endHeight = new Array();var moving = new Array();var dir = new Array();
function slidedown(objname){if(moving[objname])return;if(document.getElementById(objname).style.display != "none")return; // cannot slide down something that is already visible
moving[objname] = true;dir[objname] = "down";startslide(objname);}
function slideup(objname){if(moving[objname])return;if(document.getElementById(objname).style.display == "none")return; // cannot slide up something that is already hidden
moving[objname] = true;dir[objname] = "up";startslide(objname);}
function startslide(objname){obj[objname] = document.getElementById(objname);endHeight[objname] = parseInt(obj[objname].style.height);startTime[objname] = (new Date()).getTime();if(dir[objname] == "down"){obj[objname].style.height = "1px";}obj[objname].style.display = "block";timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);}
function slidetick(objname){var elapsed = (new Date()).getTime() - startTime[objname];if (elapsed > slideAniLen)endSlide(objname);else {var d =Math.round(elapsed / slideAniLen * endHeight[objname]);if(dir[objname] == "up")d = endHeight[objname] - d;obj[objname].style.height = d + "px";}return;}
function endSlide(objname){clearInterval(timerID[objname]);if(dir[objname] == "up")obj[objname].style.display = "none";obj[objname].style.height = endHeight[objname] + "px";delete(moving[objname]);delete(timerID[objname]);delete(startTime[objname]);delete(endHeight[objname]);delete(obj[objname]);delete(dir[objname]);return;}
function toggleSlide(objname){if(document.getElementById(objname).style.display == "none"){// div is hidden, so let's slide down
slidedown(objname);}else{ // div is not hidden, so slide up
slideup(objname);}}
function $Obj(v) { return(document.getElementById(v));}

// send vote
var q_votetype ='',starNum='';
function sendVote(o){
    starNum=o.id.substr(4);
    var v=parseInt($Obj('starUser'+starNum).innerHTML);
    q_votetype = $Obj('paramname'+starNum).innerHTML;
    var params="q_votetype="+q_votetype+"&q_vote="+v;
    myRequest = new ajaxObject('/component/accommodation/functions/vote.jx?cocoon-view=debug-raw&acco_id='+$Obj('acco_id').innerHTML+'&'+params,processData,"ratemess");
    myRequest.update('','GET');
    /*
    var message = $Obj('ratemess');
    message.innerHTML='Thanking you for voting '+$Obj('startitle'+starNum).innerHTML+v+'%';
    message.style.display="";
    setTimeout("$Obj('ratemess').style.display='none'",5000);
    */
    if(starNum=='0')
        $Obj('feedback'+starNum).style.display="";
    return false;
}

// send Feedback
function sendFeedback(){
   var v=$Obj('feedbacktext'+starNum);
   if(v && v.value && v.value.length>0){
        myRequest = new ajaxObject('/component/accommodation/functions/vote.jx?cocoon-view=debug-raw&acco_id='+$Obj('acco_id').innerHTML+'&q_feedback='+v.value+'&q_votetype='+q_votetype,processData,"ratemess");
        myRequest.update('','GET');
        $Obj('feedback'+starNum).style.display='none';
        /*
        var message = $Obj('ratemess');
        message.innerHTML='Thanking you for sharing your views!';
        message.style.display="";
        setTimeout("$Obj('ratemess').style.display='none'",3000);
        */
        return false;
   }
}

//check Email
function checkEmail(email) {var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;if (!filter.test(email)) {return false;}return true;}
function splitAndCheckEmail(tostring){var mySplitResult = tostring.split(",");for(i = 0; i < mySplitResult.length; i++){if(!checkEmail(jQuery.trim(mySplitResult[i])))return mySplitResult[i];}}

// add/remove bookmark
function executeFunction(e){ 
    myRequest = new ajaxObject(e.href,processData ,'message');
    myRequest.update('','GET');
    return false;
}

// open homepage
function homepage(link){ myRequest = new ajaxObject(link);myRequest.update('','GET');}

// send mail 
function sendMail(){
    var to = document.getElementById('__to-email').value;
    if(!to){
        displayEmailError('');return false;
    }
    var invalid=splitAndCheckEmail(to);
    if(invalid){
        displayEmailError(invalid);return false;
    }
    var params = "__to-email="+to;
    var mess = document.getElementById('__message').value;
    if(mess) params += "&__message="+mess;
    var subject = document.getElementById('__subject').value;
    if(subject) params += "&__subject="+subject;
    myRequest = new ajaxObject('/component/accommodation/functions/recommand.jx?cocoon-view=debug-raw&acco_id='+$Obj('acco_id').innerHTML+'&'+params,processRecommandationData ,'message');
    myRequest.update('','GET');
    //document.getElementById('emailerror').style.display='none';
}

function displayEmailError(invalid){
    alert("Invalid Email address "+invalid+"!");
    /*
    document.getElementById('emailerror').innerHTML="Invalid Email address "+invalid+"!";
    document.getElementById('emailerror').style.display='';
    */
    document.getElementById('sendbutton').disabled=false;
}

// call back function for bookmark
function processData(responseText, responseStatus,responseXML,container) {
  message=document.getElementById(container);
  if (responseStatus==200) {
    if(message){
        message.innerHTML = responseText;
        message.style.display="";
        setTimeout("hideDiv(message)",10000);
    }
  } else {
    //alert(responseStatus + ' -- Error Processing Request');
  }
  /*
  message=document.getElementById(container);
  if (responseStatus==200) {
    var mess = responseXML.documentElement.firstChild;
    if(mess && getInnerText(mess)=='true')
        message.innerHTML = 'Bookmark saved sucessufuly !';
    else
        message.innerHTML = 'Bookmark could not be saved!';
    message.style.display="";
    setTimeout("hideDiv(message)",10000);
  } else {
    //alert(responseStatus + ' -- Error Processing Request');
  }
  */
}

//call back function for sending mail
function processRecommandationData(responseText, responseStatus,responseXML,container) {
  message=document.getElementById(container);
  if (responseStatus==200) {
    if(message){
        message.innerHTML = responseText;
        document.getElementById('sendbutton').disabled=false;
        toggleSlide('emailDiv');
        message.style.display="";
        setTimeout("hideDiv(message)",10000);
    }
  } else {
    //alert(responseStatus + ' -- Error Processing Request');
  }
  /*
  message=document.getElementById(container);
  if (responseStatus==200) {
    var mess = responseXML.documentElement.firstChild;
    if(mess && getInnerText(mess)=='true'){
        message.innerHTML = 'Thank You for sharing this accommodation!';
        document.getElementById('sendbutton').disabled=false;
        toggleSlide('emailDiv');}
    else
        message.innerHTML = 'Problems occured while sending mail!';
    message.style.display="";
    setTimeout("hideDiv(message)",10000);
  } else {
    //alert(responseStatus + ' -- Error Processing Request');
  }
  */
}

// call calender called when the page is loaded
function loadCalendar(){if(document.getElementById('callink')){var url=document.getElementById('callink').href;
if(url){var calendar = document.getElementById('calendar');calendar.innerHTML = "<p>Loading...<\/p>";
var myRequest = new ajaxObject(url, processTabberData ,document.getElementById('calendar'));myRequest.update('','GET');}}}
// called to refresh the calender
function reloadCalendar(elem,param){
	var url=elem.href;
	loading('loading','calendardata');
	var myRequest = new ajaxObject(url, processTabberData ,document.getElementById('calendar'));myRequest.update('','GET');}
// show hide fun for calendar data
function showDetails(img){var loading = document.getElementById('d|'+img.id);loading.style.left = getX(img)+10 + 'px';
loading.style.top = getY(img) +15+ 'px';loading.style.display = 'block';}

function hideDetails(img){var loading = document.getElementById('d|'+img.id);loading.style.display = 'none';}
function getY( oElement ){var iReturnValue = 0;while( oElement != null ) {iReturnValue += oElement.offsetTop;oElement = oElement.offsetParent;}return iReturnValue;} function getX( oElement){var iReturnValue = 0;while( oElement != null ){iReturnValue += oElement.offsetLeft;oElement = oElement.offsetParent;}return iReturnValue;}
//called when hovered over the chart
var lastday;
function showdate(e,obj)
{
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		posx = e.clientX + document.body.scrollLeft;
		posy = e.clientY + document.body.scrollTop;
	}
	
	var oX = getX(obj);var oY = getY(obj);
	//var oX = obj.offsetLeft;var oY = obj.offsetTop;
	//while(obj.parentNode){// finds the absolute position of the object
	//oX=oX+obj.parentNode.offsetLeft;
	//oY=oY+obj.parentNode.offsetTop;
	//if(obj==document.getElementsByTagName('body')[0]){break}
	//else{obj=obj.parentNode;}
	//}
	var mX=posx-oX;//relative X
	var mY=posy-oY;//relative Y
	
	if(mX && mY && mX-48>0){
	    var day = parseInt((mX-48)/1.66);
	    var doc = document.getElementById(day);
	    if(doc){
	        doc.style.backgroundColor="red";
	        lastel = document.getElementById(lastday);
	        if(lastel)
	            lastel.style.backgroundColor="";
	        lastday=day;
	        var mp=document.getElementById('mapmap');
	        mp.innerHTML=document.getElementById('dt|'+day).innerHTML+':'+document.getElementById('d|'+day).innerHTML;
	        mp.style.top = posy+10+'px';mp.style.left=posx+10+'px';
	        document.body.appendChild(mp);
	        document.getElementById('mapmap').style.display="";
	    }
	}
	
}

//load map 
var map;var geocoder;var baseIcon;var gmarkers=[];var accomarkers=[];var bounds;
function load() {
    if(document.getElementById("map")){
        map = new google.maps.Map2(document.getElementById("map"));
        geocoder = new google.maps.ClientGeocoder();
        map.setCenter(new google.maps.LatLng(20.00, 0.0), 3);
        map.addControl(new google.maps.LargeMapControl());
        map.addControl(new google.maps.MapTypeControl());
        map.addControl(new google.maps.OverviewMapControl);
        map.setMapType(G_HYBRID_MAP) ;
        baseIcon = new google.maps.Icon();
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new google.maps.Size(20, 34);
        baseIcon.shadowSize = new google.maps.Size(37, 34);
        baseIcon.iconAnchor = new google.maps.Point(9, 34);
        baseIcon.infoWindowAnchor = new google.maps.Point(9, 2);
        baseIcon.infoShadowAnchor = new google.maps.Point(18, 25);
        if(document.getElementById('latitude') && document.getElementById('longitude')){
            bounds = new GLatLngBounds();
            if(document.getElementById('latitude').value && document.getElementById('longitude').value){
                var pro = new AccoMarker("1", document.getElementById('address').value, document.getElementById('latitude').value,document.getElementById('longitude').value);
                map.setCenter(pro.location,15);
            }else{
                var address=document.getElementById('address').value+', '+document.getElementById('country').value+', '+document.getElementById('continent').value;
                showAddress(address);
                map.setZoom(map.getBoundsZoomLevel(bounds));
                map.setCenter(bounds.getCenter());
            }
        }
        if(typeof(panoramiophotos) !== 'undefined' && panoramiophotos){
        	var panicon = new GIcon();
        	panicon.image = "/images/map/marker/panmarker.png";
        	panicon.shadow = "/images/map/marker/panshadow.png";
        	panicon.iconSize = new GSize(18, 18);
        	panicon.shadowSize = new GSize(22, 22);
        	panicon.iconAnchor = new GPoint(9, 9);
        	panicon.infoWindowAnchor = new GPoint(9, 0);
        	
        	var panimdiv=document.getElementById('panimages');
        	var panouterdiv=document.getElementById('panimagesouter');
        	if(panouterdiv && panoramiophotos.length>0)
        		panouterdiv.style.display='';
        	for (var i = 0; i < panoramiophotos.length; i++)
    		{
        		var markerpan = createPanMarker(panicon,panoramiophotos[i])
        	    map.addOverlay(markerpan);
        		if(panimdiv){
        			var panimurl=panoramiophotos[i].photo_file_url;
        			panimdiv.innerHTML+=" " +
        					"<a title='<a class=\"viewinpanoramio\" target=\"_blank\" href="+panoramiophotos[i].photo_url+">" +
        							"View this photo by <strong>"+panoramiophotos[i].owner_name+"</strong> in Panoramio</a>' rel=\"prettyPhoto[galleryTwo]\"" +
        									"href="+panimurl.replace(/small/, "medium")+"> " +
        											"<img style='margin-right:2px;border:1px solid #DEDEDE' src='"+panimurl.replace(/small/, "square")+"' alt='"+panoramiophotos[i].photo_title+"'></img>";
        		}
    		}
        	$(".gallery-p a[rel^='prettyPhoto[galleryTwo]']").prettyPhoto({theme: 'light_rounded'});
        }
   }
}

function createPanMarker(panicon,panphoto){
	var markerpan = new GMarker(new GLatLng(panphoto.latitude, panphoto.longitude), panicon);
	var p = panphoto;
	var html ="<div id='infowin' style='height:" + (p.height + 50) + "px; width:" + (p.width + 10) + "px'>" +
			"<p><a id='photo_infowin' target='_blank' href='" + p.photo_url + "'>" + "<img border=0 width='" + p.width + "' height='" + p.height + "' src='" + p.photo_file_url + "'></a>"+ 
			//"<p><a target='_blank' class='photo_title' href='" + p.photo_url + "'>" + p.photo_title + "</a></p>" + 
			"<div style='text-align:left;font:9px'>Author:<a target='_blank' class='photo_title' href='" + p.owner_url + "'>" + p.owner_name+ "</a><br/>" + 
			
			"<p style='font-size:6px'><a href='http://www.panoramio.com/' target='_blank'><img src='/map/images/panoramio.gif' alt='Panoramio logo' border=0/><\/a><br/>" +
			"Photos provided by Panoramio are under the copyright of their owners</p></div>" +"</div>" + "</div>";
	GEvent.addListener(markerpan, "click", function() {
		markerpan.openInfoWindowHtml(html);
      });
      return markerpan;
}

function showAddress(add) {geocoder.getLatLng(add,function(point) {if (point) {new AccoMarker("1",add.replace(/,/,'<br/>'),point.lat(),point,lng());}else{document.getElementById('map').innerHTML='Location could not be located'}});}
function hideDiv(message){message.style.display="none";}

// slide show start
function slideshow(obj){
        var height = 620;
        var width = 605;
        var innerHeight = 0;
  		var innerWidth = 0;
  		document.featured1.src='/icons/loader.gif';

  		if ( window.innerWidth && window.innerHeight ) 	                                                    
  		{	//for Netscape
	    innerHeight = window.innerHeight;
    	innerWidth = window.innerWidth;
		} else if ( document.body.clientWidth && document.body.clientHeight ) 
  		{	// for IE
    		innerHeight = document.body.clientHeight;
    		innerWidth = document.body.clientWidth;
  		}
	  	document.getElementById("slidshow").style.width=(innerWidth)+ "px";
	  	document.getElementById("slidshow").style.height=(innerHeight+500) + "px";
	  	document.getElementById("slidshow").style.display = "";
	  	document.featured1.height=540;
	  	if(innerHeight<height){
	  		height=innerHeight-10;
	  		document.featured1.height=innerHeight-90;
	  	}
	  	if(innerWidth<width){
	  		width=innerWidth-10;
	  		document.featured1.width=innerWidth-20;
	  		$Obj(disimages).style.width=innerWidth-60;
	  	}
	  	document.getElementById("comps").style.top = parseInt((innerHeight - height)/2,10) + "px";
	    document.getElementById("comps").style.left = parseInt((innerWidth - width)/2,10) + "px";
	    document.getElementById("comps").style.width=width+ "px";
	  	document.getElementById("comps").style.height=height + "px";
	  	//document.featured1.src=obj.firstChild.src.replace(/web/, "screen");
	  	testImage(obj.firstChild);
	  	if(document.getElementById('display')){
	  		document.getElementById("disimages").innerHTML=document.getElementById('display').innerHTML;
	  		var nodes= document.getElementById("disimages");
	  		var no = nodes.getElementsByTagName("img");
	  		for(i=0;i<no.length;i++){
	  			var im = no[i];
	  			//im.onmouseover=function () {document.featured1.src='/icons/loader.gif';document.featured1.src=this.src.replace(/web/, "screen");}
	  			im.onmouseover=function () {testImage(this);}
	  		}
	  	}
}

function testImage(imgmain) {
	document.featured1.src='/icons/loader.gif';
	var tester=new Image();
	tester.onload=function () {document.featured1.src=imgmain.src.replace(/web/, "screen");};
	tester.onerror=function () {document.featured1.src=imgmain.src;};
	tester.src=imgmain.src.replace(/web/, "screen");
}

//search price 
function getPrice(button){
    loading('priceloading','priceform');
	var params = '';
	var timemin = document.getElementById('timeminprice').value;
    if(!timemin){
    	alert('from date cannot be null!');$Obj('priceloading').style.display = 'none';button.disabled=false;return false;}
    params +='q_timemin='+timemin+'&';
    var timemax = document.getElementById('timemaxprice').value;
    if(!timemax){
    	alert('to date cannot be null!');$Obj('priceloading').style.display = 'none';button.disabled=false;return false;}
    params +='q_timemax='+timemax+'&';
    
    var q_persons = $Obj('q_personsprice').value;
    if(q_persons) params += 'q_persons='+q_persons+'&';
    else{alert('Select the number of persons travelling!');$Obj('priceloading').style.display = 'none';button.disabled=false;return false;}
    var q_kids = $Obj('q_kids').value;
    if(q_kids) params += 'q_kids='+q_kids+'&';
    params +='1=1';
    var myRequest = new ajaxObject($Obj('linkforprice').href+'&'+params, processPriceData,'pricedata');
    myRequest.update('','GET');
    button.disabled=false;
}
//call back function for price
function processPriceData(responseText, responseStatus,responseXML,container) {
	  if (responseStatus==200) {
	    if(container && document.getElementById(container)){
	        document.getElementById(container).innerHTML = responseText;
	        $Obj('priceloading').style.display = 'none'
	    }
	  } else {
	    //alert(responseStatus + ' -- Error Processing Request');
	  }
	}
function loading(load,container,width) {
    var loading = document.getElementById(load);
    var data = document.getElementById(container);
    if(loading && data){
    loading.style.height = data.offsetHeight+'px';
    loading.style.left = getX(data) + 'px';
    loading.style.top = getY(data) + 'px';

    if(width)loading.style.width= width;
    else loading.style.width= data.offsetWidth+'px';
    loading.style.display = 'block';}
}
// toogle slider div (Unterkunft)
var fromtext="";var totext="";
var minsl =0;var maxsl =0;var valsl;
function toggleSliderdiv(){
    if(fromtext==""){
        fromtext=$("#datefromtext").html();
        totext=$("#datetotext").html();
    }
    if($('input[name=flexi]').is(':checked')){
        $("#datefromtext").html(flfromtext);
        $("#datetotext").html(fltotext);
    }else{
        $("#datefromtext").html(fromtext);
        $("#datetotext").html(totext);
    }
    // Slider
    $("#slidertogglediv").toggle("slow");
    $("#slider").slider({range: "min",min: minsl,max: maxsl,value:valsl,animate: true,slide: function(event, ui) {$("#q_days").val(ui.value);}});
    $('#q_days').keyup(function(){
			var slider1Value = +$("#q_days").attr("value"); 
			if(slider1Value >= minsl && slider1Value <= maxsl){
				$("#slider").slider('option', 'value', parseInt(slider1Value));
				valsl = slider1Value;
			}else{
				//alert('Please enter a value between '+slider1Min+' and '+slider1Max);
				$("#q_days").val(valsl);
				return false;
			}
		});
    
    updateSliderValues();
}

function updateSliderValues(){
    var dateMin = $("#timemin").datepicker("getDate");var dateMax = $("#timemax").datepicker("getDate");
    if(dateMin!= null && dateMax!= null){
        var one_day=1000*60*60*24;
        minsl=1;
        maxsl = Math.ceil(((dateMax.getTime()-dateMin.getTime())/one_day));
        valsl = maxsl>7?7:maxsl;
        $("#q_days").val(valsl);
        $('#slider').slider('option', 'min', minsl);
        $('#slider').slider('option', 'max', maxsl);
        $('#slider').slider('option', 'value', valsl);
    }
}




