//$browserType=$inputData['vBrowserType'];
// JavaScript Document

//===========================================================//
//==============Global Variables=============================//
//===========================================================//

//map handle
var globmap;
//initial y - latitude
var initlat='39.614152077002636';
//initial x - longitude
var initlng='19.9127197265625';
//initial zoom level
var initzm=10;
//context menu handle
var contextmenu;
// event handle
var gEventClick=null;

//lat-y input definition
var yInput='lat'; 

//long-x input definition
var xInput='long'; 

var vCategories=new Array;
var vExtraFields=new Array;

var PageClick;  
var vPageCount=0;
var vCurrentPage=1;

var xhrCurrent=null;

var daysSelected=new Array();

var globOrderflag=0;
var globThisObj=null;

var htmlLoading = '<div class="ajaxLoader"><img height=\"150\"  src="images/main-ajax-loder.gif"><div>';

var geocMarker = null;//center marker of geocoding search

var vLastSubCategory = -1;//last selected category

var searchAround = 0; //search type flag {around , general}

var lastGlobObj = null;

var beachesRegions = new Array();
//===========================================================//
//===========================================================//
//===========================================================//


//=======Configure function menu=====================================================================================================//
      
      function saveMarker(){
        //put your code here
        
        
      }

//===================================================================================================================================//


//===================================================================================================================================//
//===========================Prototype Functions=====================================================================================//
//===================================================================================================================================//

Array.prototype.findIndex = function(searchId,typeId) {
  var returnIndex = -1;
  for (i=0; i<this.length; i++) {
    switch(typeId){
    case 1:
      if (this[i].myMarkerCatId== searchId){ returnIndex=i; }
      break;
    case 2:
      if (this[i].myMarkerId== searchId){ returnIndex=i; }
      break;
    default:
      if (this[i].id== searchId){ returnIndex=i; }  
    }
     
  }
  return returnIndex;
}


Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}

//===================================================================================================================================//
//===================================================================================================================================//
//===================================================================================================================================//

//custom objects constructor
function attrobj(objid,objvalue,catid){
 var id;
 var value;
 var categ;

 this.id=objid; 
 this.value=objvalue;
 this.categ=catid; 

}

  
var jsonStr;

//0=bussines
//1=agenda
var searchType=0;

function clearHighlightedSpan(){
  //Remove the highlighted style
  $.each($('.sub-menu-titles'),function(i,val){
    $(this).removeClass('sub-menu-title-down');
  });
}

function clearCategories(){
  
  clearHighlightedSpan();
  $.each($('.sub-menu a.chckBtn.down[sp_in=false]'), function(i, val) { 
    $(this).toggleClass("down");
    if($(this).attr('class')=='chckBtn down'){
      $(this).css({'background':'url(micons/'+$(this).attr('tik-icon')+') no-repeat 0 0'},1);
    }else {
      $(this).css({'background':'url("images/layout/untik-hotels.jpg") no-repeat scroll 0 0 transparent'},1);
    }
  });
}

function clearSpecialInterest(){
  spInSelected = new Array();
  clearHighlightedSpan();
  $.each($('.sub-menu a.chckBtn.down[sp_in=true]'), function(i, val) { 
    $(this).toggleClass("down");
    if($(this).attr('class')=='chckBtn down'){
      $(this).css({'background':'url(micons/'+$(this).attr('tik-icon')+') no-repeat 0 0'},1);
    }else {
      $(this).css({'background':'url("images/layout/untik-hotels.jpg") no-repeat scroll 0 0 transparent'},1);
    }
  });
}

function initBreadCrumb(){

    $('#Breadcrumb_wrap').html('<ul id="breadcrumb"><li><a title="Categories">Categories</a></li></ul>');

}

function clearAll(myCallback,obj){
  //clear leftover tipsy
  $('.tipsy').remove();
  
  initBreadCrumb();

  if(geocMarker != null )globMap.removeOverlay(geocMarker);//delete the center marker
  
  $('#searchField').val('');
  
  initDutyIcons();
  
  $('#showOnMapImg').attr({"src":"images/layout/showonmap.jpg"},1);
  $('#whatsOnImg').attr({"src":"images/layout/whatson.jpg"},1);
  
  $('#special_tags').slideUp();
  $('#special_tags_container').html('');
  if((obj != null) && (obj.attr('sp_in')=='false')){
    $.each($('.sub-menu-titles'),function(i, val){
      $(val).removeClass('sub-menu-title-down');
    });
    $('#showOnMapImg').attr({"src":"images/layout/showonmap.jpg"},1);
    $('#whatsOnImg').attr({"src":"images/layout/whatson.jpg"},1);
    $('.sub-menu:visible').prev(".left_menu_list a.hdr:").click();
  }
  clearCategories();
  clearSpecialInterest();
  
  globMap.clearOverlays();
  rmvfClickEvent();
  $("#pager").pager({pagenumber:0, pagecount: 0, buttonClickCallback: PageClick });
  $("#pager2").pager({pagenumber:0, pagecount: 0, buttonClickCallback: PageClick });
  $('#results_wrap').html('').animate({height: "0px"},500,function(){
    if(myCallback)myCallback();
  });
  
}

function scrollOnTop(glatlng,poiId,region){
  $('html, body').animate({scrollTop:0}, 'medium',function(){
      globMap.setZoom(15);
      if(glatlng)globMap.panTo(glatlng);
      if(poiId){globMap.defaultStateAll();globMap.getMarkerById(poiId).onMouseOver();}
      if(region){
      

        var myPolygon = addRegion(region);
        
        var bounds = new GLatLngBounds();
        var sW=new GLatLng(parseFloat(myPolygon.getBounds().getSouthWest().lat()),parseFloat(myPolygon.getBounds().getSouthWest().lng()));
        var nE=new GLatLng(myPolygon.getBounds().getNorthEast().lat(),myPolygon.getBounds().getNorthEast().lng());
        bounds.extend(sW);
        bounds.extend(nE);
        var helpSearchAround = searchAround; 
        if(searchAround == 1) searchAround = 0;
          globMap.setCenter(new GLatLng(bounds.getCenter().lat(),bounds.getCenter().lng()),globMap.getBoundsZoomLevel(bounds));
        searchAround = helpSearchAround;  
        bounds=0;
        sW=nE=0;
      
      
      }
  });
}

function initDutyIcons(){
  $('#Gas').find('img').attr({'src':'images/layout/gas_1.png'},1);
  $('#Pha').find('img').attr({'src':'images/layout/medical_1.png'},1);
}

function addMarkers(flag,thisObj){
   //var p=$('#param3infokiosk').val(); 
   //alert('add Markers flag='+flag+' param3infokiosk='+p); 

  if(thisObj)
    lastGlobObj = thisObj;
  else if(lastGlobObj!=null)
    thisObj = lastGlobObj;
     
  
  if(flag==0)vCurrentPage=1;
  //flag = search triggered from
  //0 : search text
  //1 : Left Menu
  //2 : Pager
  globOrderflag=flag;
  globThisObj=thisObj;
  searchType=0;

  //if there is special interest checked clear
  clearSpecialInterest();
  //set default state of duty icons
  initDutyIcons();
  
  $('#showOnMapImg').attr({"src":"images/layout/showonmap5.gif"},1);
  $('#whatsOnImg').attr({"src":"images/layout/whatson.jpg"},1);
  
  if(xhrCurrent){
    xhrCurrent.abort();
    $('DIV').stop();
  }
  
  vCategories=new Array();
  $.each($('.sub-menu a.chckBtn.down'),function(i, val){ 
    if($(val).attr('title')!='All'){//Διώχνω εκτός το πρώτο (check all)
      vCategories.push($(val).attr('cat_id'));
    }
  });
  var vJson={};//the complete json data to post
  var vExtraFieldsJson={};//extra fields json
  var jsonStr='';//serialized string of json
  var jsonBounds={};
  
  if($('#param3infokiosk').val()=='car'){
     vJson.vExtraFields='[{"id":"589","value":["752"],"categ":"45"}]';
  }
  if($('#param3infokiosk').val()=='boat'){
     //alert('add me 2'); 
     vJson.vExtraFields='[{"id":"589","value":["753"],"categ":"45"}]';
     //$('#param3infokiosk').val('');
  }
  if($('#param3infokiosk').val()=='walk'){
     vJson.vExtraFields='[{"id":"589","value":["752"],"categ":"45"}]';
     //alert('add me 3'); 
     //$('#param3infokiosk').val('');
  
  }
  if($('#param3infokiosk').val()=='orthodox'){
     vJson.vExtraFields='[{"id":"591","value":["756"],"categ":"48"}]';
  }
  if($('#param3infokiosk').val()=='catholic'){
     vJson.vExtraFields='[{"id":"591","value":["757"],"categ":"48"}]';
  }
  if($('#param3infokiosk').val()=='other'){
    vJson.vExtraFields='[{"id":"591","value":["758"],"categ":"48"}]';   
  }
  if($('#param3infokiosk').val()==''){
   // alert('add me 4'); 
    vJson.vExtraFields=$.toJSON(vExtraFields);  
  } 
  //vJson.vExtraFields=$.toJSON(vExtraFields);   
  //alert('vJson.vExtraFields'+$.toJSON(vExtraFields));
  vJson.vCategories=vCategories;
  if(!detectBrowser() && searchAround == 1)vJson.vBounds=[globMap.getBounds().getSouthWest(),globMap.fromContainerPixelToLatLng(new GPoint(624,92))];//62
  vJson.vPage=vCurrentPage;
  vJson.vSearchText=$('#searchField').val();//'ar';//$('input[class=box]').val();
  //prosthiki logw provlimatos me autakia kai json
  vJson.vSearchText=vJson.vSearchText.replace(/\"/g,"|||");
 
  vJson.vArea=$('#sb-Area').attr('mValue');
  if(detectBrowser())vJson.vBrowserType = 'true';
  else vJson.vBrowserType = 'false';
  vJson.vLastTable = $(thisObj).attr('table_id');//$(thisObj).parent().parent().prev().text();
  
  if($(thisObj).next().attr("cat_name") && $(thisObj).attr("class") == "chckBtn down"  )
    vLastSubCategory = $(thisObj).next().attr("cat_name");
  else 
    vLastSubCategory = -1;
  
  vJson.vLastSubCategory = vLastSubCategory;
  vJson.vOrder=flag;
  
  jsonStr=JSON.stringify(vJson);//serialize the json object before you post it
  jsonStr=jsonStr.replace('\"/g','"');
  jsonStr=jsonStr.replace('"[',"[");
  jsonStr=jsonStr.replace(']"',"]");
  //alert('jsonStr='+jsonStr);
  if($('#results_wrap').height()<=150){
  $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\" src="images/main-ajax-loder.gif"><div>');
    $('#results_wrap').animate({height: "150px"},500,function(){
      $('.ajaxLoader2').fadeIn('1000',function(){
          xhrCurrent=$.post('search.php?nomarkers=1',{ data: jsonStr},function(msg){
            //////////////new add maria infokiosk///////
            //alert('xoxoxo1');
          
            if($('#param3infokiosk').val()=='car'){
                $("select").val(752);
            }
            if($('#param3infokiosk').val()=='boat'){
                $("select").val(753);
            }
            if($('#param3infokiosk').val()=='walk'){
                 $("select").val(754);
            }
            if($('#param3infokiosk').val()=='orthodox'){
                 $("select").val(756);
            }
            if($('#param3infokiosk').val()=='catholic'){
                 $("select").val(757);
            }
            if($('#param3infokiosk').val()=='other'){
                 $("select").val(758);
            }
            $('#param3infokiosk').val('');
            /////////////////////////////////////////
            $('#searchField').val('');
            $("#pager").pager({pagenumber:vCurrentPage, pagecount: vPageCount, buttonClickCallback: PageClick });
              $('.ajaxLoader2').fadeOut('slow', function(){
                $('#results_wrap').html(msg);
                $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                  $('.result-wrapper-fade').fadeIn('100',function(){
                    $('#results_wrap center').fadeIn('20');
                    if(searchAround == 1){
                      vMark.remove();
                      globMap.addOverlay(vMark);
                    }
                      //$('#map_wrapper').unblock();                    
                  });
                });
              });
          },"text");
      });
    });
  }else{
    $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\"  src="images/main-ajax-loder.gif"><div>'); 
    $('#results_wrap').animate({height: "150px"},500,function(){
      $('.ajaxLoader2').fadeIn('1000',function(){
            xhrCurrent=$.post('search.php?nomarkers=1',{ data: jsonStr},function(msg){
            //////////////new add maria infokiosk///////
            //alert('xoxoxo2');
          
            if($('#param3infokiosk').val()=='car'){
                $("select").val(752);
            }
            if($('#param3infokiosk').val()=='boat'){
                $("select").val(753);
            }
            if($('#param3infokiosk').val()=='walk'){
                 $("select").val(754);
            }
            if($('#param3infokiosk').val()=='orthodox'){
                 $("select").val(756);
            }
            if($('#param3infokiosk').val()=='catholic'){
                 $("select").val(757);
            }
            if($('#param3infokiosk').val()=='other'){
                 $("select").val(758);
            }
            $('#param3infokiosk').val('');
            /////////////////////////////////////////
            $('#searchField').val('');
              $("#pager").pager({pagenumber:vCurrentPage, pagecount: vPageCount, buttonClickCallback: PageClick });
                $('.ajaxLoader2').fadeOut('slow', function(){
                                  $('#results_wrap').html(msg);
                  $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                    $('.result-wrapper-fade').fadeIn('100',function(){
                      $('#results_wrap center').fadeIn('20');
                     if(searchAround == 1){
                      vMark.remove();
                      globMap.addOverlay(vMark);
                    }
                    //$('#map_wrapper').unblock();
                    });
                  });
                });
            },"text");
        });
    });
  
  }

}



function addExtraField(obj){
  //alert('addExtraField'+$(obj).name());  
  if(($(obj).val()==-1) || ($(obj).attr('checked')==false) || ($(obj).val()==null) ){
     
  if(vExtraFields.length!=1)
    //find the index position of the given object and swap it with the last before you pop it
    //alert('vExtraFields='+vExtraFields[vExtraFields.findIndex($(obj).attr('attr_id'))]);
    vExtraFields[vExtraFields.findIndex($(obj).attr('attr_id'))]=vExtraFields[(vExtraFields.length-1)];
    //alert('1 vExtraFields='+vExtraFields[vExtraFields.findIndex($(obj).attr('attr_id'))]);
    vExtraFields.pop();
    
  }else{
    //check if is allready inside the array there is no need to put it twice
    if(vExtraFields.findIndex($(obj).attr('attr_id'))==-1)
      vExtraFields.push(new attrobj($(obj).attr('attr_id'),$(obj).val(),$(obj).attr('cat_id')));
    
    else
      vExtraFields[vExtraFields.findIndex($(obj).attr('attr_id'))]= new attrobj($(obj).attr('attr_id'),$(obj).val(),$(obj).attr('cat_id'));
      //alert('2 vExtraFields='+vExtraFields.findIndex($(obj).attr('attr_id'))+' a='+$(obj).attr('attr_id')+' val='+$(obj).val()+' cat_id='+$(obj).attr('cat_id') );
  }  
  

}

function geo_suggestions(Geocoder,address){

var suggestionText=new Array();

Geocoder.getLocations(address, function (result)
          {   if(address!="")address+=" Ελλάδα"
              if (result.Status.code == G_GEO_SUCCESS) {
              // ===== If there was more than one result, "ask did you mean" on them all =====
                //alert(result.Placemark.length);
                // Loop through the results
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates;//place("+p[1]+","+p[0]+","+mapId+","+Geocoder+",1);
                  var addArray=new Array();
                  addArray=result.Placemark[i].address.replace(',',' ');
                  //suggestionText+=addArray+", ";
                  suggestionText.push(result.Placemark[i].address.replace(',',' '));
                }
                return suggestionText;
            }
            // ====== Decode the error status ======
            else {
              
              suggestionText.push('nothing');
              return suggestionText;
            }
          }
        );


}
var suggestAddresses = new Array();
function initautocomplete(sType){
 
    $(":input").unautocomplete();
    
    if(sType=='Address'){    
      $('#searchField').geo_autocomplete(new google.maps.Geocoder,{
    		mapkey: vMapkey, 
    		selectFirst: false,
    		minChars: 3,
    		cacheLength: 50,
    		width: 300,
    		scroll: true,
    		scrollHeight: 330
    	}).result(function(_event, _data) {
    		if (_data){ 
        		try{
              globMap.fitBounds(_data.geometry.viewport);
            }catch(err){
              vdata=_data;
              globMap.setCenter(new GLatLng(_data.geometry.location.lat(),_data.geometry.location.lng()),14);
              
              if(geocMarker != null )globMap.removeOverlay(geocMarker);
              geocMarker = new GMarker(new GPoint(_data.geometry.location.lng(),_data.geometry.location.lat()),{title:_data.formatted_address})
              globMap.addOverlay(geocMarker);
              
              //alert(err.message+' '+_data.geometry.location.lng());
            }
        }
    	});
    	
     $('#searchField').keydown(function(key){
      
     });    	

    }else if(sType=='Business'){
        //alert($('#sb-Area').attr('mValue'));
        $("#searchField").autocomplete('autocomp_search.php?type=Business&vArea='+$('#sb-Area').attr('mValue'), {
      		width: 300,
      		selectFirst: false,
      		max:10,
      	  formatResult: function(data, value) {
      			return value.split(" - ")[0];
      			
      		}
    	 }).result(function() {
          addMarkers(0);
        });

    	 
     $('#searchField').keydown(function(key){if(key.keyCode==13)addMarkers(0);});
    }

}

function addAgendaMarkers(){

$('.sub-menu:visible').prev(".left_menu_list a.hdr:").click();
$('#special_tags_container').fadeOut(100).html('').fadeIn(10);


$('#showOnMapImg').attr({"src":"images/layout/showonmap.jpg"},1);
$('#whatsOnImg').attr({"src":"images/layout/whatson3.gif"},1);

if($('#results_wrap').height()<=150){
  $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\" src="http://www.elevatestechnology.com/pbcmdc1/edu/skin/images/ajax_loader-2.gif"><div>');
    $('#results_wrap').animate({height: "150px"},500,function(){
    
    
          $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\"  src="images/main-ajax-loder.gif"><div>'); 
          $('.ajaxLoader2').fadeIn('1000',function(){
          var vJsonstr2={};
          vJsonstr2.days=daysSelected;
          vJsonstr2.vPage=vCurrentPage;
          vJsonstr2.vCategories=$('#attrCateg').attr('mValue'); 
          vJsonstr2.vArea=$('#areaAgenda').attr('mValue');          
          //alert($('#attrCateg').attr('mValue'));
          
          $.post('searchAgenda.php',{ data: vJsonstr2},function(msg){
                    

            $("#pager").pager({pagenumber:vCurrentPage, pagecount: vPageCount, buttonClickCallback: PageClick });
              $('.ajaxLoader2').fadeOut('slow', function(){

                $('#results_wrap').html(msg);
                $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                  $('.result-wrapper-fade').fadeIn('100',function(){
                    $('#results_wrap center').fadeIn('20');
                  });
                });

              });
          },"text");
        });
    });

}else{

          $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\" style="margin-top:30px;" src="http://www.elevatestechnology.com/pbcmdc1/edu/skin/images/ajax_loader-2.gif"><div>'); 
          $('.ajaxLoader2').fadeIn('1000',function(){
          var vJsonstr2={};
          vJsonstr2.days=daysSelected;
          vJsonstr2.vPage=vCurrentPage;
          vJsonstr2.vCategories=$('#attrCateg').attr('mValue');
          vJsonstr2.vArea=$('#areaAgenda').attr('mValue');           
          //alert($('#attrCateg').attr('mValue'));
          
          $.post('searchAgenda.php',{ data: vJsonstr2},function(msg){          
            $("#pager").pager({pagenumber:vCurrentPage, pagecount: vPageCount, buttonClickCallback: PageClick });
              $('.ajaxLoader2').fadeOut('slow', function(){
                $('#results_wrap').html(msg);
                $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                  $('.result-wrapper-fade').fadeIn('100',function(){
                    $('#results_wrap center').fadeIn('20');
                  });
                });
               
              });
          },"text");
        
        });


}



}

function addMarkersTodays(st){
initDutyIcons();

$('#showOnMapImg').attr({"src":"images/layout/showonmap.jpg"},1);
$('#whatsOnImg').attr({"src":"images/layout/whatson.jpg"},1);

  
  if(xhrCurrent){
    xhrCurrent.abort();
    $('DIV').stop();
  }
  


  var url = 'searchDuties.php'; 
  
  if($('#results_wrap').height()<=150){
  $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\" src="images/main-ajax-loder.gif"><div>');
    $('#results_wrap').animate({height: "150px"},500,function(){
      $('.ajaxLoader2').fadeIn('1000',function(){
          xhrCurrent=$.post(url,{ type:st },function(msg){
            $("#pager").pager({pagenumber:vCurrentPage, pagecount: 0, buttonClickCallback: PageClick });
              $('.ajaxLoader2').fadeOut('slow', function(){
                $('#results_wrap').html(msg);
                $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                  $('.result-wrapper-fade').fadeIn('100',function(){
                    $('#results_wrap center').fadeIn('20');
                  });
                });
              });
          },"text");
      });
    });
    
  }else{
    
    $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\"  src="images/main-ajax-loder.gif"><div>'); 
    $('#results_wrap').animate({height: "150px"},500,function(){
      $('.ajaxLoader2').fadeIn('1000',function(){
            xhrCurrent=$.post(url,{ type:st },function(msg){
              $("#pager").pager({pagenumber:vCurrentPage, pagecount: 0, buttonClickCallback: PageClick });
                $('.ajaxLoader2').fadeOut('slow', function(){
                  $('#results_wrap').html(msg);
                  $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                    $('.result-wrapper-fade').fadeIn('100',function(){
                      $('#results_wrap center').fadeIn('20');
                    });
                  });
                });
            },"text");
        });
    });
  
  }

}

window.onload = function() {
    
    document.getElementById('datepicker').onselectstart = function() {return false;} // ie
    document.getElementById('datepicker').onmousedown = function() {return false;} // mozilla
}

 function addSpecialMarkers(){
   
   if($('#results_wrap').height()<=150){
  $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\" src="images/main-ajax-loder.gif"><div>');
    $('#results_wrap').animate({height: "150px"},500,function(){
      $('.ajaxLoader2').fadeIn('1000',function(){
          xhrCurrent=$.post('searchSpIn.php?nomarkers=1',{ data: spInSelected,vPage : vCurrentPage },function(msg){
            $("#pager").pager({pagenumber:vCurrentPage, pagecount: vPageCount, buttonClickCallback: PageClick3 });
              $('.ajaxLoader2').fadeOut('slow', function(){
                $('#results_wrap').html(msg);
                $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                  $('.result-wrapper-fade').fadeIn('100',function(){
                    $('#results_wrap center').fadeIn('20');
                  });
                });
              });
          },"text");
      });
    });
    
  }else{
    
    $('#results_wrap').html('<div class="ajaxLoader2"><img height=\"150\"  src="images/main-ajax-loder.gif"><div>'); 
    $('#results_wrap').animate({height: "150px"},500,function(){
      $('.ajaxLoader2').fadeIn('1000',function(){
            xhrCurrent=$.post('searchSpIn.php?nomarkers=1',{ data: spInSelected ,vPage : vCurrentPage},function(msg){
              $("#pager").pager({pagenumber:vCurrentPage, pagecount: vPageCount, buttonClickCallback: PageClick3 });
                $('.ajaxLoader2').fadeOut('slow', function(){
                  $('#results_wrap').html(msg);
                  $('#results_wrap').animate({height:($('.result-wrapper-fade').height()+15)+'px'},200,function(){
                    $('.result-wrapper-fade').fadeIn('100',function(){
                      $('#results_wrap center').fadeIn('20');
                    });
                  });
                });
            },"text");
        });
    });
  
  }   
   
   
   }


function initBinding(){

  
  
  //tooltip bug fix
  $(document).ajaxSuccess(function(){
    setTimeout(function(){
    $(".cboxElement").colorbox({onClosed:function(){ $('.tipsy').remove(); }});
    },3000);
  });
  
  //bikes map
  $('#horse').colorbox({speed:"slow", iframe:"true", transition:"elastic" , width:"1024px",href:"tiles/bikesmap.php", height:"800px"});
  
  //booking.com
  $('#booking').colorbox({speed:"slow", transition:"elastic" , width:"930px",href:"booking.php", height:"590px"});
  
  $('#Pha').click(function(){clearAll();addMarkersTodays('pha');  $('#Pha').find('img').attr({'src':'images/layout/medical_2.png'},1);});
  $('#Gas').click(function(){clearAll();addMarkersTodays('gas');  $('#Gas').find('img').attr({'src':'images/layout/gas_2.png'},1);});
  
  $("#cheapGasBtn").click(function(){
    var time = 120;
    var obj = $(this);
    var slidetime = 300;  
    //$('#cheapGasContainer').html(htmlLoading);
    if($('#cheapGasContainer').css('display') == 'block')$('#cheapGasContainer').slideUp(slidetime);
    else{ 
      $('#cheapGasContainer').css({'height':'auto'},1);
      $('#cheapGasContainer').html(htmlLoading);
      $('#cheapGasContainer').slideDown(300,function(){ 
          
          $('#cheapGasContainer').css({'height':'148px'},1);
          
          $.post('fuelprices.php',{},function(data){
            $('#cheapGasContainer').find('.ajaxLoader').fadeOut('slow',function(){
              $('#cheapGasContainer').animate({height:'80px'},200,function(){
                $('#cheapGasContainer').html(data);
                //$('#cheapGasContainer').fadeIn('slow');
              });
            });
          });
          
          
      });
      
    }

    //}else $('#cheapGasContainer').slideUp(slidetime,function(){$('#cheapGasContainer').html(htmlLoading);obj.find('img').animate({top:'0px'},time);});
  });
  
  $("#Air").click(function(){
    var time = 120;
    var obj = $(this);
    var slidetime = 300;  
    $('#moreTravel').html(htmlLoading);
    $("#buttonsWrapperTravel").find('img').animate({top:'0px'},100);
    if($('#moreTravel').css('display') == 'block')$('#moreTravel').slideUp(slidetime,function(){$('#moreTravel').html(htmlLoading);});
    var pos = $(this).find('img').css('top');
    if(pos=='0px'){$(this).find('img:eq(0)').animate({top:'5px'},time,function(){$('#moreTravel').slideDown(slidetime,function(){$('#moreTravel').find('.ajaxLoader').fadeOut('100',function(){$('#moreTravel').load('flights.php');});})});
    }else $('#moreTravel').slideUp(slidetime,function(){$('#moreTravel').html(htmlLoading);obj.find('img').animate({top:'0px'},time);});
  });

  $("#Sea").click(function(){
    var time = 120;
    var obj = $(this);
    var slidetime = 300;  
    $('#moreTravel').html(htmlLoading);
    $("#buttonsWrapperTravel").find('img').animate({top:'0px'},100);
    if($('#moreTravel').css('display') == 'block')$('#moreTravel').slideUp(slidetime,function(){$('#moreTravel').html(htmlLoading);});
    var pos = $(this).find('img').css('top');
    if(pos=='0px'){$(this).find('img:eq(0)').animate({top:'5px'},time,function(){$('#moreTravel').slideDown(slidetime,function(){$('#moreTravel').find('.ajaxLoader').fadeOut('100',function(){$('#moreTravel').load('bysea.php');});})});
    }else $('#moreTravel').slideUp(slidetime,function(){$('#moreTravel').html(htmlLoading);obj.find('img').animate({top:'0px'},time);});
  });
 
   $("#Coach").click(function(){
    var time = 120;
    var obj = $(this);
    var slidetime = 300;  
    $('#moreTravel').html(htmlLoading);
    $("#buttonsWrapperTravel").find('img').animate({top:'0px'},100);
    if($('#moreTravel').css('display') == 'block')$('#moreTravel').slideUp(slidetime,function(){$('#moreTravel').html(htmlLoading);});
    var pos = $(this).find('img').css('top');
    if(pos=='0px'){$(this).find('img:eq(0)').animate({top:'5px'},time,function(){$('#moreTravel').slideDown(slidetime,function(){$('#moreTravel').find('.ajaxLoader').fadeOut('100',function(){$('#moreTravel').load('bycoach.php');});})});
    }else $('#moreTravel').slideUp(slidetime,function(){$('#moreTravel').html(htmlLoading);obj.find('img').animate({top:'0px'},time);});
  });

   $('#bus').colorbox({speed:"slow", transition:"elastic" , width:"930px",href:"bus.php", height:"515px"});
   $('#taxi').colorbox({speed:"slow", transition:"elastic" , width:"930px",href:"taxi.php", height:"515px"});
  
  //$("#Air").colorbox({speed:"slow", transition:"elastic" , width:"650px",href:"flights.php",iframe:true, height:"700px"});
      
  
  $('#bottomToolbarHandleWrap').click(function(){
      if($('#bottomToolbarFixed').attr('isHidden')!=0){
        $('#bottomToolbarHandleRight').css({'background':'url("http://cdn.wibiya.com/Graphics_Toolbar/Themes/Round/sprite_lite_gray.png") repeat scroll 0 0px transparent'},1);
        $('#bottomToolbarFixed').animate({
          bottom: '0px'
        },500,function(){
       $('#bottomToolbarFixed').attr({'isHidden':0},1)});        
      }else{
        $('#bottomToolbarHandleRight').css({'background':'url("http://cdn.wibiya.com/Graphics_Toolbar/Themes/Round/sprite_lite_gray.png") repeat scroll 0 -60px transparent'},1);
      $('#bottomToolbarFixed').animate({
          bottom: '-52px'
        },500,function(){
        $('#bottomToolbarFixed').attr({'isHidden':1},1)});
      }
  });  
    

  $('#bt-close').click(function(){
    $(this).slideToggle(10);
    $('#topToolbarFixed').slideToggle(1000);
  });
  
  $('#contactus').colorbox({speed:"slow", transition:"elastic" , width:"630px",href:"contact.php", height:"515px"});
  
  $('#terms').colorbox({speed:"slow", transition:"elastic" , width:"880px",href:"terms.php", height:"580px"});
  
  
  /*
  $('*:not(.colorbximg .cboxElement)').click(function(a){
    
    a.stopPropagation();    
    if($(this).attr('class')!='customselectbtn' && $(this).attr('class')!='sb-item')

    $('.sb-list-round:visible').stop().slideToggle(100);
  
  });
  */
  
  //initialize the agenda days array
  daysSelected=new Array();
  //tdnormal tdchecked
  $.each($('.ui-datepicker-calendar tbody td.tdchecked'),function(i,obj){
    //$(obj).removeClass('tdchecked');
         daysSelected.push("'"+$(obj).attr('date')+"'");
  });
  
  
  //social media change image on hover
  $('#facebook').hover(
      function(){
        $(this).attr({'src':'images/facebook_02.png'},1)
      },
      function(){
        $(this).attr({'src':'images/facebook_01.png'},1)
      });
      
  $('#twitter').hover(
      function(){
        $(this).attr({'src':'images/twitter_02.png'},1)
      },
      function(){
        $(this).attr({'src':'images/twitter_01.png'},1)
      });
  
  
  
  //$('#callendar-wrap').tipsy({gravity: 's'});
  $('#searchType').tipsy({gravity: 's'});
  $('#sb-Area').tipsy({gravity: 's'});
  $('#dragimg').tipsy({gravity: 's'});
  $('#addimg').tipsy({gravity: 's'});
  $('#maptype').tipsy({gravity: 's'});
  $('#areaAgenda').tipsy({gravity: 's'});
  $('#attrCateg').tipsy({gravity: 's'});
  $('#clearimg').tipsy({gravity: 's'});  
  
  $('#Air').tipsy({gravity: 's'});
  $('#Sea').tipsy({gravity: 's'});
  $('#Coach').tipsy({gravity: 's'});    
  
  $('#Gas').tipsy({gravity: 's'});
  $('#Pha').tipsy({gravity: 's'});  
  
  $('#facebook').tipsy({gravity: 's'}); 
  $('#twitter').tipsy({gravity: 's'}); 
        
  
  $('#clearimg').click(function(){clearAll();});
  
  
  $('.sb-header').click(function(){
  
    $(this).next().next().slideToggle(100);
  
  });
  
  $('.sb-header-right').click(function(){
    $(this).next().slideToggle(100);
  });
  
  $('#searchType').click(function(){
    $('#st-list').slideToggle(100);

  });
  
  $('#attrCateg').click(function(){
    $('#attrcat-list').slideToggle(100);
  });
  
  $('#areaAgenda').click(function(){
    $('#agenda-area-list').slideToggle(100);
  });

  $('#sb-Area').click(function(){
    $('#map-area-list').slideToggle(100);
  });  
  
      
  
  $('.sb-item').click(function(){
    
    
    if($(this).parent().attr('id')=='attrcat-list'){
      $('#attrCateg').find('.cusomselectspan').text($(this).text());
      $('#attrCateg').attr({'mValue':$(this).attr('mValue')},1);
    }
  
    if($(this).parent().attr('id')=='agenda-area-list'){
      $('#areaAgenda').find('.cusomselectspan').text($(this).text());
      $('#areaAgenda').attr({'mValue':$(this).attr('mValue')},1);
    }else if($(this).parent().attr('id')=='map-area-list'){
      $('#sb-Area').find('.cusomselectspan').text($(this).text());
      $('#sb-Area').attr({'mValue':$(this).attr('mValue')},1);
    }
    
    $(this).parent().prev().prev('.sb-header').text($(this).text());
    $(this).parent().prev().prev('.sb-header').attr({'mValue':$(this).attr('mValue')},1);
    //$('.sb-header').text($(this).text());
    $.each($(this).siblings(),function(i,obj){$(obj).removeClass('sb-item-focused');})
    $(this).addClass('sb-item-focused');
    $(this).parent('ul').slideToggle(100);
    
    
    var type=$(this).parent().prev().prev('.sb-header').text();
    
    if(type!='Address' && type!='Business' )initautocomplete($('#st-list').find('li.sb-item-focused').text()); 
    else initautocomplete(type);
    
  });
  
    
    initautocomplete('Business');

/*  
    $.ctrl('R', function() {
      //alert("Saving...");
    });    
    
    $.trapKey("UP").setEvent(function(){
      //alert("↑");
    });        
    $.trapKey("DOWN").setEvent(function(){
      //alert("↑");
    });        
    $.trapKey("LEFT").setEvent(function(){
      //alert("↑");
    });        
    $.trapKey("RIGHT").setEvent(function(){
      //alert("↑");
    });   
*/    
    $('#searchField').keydown(function(key){if(key.keyCode==13)addMarkers(0);});     


    
      
    //$(document).ready(function() {
        $("#pager").pager({ pagenumber: 1, pagecount: vPageCount, buttonClickCallback: PageClick });
        $("#pager2").pager({ pagenumber: 1, pagecount: vPageCount, buttonClickCallback: PageClick });
    //});

    PageClick = function(pageclickednumber) {
        $("#pager").pager({ pagenumber: pageclickednumber, pagecount: vPageCount, buttonClickCallback: PageClick });
        $("#results_wrap").find('center').html("Clicked Page " + pageclickednumber);
        vCurrentPage=pageclickednumber;
        addMarkers(2,globThisObj);
//        addMarkers(globOrderflag);
    }
    
    PageClick2 = function(pageclickednumber) {
        $("#pager").pager({ pagenumber: pageclickednumber, pagecount: vPageCount, buttonClickCallback: PageClick2 });
        $("#pager2").pager({ pagenumber: pageclickednumber, pagecount: vPageCount, buttonClickCallback: PageClick2 });        
        $("#results_wrap").find('center').html("Clicked Page " + pageclickednumber);
        vCurrentPage=pageclickednumber;
        addAgendaMarkers();
    }
    
    PageClick3 = function(pageclickednumber) {
        $("#pager").pager({ pagenumber: pageclickednumber, pagecount: vPageCount, buttonClickCallback: PageClick3 });
        $("#pager2").pager({ pagenumber: pageclickednumber, pagecount: vPageCount, buttonClickCallback: PageClick3 });        
        $("#results_wrap").find('center').html("Clicked Page " + pageclickednumber);
        vCurrentPage=pageclickednumber;
        addSpecialMarkers();
        
    }
    
  
  
  //search button
  $('button[class=btn]').click(function(){

      addMarkers(0);
  
  });

 
  $('#dragimg').click(function(){
  
    $('#dragimg').attr({'src':'images/toolbar/Fdrag.png'},1);
    $('#addimg').attr({'src':'images/toolbar/addpoint.png'},1);
    rmvfClickEvent();
    
    
  });
  
  $('#addimg').click(function(){
    
    $('#dragimg').attr({'src':'images/toolbar/drag.png'},1);
    $('#addimg').attr({'src':'images/toolbar/Faddpoint.png'},1);
      fClickEvent();
    
  });

function getAttributes(obj,vclass){
         // alert('hello...');
          $.ajax({
            type: 'POST',
            url: 'attributes.php',
            data: {'cat_id':obj.attr('cat_id'),'table_id':obj.attr('table_id'),'vClass':vclass},
            beforeSend:function(){
              $('#special_tags_container').html('<center class="ajaxLoader">LOADING...</center>');
            },success: function(msg){
              $('.ajaxLoader').fadeOut('slow',function(){
                //$(msg).hide();
                $('#special_tags_container').html(msg);
                //$('#special_tags').html(msg);
              });
            },dataType: 'html'
          });


}

function toggleThisSpan(obj){


      $.each($('.sub-menu-titles'),function(i, val){
         $(val).removeClass('sub-menu-title-down');
      });
      $.each($('span.sub-menu-titles:visible'), function(i, val) { 
        $(val).removeClass("sub-menu-title-down");
      });    
      obj.addClass("sub-menu-title-down");
      
      getAttributes(obj);
      var bread="<ul id='breadcrumb'><li><a title='Home'>Categories</a></li><li><a href='#' title='Sample page 1'>"+obj.parent().parent().parent().find('a').text()+"</a></li><li><a href='#' title='Sample page 2'>"+obj.text()+"</a></li></ul>";
      $('#Breadcrumb_wrap').html(bread);


}
    
    //span high light extra fields 
    //now make it toggle buttons
    /*
    $('span.sub-menu-titles').click(function(e){

      $.each($('.sub-menu-titles'),function(i, val){
         $(val).removeClass('sub-menu-title-down');
      });
      $.each($('span.sub-menu-titles:visible'), function(i, val) { 
        $(val).removeClass("sub-menu-title-down");
      });    
      $(this).addClass("sub-menu-title-down");
      
      getAttributes($(this));
      var bread="<ul id='breadcrumb'><li><a title='Home'>Categories</a></li><li><a href='#' title='Sample page 1'>"+$(this).parent().parent().parent().find('a').text()+"</a></li><li><a href='#' title='Sample page 2'>"+$(this).text()+"</a></li></ul>";
      $('#Breadcrumb_wrap').html(bread);
        
    });
    */

   
   function uncheckCategories(){
        var vClass=$(this).attr('class');
        $.each($(this).parent().siblings(), function(i,val) { 
          if(vClass=='chckBtn down'){
            $(val).find('a').addClass("down");
            //if($(this).find('a').attr('tik-icon')!='')$(val).find('a').css({'background':'url(../icons/'+$(this).find('a').attr('tik-icon')+') no-repeat 0 0'})
            $(val).find('a').css({'background':'url(micons/'+$(val).find('a').attr('tik-icon')+') no-repeat 0 0'},1);
          }else{
            $(val).find('a').removeClass("down");
            //if($(this).find('a').attr('tik-icon')!='')$(val).find('a').css({'background':'url(../icons/untik.jpg) no-repeat 0 0'})
            $(val).find('a').css({'background':'url("images/layout/untik-hotels.jpg") no-repeat 0 0 transparent'},1);
          }
        });
   }
   

     //check buttons - toggle special interest
     
    //$('a.chckBtn[sp_in=true]').click(function(){
    $('.sub-menu li:has(a.chckBtn[sp_in=true])').click(function(){
        
        clearCategories();
        $(this).find('a').toggleClass("down");
        if($(this).find('a').attr('class')=='chckBtn down'){
          $(this).find('a').css({'background':'url(micons/'+$(this).find('a').attr('tik-icon')+') no-repeat 0 0'},1);
        }else{
          $(this).find('a').css({'background':'url("images/layout/untik-hotels.jpg") no-repeat scroll 0 0 transparent'},1);
        }
         
         //get results each time you tap check buttons
         if($(this).find('a').attr('title')!='All'){
              if($(this).find('a').attr('class')=='chckBtn down')toggleThisSpan($(this).find('a').next());//$($(this).next()).click(); 
          }else {
            //if($(this).attr('class')=='chckBtn down')alert($(this).attr('class'));
          }
          spInSelected = new Array();
          $.each($('a.chckBtn[sp_in=true].down'),function(i,val){
            if($(val).attr('title')!='All')spInSelected.push($(val).attr('cat_id'));
          });//if is not the first checkbox
          addSpecialMarkers();
    
    });  
  
    
    //check buttons - toggle
    //$('a.chckBtn[sp_in=false]').click(function(){
    $('.sub-menu li:has(a.chckBtn[sp_in=false])').click(function(){ 
        //alert('hip....maria...'+$(this).find('a').attr('title'));   
        vCurrentPage = 1;
      
        $(this).find('a').toggleClass("down");

        if($(this).find('a').attr('class')=='chckBtn down'){
          $(this).find('a').css({'background':'url(micons/'+$(this).find('a').attr('tik-icon')+') no-repeat 0 0'},1);
        }else {
          $(this).find('a').css({'background':'url("images/layout/untik-hotels.jpg") no-repeat scroll 0 0 transparent'},1);
        }
        //get results each time you tap check buttons
         
         if($(this).find('a').attr('title')!='All'){
              addMarkers(1,$(this).find('a'));
              
              if($(this).find('a').attr('class')=='chckBtn down')toggleThisSpan($(this).find('a').next());//$($(this).find('a').next()).click(); 
              else $('#special_tags').slideUp();
              
              
          }else {
            
              //if($(this).attr('class')=='chckBtn down')$($(this).next()).click();
            //if($(this).attr('class')=='chckBtn down')alert($(this).attr('class'));
          
          }
    });
    
    
    
    
   /*
     //Check all button of same sub menu list on SPECIAL INTEREST
    $("a.chckBtn[title=All][sp_in=true]").click(function(){
        
        var vClass=$(this).attr('class');
        $.each($(this).parent().siblings(), function(i,val) { 
          if(vClass=='chckBtn down'){
            $(val).find('a').addClass("down");
            //if($(this).find('a').attr('tik-icon')!='')$(val).find('a').css({'background':'url(../icons/'+$(this).find('a').attr('tik-icon')+') no-repeat 0 0'})
            $(val).find('a').css({'background':'url(micons/'+$(val).find('a').attr('tik-icon')+') no-repeat 0 0'},1);
          }else{
            $(val).find('a').removeClass("down");
            //if($(this).find('a').attr('tik-icon')!='')$(val).find('a').css({'background':'url(../icons/untik.jpg) no-repeat 0 0'})
            $(val).find('a').css({'background':'url("images/layout/untik-hotels.jpg") no-repeat 0 0 transparent'},1);
          }
        });
        
          spInSelected = new Array();
          $.each($('a.chckBtn[sp_in=true].down'),function(i,val){
            if($(val).attr('title')!='All')spInSelected.push($(val).attr('cat_id'));
          });//if is not the first checkbox

        //addMarkers(1);
        
    });   
  */
    //Check all button of same sub menu list
    //$("a.chckBtn[title=All][sp_in=false]").click(function(){
    $('.sub-menu li:has(a.chckBtn[title=All][sp_in=false])').click(function(){    

      var bread="<ul id='breadcrumb'><li><a title='Categories'>Categories</a></li><li><a href='#' title=''>"+$(this).find('a').parent().parent().parent().find('a').text()+"</a></li><li><a href='#' title='Sample page 2'>"+$(this).find('a').next().text()+"</a></li></ul>";
      $('#Breadcrumb_wrap').html(bread);

        
                
        var vClass=$(this).find('a').attr('class');
        getAttributes($(this).find('a'),vClass);
        
        $.each($(this).find('a').parent().siblings(), function(i,val) { 
          if(vClass=='chckBtn down'){
            $(val).find('a').addClass("down");
            //if($(this).find('a').attr('tik-icon')!='')$(val).find('a').css({'background':'url(../icons/'+$(this).find('a').attr('tik-icon')+') no-repeat 0 0'})
            $(val).find('a').css({'background':'url(micons/'+$(val).find('a').attr('tik-icon')+') no-repeat 0 0'},1);
          }else{
            $(val).find('a').removeClass("down");
            //if($(this).find('a').attr('tik-icon')!='')$(val).find('a').css({'background':'url(../icons/untik.jpg) no-repeat 0 0'})
            $(val).find('a').css({'background':'url("images/layout/untik-hotels.jpg") no-repeat 0 0 transparent'},1);
          }
        });
        
        addMarkers(1,$(this).find('a'));
        
    });

    //$.each($('.sub-menu a.chckBtn'), function(i, val) { alert(i);});    
    
    
    //Right panel datepicker
    $('.ui-datepicker-calendar tbody td').click(function(e) {
          if(e.ctrlKey) {
            //console.log("Ctrl+Click");
            // your code goes here...
            if($(this).attr('class')=='tdnormal tdchecked')$(this).removeClass('tdchecked');
            else $(this).addClass('tdchecked');
            
            
          } else if(e.altKey) {
            //console.log("Alt+Click");
          }else if(e.shiftKey){
              //console.log("Shift+Click");
              var startobj=null;
              $.each($('.ui-datepicker-calendar tbody td.tdchecked'),function(i,obj){
                  //$(obj).removeClass('tdchecked');
                     if(i==0)startobj=$(obj);
              });
              var iterObj=$(this);    
              $.each($('.ui-datepicker-calendar tbody td'),function(i,obj){
              if($(obj).text()!=' '){
                 if(parseFloat(iterObj.text())<parseFloat(startobj.text())){
                    if(parseFloat($(obj).text())<parseFloat(startobj.text()) && parseFloat($(obj).text())>=parseFloat(iterObj.text())){
                        $(obj).addClass('tdchecked');
                    }
                }else{
                  //alert($(obj).text()+' '+iterObj.text());
                  if(parseFloat($(obj).text())<=parseFloat(iterObj.text()) && parseFloat($(obj).text())>parseFloat(startobj.text())){
                        $(obj).addClass('tdchecked');
                  }
                }
              }
              });

              
              //
              $.each($('.ui-datepicker-calendar tbody td'),function(i,obj){
                //$(obj).removeClass('tdchecked');
              });
            
          }else{ 
              $.each($('.ui-datepicker-calendar tbody td'),function(i,obj){
                $(obj).removeClass('tdchecked');
              });
              $(this).addClass('tdchecked');
            }
            daysSelected=new Array();
            //tdnormal tdchecked
              $.each($('.ui-datepicker-calendar tbody td.tdchecked'),function(i,obj){
                     daysSelected.push("'"+$(obj).attr('date')+"'");
              });
        }); 

    //$(".ui-datepicker-calendar").after('<button class="customButton" >Go</button>');
    //$('.ui-datepicker .ui-datepicker-buttonpane button').html(' Search ');
    $('.customButton').click(function(){
        //$("a.chckBtn[title=All].down").click();
        clearAll(function(){
        
        addAgendaMarkers();},null);          

      
    });    

/* tree view     
    $("#left_menu").treeview({
      animated: "fast",collapsed: true,unique:true
    });
*/
/*      
    $(".left_menu_list a.hdr").click(function(){
    
      if($(this).next('.sub-menu').is(":hidden")){
        var thisheight=$(this).next('.sub-menu').height();

        $(this).next('.sub-menu').animate({height:'200px',display: 'block'},1000);
      }else{
        //var thisheight=$(this).next('.sub-menu').height();
        $(this).next('.sub-menu').animate({ display: 'none',height:'0px'},1000);      
      }
    });

 */ 
    $(".left_menu_list a.hdr").click(function(){
   // alert('id='+$(this).text());
     if($(this).next().is(":hidden")){
        var h = $(".sub-menu:visible").height();
        var cssHeight=$(".sub-menu:visible").css('height');
        $(".sub-menu:visible").animate( 
        { height: '1px' }, 'fast', function() {
          $(this).hide();
          $(this).height(h);
          $(this).css('height',cssHeight);
          $(this).attr({'opened':'0'},1);
          //callBack();
          $(this).parent().css({'background':'#cccccc'},1);
        });
        
        $(this).next().slideDown("fast");
        
        $(this).next().attr({'opened':'1'},1)
        $(this).parent().css({'background':'#dbdbdb'},1);
          

      }else{
        var h = $(this).next().height();
        var cssHeight=$(this).next().css('height');
        $(this).next().animate( 
        { height: '1px' }, 'fast', function() {
          $(this).hide();
          $(this).height(h);
          $(this).css('height',cssHeight);
          $(this).attr({'opened':'0'},1);
          $(this).parent().css({'background':'#cccccc'},1);
        });
        
      }
    }); 


    /*


    
    $('.sub-menu li').click(function(){
        $(this).find('a').click();
    });
    
        */
}

function detectCrapBrowser(){
  var useragent = navigator.userAgent;
  //check whether the client browser is tha fucking ie6 piece of shit
  alert(useragent);
  if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
    return true;        
  } else {
    return false;
  }
}

function detectBrowser(){
  var useragent = navigator.userAgent;
  
  //var mapdiv = document.getElementById("map_canvas");
  //check whether the client browser is on Android or iPhone platform
  if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
    return true;        
  } else {
    return false;
  }
}

$(document).ready(function() {
  //detectCrapBrowser();
  
  initBinding();
  newMap(initlat,initlng,initzm,'map_wrapper');
});


function showPoiInfo(){
  if(markersOnMap[poiId]){
    var htmlInfo="<div onclick='' style='border:0px black solid; height:130px; width:250px;' id='infoContent'></div><br><div id='latlng'></div><br><div id='country'></div>";
    globmap.setCenter(markersOnMap[poiId].getLatLng());
    markersOnMap[poiId].openInfoWindow(htmlInfo);
  }
}

// === functions that perform the context menu options ===
  function zoomIn() {
    // perform the requested operation
    globMap.zoomIn();
    // hide the context menu now that it has been used
    contextmenu.style.visibility="hidden";
  }      
  function zoomOut() {
    // perform the requested operation
    globMap.zoomOut();
    // hide the context menu now that it has been used
    contextmenu.style.visibility="hidden";
  }      
  function zoomInHere() {
    // perform the requested operation
    var point = globMap.fromContainerPixelToLatLng(clickedPixel)
    globMap.zoomIn(point,true);
    // hide the context menu now that it has been used
    contextmenu.style.visibility="hidden";
  }      
  function zoomOutHere() {
    // perform the requested operation
    var point = globMap.fromContainerPixelToLatLng(clickedPixel)
    globMap.setCenter(point,globMap.getZoom()-1); // There is no map.zoomOut() equivalent
    // hide the context menu now that it has been used
    contextmenu.style.visibility="hidden";
  }      
  function centreMapHere() {
    // perform the requested operation
    var point = globMap.fromContainerPixelToLatLng(clickedPixel)
    globMap.setCenter(point);
    // hide the context menu now that it has been used
    contextmenu.style.visibility="hidden";
  }
  function removeMarker(){
    // perform the requested operation
    //and clear the marker
    globMap.clearOverlays();
    // hide the context menu now that it has been used
    contextmenu.style.visibility="hidden";
  }
function removePDMarkers(){
  
  
  var marker = globMap.getFirstMarker();
  while (marker != null)
  {
  	marker.remove();	
  	marker = globMap.getFirstMarker();
  }
  
  
  while(beachesRegions.length!=0){
    beachesRegions[beachesRegions.length-1].remove();
    beachesRegions.pop();
  }
  
  beachesRegions = new Array();
}      
var vMark;
function fClickEvent(){

  gEventClick=new GEvent.addListener(globMap, "click", function(marker,point){
       if(!marker){
              searchAround = 1;
              var customIcon = new GIcon(); 
              customIcon.image = 'http://maps.gstatic.com/intl/el_ALL/mapfiles/arrow.png';
              customIcon.iconSize = new GSize(39,34);  
              customIcon.shadow = '';//http://labs.google.com/ridefinder/images/mm_20_shadow.png
              customIcon.infoWindowAnchor = new GPoint(0, -34);                                            
              customIcon.iconAnchor = new GPoint(10, 34);
                                                          
              //customIcon.iconAnchor = new GPoint(".($size[0]/2).", ".$size[1].");
              if(vMark)vMark.remove();
              vMark=new GMarker(point,{draggable:true,bouncy:true,icon:customIcon});
              //$('#map_wrapper').block();
              //$('#map_wrapper').block({message:'Searching...'});
              //globMap.clearOverlays();
              
              contextmenu.style.visibility="hidden";
              this.addOverlay(vMark);
              if(globMap.getZoom()>12)
                globMap.setCenter(point,globMap.getZoom());
              else
                globMap.setCenter(point,12);
                    /*
                    GEvent.addListener(globMap,"singlerightclick",function(pixel,tile,clMark) {
                       if(vMark!=clMark)return false;
                        // store the "pixel" info in case we need it later
                        // adjust the context menu location if near an egde
                        // create a GControlPosition
                        // apply it to the context menu, and make the context menu visible
                        clickedPixel = pixel;
                        var x=pixel.x;
                        var y=pixel.y;
                        if (x > globMap.getSize().width - 120) { x = globMap.getSize().width - 120 }
                        if (y > globMap.getSize().height - 100) { y = globMap.getSize().height - 100 }
                        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
                        pos.apply(contextmenu);
                        contextmenu.style.visibility = "visible";
                    });
                  */
            GEvent.addListener(vMark,'dragend',function(){
              //if there are input defined store coordinates there ondragend event fill the coordinates
              if($('#'+yInput))$('#'+yInput).val(vMark.getLatLng().lat());//latitude
              if($('#'+xInput))$('#'+xInput).val(vMark.getLatLng().lng());//longitude
              if(globMap.getZoom()>12)
                globMap.setCenter(vMark.getPoint(),globMap.getZoom());
              else
                globMap.setCenter(vMark.getPoint(),12);
              addMarkers();
            });
              //if there are input defined store coordinates fill the coordinates
              if($('#'+yInput))$('#'+yInput).val(vMark.getLatLng().lat());//latitude
              if($('#'+xInput))$('#'+xInput).val(vMark.getLatLng().lng());//longitude
              addMarkers();
              
              }
   });

}

function rmvfClickEvent(){

  if(gEventClick){
    GEvent.removeListener(gEventClick);
    GEvent.clearListeners(globMap,"click") ;
    gEventClick = null;
    searchAround = 0;
    vMark.remove();
  }

}
var customUI ;

function addRegion(data,ommit,imagePath,tooltip,details,mid,id,tableId,sizeX,sizeY){

      var myPolygon;
      vPointsArray=new Array();
      $.each($.parseJSON(data),function(i,val){
        vPointsArray.push(new GLatLng(val[1],val[0]));
      });
      if(vPointsArray!=0){
        //myPolygon = new GPolygon(vPointsArray, "#000000", 1, 1,"#336699",0.3);
        myPolygon = new GPolygon(vPointsArray, "#CA6B10", 1, 1,"#FFF8A7",0.7);
        if(ommit!=1){
          beachesRegions.push(myPolygon);
          globMap.addOverlay(myPolygon);
          var mIcon = new GIcon();
          if(imagePath!='')mIcon.image = imagePath;
          if(sizeX && sizeY)mIcon.iconSize = new GSize(sizeX,sizeY); 
          mIcon.shadow = '';//http://labs.google.com/ridefinder/images/mm_20_shadow.png
          mIcon.infoWindowAnchor = new GPoint(5, 1);                                            
          mIcon.iconAnchor = new GPoint(10,35);
          
          var mpdMarker = new PdMarker(myPolygon.getBounds().getCenter(),{icon:mIcon,draggable:false,bouncy:false});//,{icon:icon,draggable:false,bouncy:false}
          if(tooltip!='')mpdMarker.setTooltip(tooltip);
          if(details)mpdMarker.setDetailWinHTML(details);
          globMap.addOverlay(mpdMarker);
          
          GEvent.addListener(mpdMarker, "click", function() {
            $("#moreInfoId"+mid).colorbox({speed:"500" , transition:"elastic" , width:"930px",href:"morePage.php?table="+tableId+"&id="+id+'&requestInside=true', height:"590px"});
            $("#moreInfoIdnm"+mid).colorbox({speed:"500" , transition:"elastic" , width:"930px",href:"morePage.php?table="+tableId+"&id="+id+'&requestInside=true', height:"590px"});
            $("#moreInfoIdimg"+mid).colorbox({speed:"500" , transition:"elastic" , width:"930px",href:"morePage.php?table="+tableId+"&id="+id+'&requestInside=true', height:"590px"});
            
            globMap.closeDetailWinAll(this);
          });
          
         } 
      }
      return myPolygon;

}


function HomeControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to set the map to Home';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = '<b>Home</b>';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to
  // Chicago
  google.maps.event.addDomListener(controlUI, 'click', function() {
    //map.setCenter(chicago)
  });

}

  markersArray = new Array();
  // Shows any overlays currently in the array
  function showOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(map);
      }
    }
  }

  function addMarker(location,map,vIcon) {
    if(vIcon=='')vIcon=null;
    marker = new google.maps.Marker({
      position: location,
      map: map,
      icon: vIcon
    });
    markersArray.push(marker);
    marker.setMap(map);

    
  }

  // Deletes all markers in the array by removing references to them
  function deleteOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  }



function newMap( CenterX , CenterY , ZoomLvl , conteiner ) {

if(detectBrowser()){
      var newyork = new google.maps.LatLng(CenterX, CenterY);
      var myOptions = {
        zoom: ZoomLvl,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center:newyork,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel:false  
      };
      globMap = new google.maps.Map(document.getElementById(conteiner), myOptions);
      
      google.maps.event.addListener(globMap,'click',function(event){
        //addMarker(event.latLng,globMap);
      });
      
      google.maps.event.addListener(globMap,'dragend',function(){
        //deleteOverlays();
        addMarkers(globOrderflag);
      });
      
      google.maps.event.addListener(globMap,'zoomend',function(oldLevel,newLevel){
      
        addMarkers();
      
      });
              
        
  }else if (GBrowserIsCompatible()) {
    if(conteiner){
        
        globMap = new GMap2(document.getElementById(conteiner));
        globMap.setCenter(new GLatLng(CenterX,CenterY), ZoomLvl);
        globMap.setMapType(G_NORMAL_MAP);

        
        customUI = globMap.getDefaultUI();
        customUI.zoom.scrollwheel = false; 
        customUI.controls.menumaptypecontrol = false;
        customUI.controls.scalecontrol = false;
        customUI.controls.largemapcontrol3d = false;
        customUI.controls.maptypecontrol = false; 
        customUI.controls.smallmapcontrol3d = true;
        customUI.controls.hierarchicalmaptypecontrol = false;        
        customUI.controls.overviewmapcontrol = true;
        globMap.setUI(customUI);
   
        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,70));
        var pos2 = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,70));
        globMap.addControl(new GLargeMapControl(),pos);
        globMap.addControl(new GMapTypeControl(),pos2);
        
        vGeocoder = new GClientGeocoder();

                    
         // === create the context menu div ===
      contextmenu = document.createElement("div");
      contextmenu.style.visibility="hidden";
      contextmenu.style.background="#ffffff";
      contextmenu.style.border="1px solid #8888FF";

      contextmenu.innerHTML = 
                             /*'<a  href="javascript:saveMarker()"><div class="context">&nbsp;&nbsp;Add Point&nbsp;&nbsp;<\/div><\/a>'                            
                            + '<a href="javascript:removeMarker()"><div class="context">&nbsp;&nbsp;Remove Point &nbsp;&nbsp;<\/div><\/a>'*/
                              '<a onclick="addMarkers();"><div class="context">&nbsp;&nbsp;Search Around &nbsp;&nbsp;<\/div><\/a>'                                                       
                            + '<a href="javascript:zoomInHere()"><div class="context">&nbsp;&nbsp;Zoom in &nbsp;&nbsp;<\/div><\/a>'
                            + '<a href="javascript:zoomOutHere()"><div class="context">&nbsp;&nbsp;Zoom out &nbsp;&nbsp;<\/div><\/a>'
                            + '<a href="javascript:centreMapHere()"><div class="context">&nbsp;&nbsp;Centre map here&nbsp;&nbsp;<\/div><\/a>';

      globMap.getContainer().appendChild(contextmenu);

      // === listen for singlerightclick ===
      // === If the user clicks on the map, close the context menu ===
      GEvent.addListener(globMap,'click',function(marker,point){
        //if(!marker)globMap.closeDetailWinAll(null);
        contextmenu.style.visibility="hidden";
      });
      
      GEvent.addListener(globMap,'dragend',function(){
         //if(searchAround == 1)addMarkers();
        //globMap.clearOverlays();
        //addMarkers();
        
      });
      
      GEvent.addListener(globMap,'zoomend',function(oldLevel,newLevel){
        //if(searchAround == 1)addMarkers();
      
      });
      
      GEvent.addListener(globMap,'mouseover',function(poi){
        //globMap.showControls();
      });

      GEvent.addListener(globMap,'mouseout',function(poi){
        //globMap.hideControls();
      });
  

      
    }
  }
 
}

