var markers=new Array();
var systemEvents=false;
var map= false;
var itemChanged = false;
var mapIsLoaded = false;
var dotsLoaded = false;

function searchInitialize() {
	var allInputs=new Array('lfObjectType', 'lfPrice', 'lfPeople', 'lfFood', 'lfLanguage', 'lfRegion');
	for (var i in allInputs) {
		$('input[name='+allInputs[i]+']').val(inputValues[allInputs[i]]);
        //alert(allInputs[i]);
		updatePulldown(allInputs[i], 1);
	}
	updateFulltext();
	setTimeout('searchGetResults();', 2000);
}

function searchReset() {
	var allInputs=new Array('lfObjectType', 'lfPrice', 'lfPeople', 'lfFood', 'lfLanguage', 'lfRegion');
	for (var i in allInputs) {
		$('input[name='+allInputs[i]+']').val('');
		updatePulldown(allInputs[i], 1);
	}
	$('#searchOpen .fulltext input').val('').trigger('blur');
	setTimeout('searchGetResults();', 2000);

	var googleMap=new Array();
	googleMap[0]=mapCountryData['lat'];
	googleMap[1]=mapCountryData['lng'];
	googleMap[2]=mapCountryData['zoom'];
	cookieArrayWrite('googleMap', googleMap);
	map.setCenter(new google.maps.LatLng(googleMap[0], googleMap[1]));
	map.setZoom(googleMap[2]-0);

}

function searchMapInitialize() {
    mapIsLoaded = false;
    $('div#mapWait').show();

	//var googleMap=cookieArrayRead('googleMap');

        //$('div#mapWait').show();

		googleMap=new Array();

	if (googleMap.length<3) {
		googleMap=new Array();
		googleMap[0]=mapCountryData['lat'];
		googleMap[1]=mapCountryData['lng'];
		googleMap[2]=mapCountryData['zoom'];
	}

  var latlng = new google.maps.LatLng(googleMap[0], googleMap[1]);
  var myOptions = {
    scrollwheel: false,
    zoom: googleMap[2]-0,
    center: latlng,
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

    google.maps.event.addListener(map, 'dragend', function(event) {
    	if (systemEvents==true) return false;
    	$('input[name=lfRegion]').val('');
		updatePulldown('lfRegion', 1);
		setTimeout('searchGetResults();', 2000);
		var googleMap=new Array();
		googleMap[0]=map.getCenter().lat();
		googleMap[1]=map.getCenter().lng();
		googleMap[2]=map.getZoom();
		cookieArrayWrite('googleMap', googleMap);
    });

    google.maps.event.addListener(map, 'zoom_changed', function(event) {
    	if (systemEvents==true) return false;
    	$('input[name=lfRegion]').val('');
		updatePulldown('lfRegion', 1);
		setTimeout('searchGetResults();', 2000);
		var googleMap=new Array();
		googleMap[0]=map.getCenter().lat();
		googleMap[1]=map.getCenter().lng();
		//googleMap[2]=map.getZoom();
		cookieArrayWrite('googleMap', googleMap);
    });
    google.maps.event.addListener(map, 'tilesloaded', function(a){
        mapIsLoaded = true;
        if(mapIsLoaded && dotsLoaded) {
            $('div#mapWait').hide();
            //mapIsLoaded = false;
            //dotsLoaded = false;
        }
    });

    //$('div#map-canvas').fadeIn(400);
    //$('div#map-canvas').show();
}

function updateFulltext() {
	var defaultValue = $('#searchInputs .fulltext input').attr('defaultValue');
    //alert($('#searchInputs .fulltext input').attr('value'));
    if($('#searchInputs .fulltext input').attr('value') != defaultValue) {
        $('#searchInputs .fulltext input').removeClass('noSelection');
    }

    $('#searchInputs .fulltext input').focus(function(){
        if($(this).val() == defaultValue) {
            $(this).val('');
        }
    });

    $('#searchInputs .fulltext input').blur(function(){
        if($(this).val() == '') {
            $(this).val(defaultValue);
            $(this).addClass('noSelection');
        } else {
            $(this).removeClass('noSelection');
        }
    });
}

function updatePulldown(name, setOnly) {
        //alert(name);
	// Set selected A elements
	thisInput=$('input[name='+name+']');
	thisDiv=$(thisInput).parents('div.complex');
	$(thisDiv).find('a').removeClass('selected');
	var thisInputVal=thisInput.val();
	//thisInputVal=thisInputVal.substring(1);
	//thisInputVal=thisInputVal.substring(0, thisInputVal.length-1);
     /*
	if ($(thisDiv).hasClass('multiple')) {
		if (thisInputVal.length>0) {
			thisInputVal=thisInputVal.split(',');
			var userOutput=new Array();
			for (var i in thisInputVal) {
				$(thisDiv).find('a[valueId='+thisInputVal[i]+']').addClass('selected');
				userOutput[userOutput.length]=$(thisDiv).find('a[valueId='+thisInputVal[i]+']').html();
			}
			$(thisDiv).find('p').html(userOutput.join(', ')).addClass('selected');
		} else {
			$(thisDiv).find('p').html($(thisDiv).find('p').attr('defaultValue')).removeClass('selected');
		}
	} else {
		//thisInput.val(thisInputVal);
		if (thisInputVal.length>0) {
			$(thisDiv).find('a[valueId='+thisInputVal+']').addClass('selected');
			$(thisDiv).find('p').html($(thisDiv).find('a[valueId='+thisInputVal+']').html()).addClass('selected');
		} else {
			$(thisDiv).find('p').html($(thisDiv).find('p').attr('defaultValue')).removeClass('selected');
		}
		if (setOnly!=1) $(thisDiv).find('p').trigger('click');
	}
     */
    if (thisInputVal.length>0) {
        $(thisDiv).find('a[valueId='+thisInputVal+']').addClass('selected');
        $(thisDiv).find('p').html($(thisDiv).find('a[valueId='+thisInputVal+']').html()).addClass('selected');
    } else {
        $(thisDiv).find('p').html($(thisDiv).find('p').attr('defaultValue')).removeClass('selected');
    }
    if (setOnly!=1) $(thisDiv).find('p').trigger('click');
}

function searchGetResults() {
    dotsLoaded = false;
    $('div#mapWait').show();
    //$('div#mapWait').show();
	if (map && $('input[name=lfRegion]').val()=='') {
		var t=map.getBounds().toString();
		t=t.replace(/\(|\)|\s/g, '');
        //alert(map);
		$('input[name=lfBounds]').val(t);
	} else {
		$('input[name=lfBounds]').val('');
	}


	var defaultValue = $('#searchOpen .fulltext input').attr('defaultValue');
    if($('#searchOpen .fulltext input').attr('value') == defaultValue) {
		$('#searchOpen .fulltext input').val('');
    }

    //alert("/"+myPath+"ajax/search_results.php"+$('[name=mapForm]').serialize());
	$.ajax({
		async: true,
		type: "GET",
		url: "/"+myPath+"ajax/search_results.php",
		data: $('[name=mapForm]').serialize(),
		dataType: "text",
		success: function(msg, status){
            //alert(msg);
			systemEvents=true;
			eval(msg);
			systemEvents=false;
			for (i in a) {
				a[i]=a[i].split('~');
			}
			clearMarkers();
			showResultsOnMap(a);
            //$('div#mapWait').hide();
			$('#resultsCount').html(a.length);
			return false;
		}
	});
    if($('#searchOpen .fulltext input').attr('value') == '') {
		$('#searchOpen .fulltext input').val(defaultValue);
    }
}

function showResults() {
    $('div#resultsWait').show();
	if (map && $('input[name=lfRegion]').val()=='') {
		var t=map.getBounds().toString();
		t=t.replace(/\(|\)|\s/g, '');
		$('input[name=lfBounds]').val(t);
	} else {
		$('input[name=lfBounds]').val('');
	}
	//alert($('form[name=mapForm] input[name=lfRegion]').val());
	//alert($('[name=mapForm]').serialize()+"&resultsOnly=1");

	$.ajax({
		async: true,
		type: "GET",
		url: "/"+objectsListUrl,
		data: $('[name=mapForm]').serialize()+"&resultsOnly=1",
		dataType: "text",
		success: function(msg, status){
            $('div#resultsWait').hide();
            $.scrollTo($('div#mainContentArea'), {duration: 500, offset: {top:-180, left:0}});
            //alert(msg);
            $('#mainContentArea').slideUp(1000, function() {
                $(this).html(msg).slideDown(1000);
                alignFavorites();
            });
			return false;
		}
	});
}

function showResultsOnMap(a) {
	var typeSmall=new Array('/'+myPath+'html/i/map_dot_small.png', 1000);
	var typeLarge=new Array('/'+myPath+'html/i/map_dot_large.png', 1001);
	var typeFavorite=new Array('/'+myPath+'html/i/map_dot_favorite.png', 1002);
	var favCookie=cookieArrayRead("favCookie");

	var thisType=new Array();
	for (i in a) {
		thisType=typeSmall;
		if (a[i][4]==1) thisType=typeLarge;
		if (favCookie.length>0) {
			for (ii in favCookie) {
				if (favCookie[ii].indexOf(a[i][3])>-1) {
					thisType=typeFavorite;
				}
			}
		}
		markers[i]=new google.maps.Marker({
			position: new google.maps.LatLng(a[i][0], a[i][1]),
			map: map,
			icon: thisType[0],
			zIndex: thisType[1],
			title: a[i][2]
		});
	}
    dotsLoaded = true;
    setTimeout('hideWaiter()', 500);
}

function clearMarkers() {
	for(var i=0; i<markers.length; i++){
		markers[i].setMap(null);
	}
	markers.length = 0;
}

function hideWaiter() {
    if(mapIsLoaded && dotsLoaded) {
        $('div#mapWait').hide();
    }
}

function showMap(){
    $('div#mapPhoto').fadeOut(400);

    $('div#slider').animate({
        left: '102px'
      }, 400, function() {
        // Animation complete:
        $('div.btn').addClass('closed');
        $('#map-canvas').css('visibility','visible');
        $('div#searchOpenRight div').show();
        $('div#slider').removeClass('open').addClass('closed');

        if (!map) {
    		var firstInit=true;
    	} else {
    		var firstInit=false;
    	}
		if (firstInit) searchMapInitialize();
		if (firstInit) searchInitialize(); // Init the search
      });

}


$(document).ready(function(){

    // Map OPEN
    $('#searchClosed.home').live('click', function(){
        /*$('div#slider').animate({
                left: '0px'
        }, 40, function() {
                // Animation complete.
        });*/
        //$('div#map-texts div.btn').css('visibility','visible');
        $('div#map-photo').show();
        $('#searchClosed').hide();
        /*
        if (!map) {
    		var firstInit=true;
    	} else {
    		var firstInit=false;
    	}
        */
		//if (firstInit) searchMapInitialize();
		//if (firstInit) searchInitialize(); // Init the search
        //cookieWrite('mapClose', 'false', 12);
    });
    $('#searchClosed.other').live('click', function(){
        $('#mapPhoto').hide();
        $('div#map-photo').show();
        $('#searchClosed').hide();
        $('div#searchOpenRight div').show();

        if (!map) {
    		var firstInit=true;
    	} else {
    		var firstInit=false;
    	}
		if (firstInit) searchMapInitialize();
		if (firstInit) searchInitialize(); // Init the search
        //cookieWrite('mapClose', 'false', 12);

    });

    // Map CLOSE
    $('#btnCloseSearch, #navigation h2').live('click', function(){
		$('div#map-photo').hide();
        $('#searchClosed').show();
        //$('#map-canvas').css('visibility','hidden');
        //$('div#slider').removeClass('closed');
        $('div.btn').removeClass('closed');
        $('div#searchOpenRight div').hide();
        //cookieWrite('mapClose', 'true', 12);
    });

    // Map TYPE OPEN
    $('#searchOpenRight span').live('click', function(){
        $('div#maptype').slideToggle('fast');
    });

    // Map TYPE Select
    $('div#maptype li').live('click', function(){
        map.setMapTypeId($(this).attr('defaultValue'));
        $('div#maptype').slideUp();
    });

    // Map ZOOM In
    $('#btnMapIn').live('click', function(){
        map.setZoom(map.getZoom()+1);
    });

    // Map ZOOM Out
    $('#btnMapOut').live('click', function(){
        map.setZoom(map.getZoom()-1);
    });

    // Open / Close pulldown
    $('.complex > p').live('click', function(){
        if($(this).hasClass('selectOpen')) {
            $(this).prev().slideUp('fast', function() {
	            $(this).next().removeClass('selectOpen');
            });
            if(itemChanged){        
                setTimeout('searchGetResults();', 2000);
            }
            itemChanged = false;
        } else {
            $('.complex > p').removeClass('selectOpen'); // switch to arrow down
            $('.complex > div').hide(); // close all

            $(this).addClass('selectOpen'); // arrow up
            $(this).prev().slideDown('fast'); // open th current one
        }
    });

    // Close pulldown button
    $('.closePldn').live('click', function(){
        $(this).parent().slideUp('fast', function() {
            $(this).next().removeClass('selectOpen');
        });
        if(itemChanged){
            setTimeout('searchGetResults();', 2000);
        }
        itemChanged = false;
    });

    // noMatter
    $('.complex .noMatter').live('click', function(){
    	var thisInput=$(this).parents('div.complex').find('input');
        thisInput.val(''); // input
		updatePulldown(thisInput.attr("name"));
        itemChanged = true;
		$(this).parent().parent().parent().next().trigger('click');
    });

    $('.complex li a').live('click', function() {
            $('div#mapWait').show();
            if (!map) {
        		var firstInit=true;
        	} else {
        		var firstInit=false;
        	}
    		if (firstInit) searchMapInitialize();
    		if (firstInit) searchInitialize(); // Init the search
            showMap();

		var value=$(this).attr("valueId");
	    thisInput=$(this).parents('div.complex').find('input');
	    thisInputVal = thisInput.val();
		thisDiv=$(thisInput).parents('div.complex');
        /*
		if ($(thisDiv).hasClass('multiple')) {
			if (thisInputVal.indexOf(','+value+',')>-1) {
				thisInput.val(thisInputVal.replace(value+',', ''));
				if (thisInput.val()==',') thisInput.val('');
			} else {
				if (thisInputVal=='') {
					thisInput.val(value);
					//thisInput.val(','+value+',');
				} else {
					thisInput.val(thisInputVal+value+',');
				}
			}
		} else {
					thisInput.val(value);
					//thisInput.val(','+value+',');
		}
        */
        thisInput.val(value);
        itemChanged = true;
		updatePulldown(thisInput.attr("name"));
	});
        $('a.maps, div.btn').click(function(){
            //$('div.btn a').blur();
            //showMap();

            //$('div#mapWait').show();
            $('div#searchOpenRight div').fadeIn(400);
            $('div#mapPhoto').fadeOut(400);
        	$('div#slider').animate({
                    left: '102px'
            }, 400, function() {
                $('div#slider').removeClass('open').addClass('closed');
            });
            $('div#map-texts div.btn').css('visibility','hidden');
            if (!map) {
        		var firstInit=true;
        	} else {
        		var firstInit=false;
        	}
    		if (firstInit) searchMapInitialize();
    		if (firstInit) searchInitialize(); // Init the search
        });
        $('a#slider_tab').click(function(){

             if($('div#slider').hasClass('open')) {
                $('div#searchOpenRight div').fadeIn(400);
                $('div#mapPhoto').fadeOut(400);
            	$('div#slider').animate({
                        left: '102px'
                }, 400, function() {
                    $('div#slider').removeClass('open').addClass('closed');
                });
                $('div#map-texts div.btn').css('visibility','hidden');
                if (!map) {
            		var firstInit=true;
            	} else {
            		var firstInit=false;
            	}
        		if (firstInit) searchMapInitialize();
        		if (firstInit) searchInitialize(); // Init the search
             } else {
                $('div#slider').animate({
                        left: '0px'
                }, 400, function() {
                        $('div#slider').removeClass('closed').addClass('open');
                });
             } 
        });

        $('input[name=lfFulltext1]')
            .bind('keyup', function(event) {
                if (event.keyCode==13) {
                    if($('div#map-photo').css('display') == 'none') {
                        $('div#map-photo').show();
                        $('#searchClosed').hide();
                    }
                    if($('div#slider').hasClass('closed')) {
                        setTimeout('searchGetResults();', 2000);
                    } else {
                        showMap();
                    }
                }
        	});

        /*$('input[name=lfHeaderFulltext]').bind('keyup', function(event) {
            if (event.keyCode==13) {
                $('input[name=lfFulltext1]').val($('input[name=lfHeaderFulltext]').val());
                if($('div#map-photo').css('display') == 'none') {
                    $('div#map-photo').show();
                    $('#searchClosed').hide();
                }
                if($('div#slider').hasClass('closed')) {
                    setTimeout('searchGetResults();', 2000);
                } else {
                    showMap();
                }
    		}
    	});

        $('input[name=lfHeaderFulltextSubmit]').click(function() {
            $('input[name=lfFulltext1]').val($('input[name=lfHeaderFulltext]').val());
            if($('div#map-photo').css('display') == 'none') {
                $('div#map-photo').show();
                $('#searchClosed').hide();
            }
            if($('div#slider').hasClass('closed')) {
                //alert('ma');
                setTimeout('searchGetResults();', 2000);
            } else {
                //alert('nema');
                showMap();
            }
    	}); */

        $('a#showResults').click(function() {
            showResults();
    	});
});
