var rootPath = 'http://nekretnine-hrvatska.com.hr/';

function getSearchFormUrl(rootPath){
	filter_region = document.getElementById('filter_region').value;
	filter_island = document.getElementById('filter_island').value;
	filter_city = document.getElementById('filter_city').value;
	path = rootPath+'ajax_search_form.php?filter_region='+filter_region+"&filter_island="+filter_island+"&filter_city="+filter_city+"&reset_filter_cityareas=1"+(filter_city==""?"&reset_filter_city=1":"");
	return path;
}

function getAddToFavoritesUrl(rootPath, rid){
	closeFooterToolbarMenu();
	return rootPath+'footer_toolbar.php?addFavorite='+rid;
}

function getReloadUrl(rootPath){	
	return rootPath+'footer_toolbar.php';
}


function deleteFromFavorites(rootPath, rid){
	$('.addFavorite'+ rid).css('display', 'inline-block');
	$('.addFavoriteActive'+ rid).css('display', 'none');	
	$('#favoriteRow'+ rid).css('display', 'none');
	closeFooterToolbarMenu();
	$('#footer_toolbar').load(getDeleteFromFavoritesUrl(rootPath, rid),'');
}

function popupLogin(rootPath){
	popup_email = document.getElementById('popup_login_box_email').value;
	pass = document.getElementById('popup_login_box_password').value;
	remember = document.getElementById('popup_login_box_remember').checked ? 1 : 0;
	page = document.getElementById('popup_login_box_current_page').value;		
	$('#loginPopupHtml').load(rootPath+'login_popup.php?e='+popup_email+'&p='+pass+'&r='+remember+'&page='+page,'');
}

function popupForgotPassword(rootPath){	
	email_forgot = document.getElementById('forgot_email').value;
	$('#forgotPasswordPopupHtml').load(rootPath+'forgot_password_popup.php?forgot_email='+email_forgot+'&isPostBack=1','');
}

function deleteFromSearches(rootPath, id){	
	closeFooterToolbarMenu();
	$('#footer_toolbar').load(getDeleteMySearchUrl(rootPath, id),'');
}

function closeFooterToolbarMenu(){
	$("#jx-menu-con-id").fadeOut();
	$("li").each(function (i) {
	   $(this).parent().removeClass("jx-nav-menu-active");
	   $(this).parent().removeClass("jx-nav-menu-active-rounded");
	});	
	button_active = false; // remove button's active state	
	active_button_name="";	
}

function getDeleteFromFavoritesUrl(rootPath, rid){
	return rootPath+'footer_toolbar.php?removeFavorite='+rid;
}

function getDeleteMySearchUrl(rootPath, id){	
	return rootPath+'footer_toolbar.php?removeSearch='+id;
}




function getStarRatingUrl(rootPath, starRatingType, realestateId, vote){	
	return rootPath+'star_rating.php?starRatingType='+starRatingType+"&realestateId="+realestateId+"&vote="+vote;
}

function reloadStarRatingOverall(rootPath, realestateId){
	path = getStarRatingUrl(rootPath, 'overall', realestateId, 1);
	$('#star_rating_overall_holder').load(path,'');//reload overall
}

function sendRequest(rootPath){	
	projectId = '';
	realestateId = '';
	
	name = Base64.encode(document.getElementById('request_form_name').value);
	email_request = document.getElementById('request_form_email').value;
	phone = Base64.encode(document.getElementById('request_form_phone').value);
	subject = Base64.encode(document.getElementById('request_form_subject').value);
	message = Base64.encode(document.getElementById('request_form_message').value);
	security_code = document.getElementById('security_code').value;	
	if( document.getElementById('realestateId'))realestateId = document.getElementById('realestateId').value;
	if( document.getElementById('projectId'))projectId = document.getElementById('projectId').value;	
	if( document.getElementById('realestateId2'))realestateId = document.getElementById('realestateId2').value;
	if( document.getElementById('projectId2'))projectId = document.getElementById('projectId2').value;	
	return rootPath+'request_form.php?sendRequest=1&realestateId='+realestateId+"&request_form_name="+name+"&request_form_email="+email_request+"&request_form_phone="+phone+"&request_form_subject="+subject+"&request_form_message="+message+"&security_code="+security_code;
}

function sendContactForm(rootPath){
	name = Base64.encode(document.getElementById('contact_form_name').value);
	email_contact = document.getElementById('contact_form_email').value;
	phone = Base64.encode(document.getElementById('contact_form_phone').value);
	subject = Base64.encode(document.getElementById('contact_form_subject').value);
	message = Base64.encode(document.getElementById('contact_form_message').value);
	security_code = document.getElementById('security_code').value;
	return rootPath+"contact_form.php?sendContactForm=1&contact_form_name="+name+"&contact_form_email="+email_contact+"&contact_form_phone="+phone+"&contact_form_subject="+subject+"&contact_form_message="+message+"&security_code="+security_code;
}

function validateHuman(n1, n2, val){
	r = -1;
	if(n1>n2){
		r = n1 - n2;
	}
	else{
		r = n1 + n2;
	}	
	if(r==val){		
		return true;
	}
	return false;
}

function validateSecurityCode(n1, n2){
	if(document.getElementById('requestGrayButton') && document.getElementById('security_code')){
		state = validateHuman(n1, n2, document.getElementById('security_code').value);
		
		document.getElementById('requestGrayButton').style.display = state ? 'none' : 'inline-block';
		document.getElementById('requestGreenButton').style.display = state ? 'inline-block' : 'none';
		
	}
}

function checkAndEnableContactButton(n1, n2, val, rootPath){
	if(validateHuman(n1, n2, val)){
		$("#contactFormSubmitButton").removeClass("disabledButton");
		$("#contactFormSubmitButton").addClass("greenButton");
		$("#contactFormSubmitButton").attr("onclick", "$('#contact_form').load(sendContactForm('"+rootPath+"'),'');");
	}
	else{
		$("#contactFormSubmitButton").removeClass("disabledButton");
		$("#contactFormSubmitButton").removeClass("greenButton");		
		$("#contactFormSubmitButton").addClass("disabledButton");
		$("#contactFormSubmitButton").removeAttr("onclick");
	}
}

function updateStats(rid, action, email_update, sendPotentialRequests, rootPath){	
	if(action=="phone"){		
  		$('#phoneNumbers').css('display','block');
  		$('#phoneNumbersLink').css('display','none');
	}
	return rootPath+'tracker.php?realestateId='+rid+'&action='+action+'&email='+email_update+'&sendPotentialRequests='+sendPotentialRequests;
}






function resetSelectValue(elementId){
	document.getElementById(elementId).value="";
}

function resetCityArea(){
	if(document.getElementById("filter_cityarea0")){
		for(i=0;i<200;i++){
			if(document.getElementById("filter_cityarea"+i)){
				//document.getElementById("filter_cityarea"+i).checked=false;				
			}
			else{
				break;
			}
		}
	}
}

function setSearchMap(quartName){
	el = document.getElementById("address");
	zoom = 6;
	loc = "Hrvatska";
	
	/*
	select_list_field = document.getElementById('filter_island');
	select_list_selected_index = select_list_field.selectedIndex;
	val = select_list_field.options[select_list_selected_index].value;
	text = select_list_field.options[select_list_selected_index].text;
	*/
	val = $('#filter_island option:selected').val();
	text = $('#filter_island option:selected').text();
	
	
	if(val!="") {
		loc += (text!=""?", ":"") + text;
		zoom = 9;
	}
	/*
	select_list_field = document.getElementById('filter_city');
	select_list_selected_index = select_list_field.selectedIndex;	
	val = select_list_field.options[select_list_selected_index].value;
	text = select_list_field.options[select_list_selected_index].text;
	*/
	val = $('#filter_city option:selected').val();
	text = $('#filter_city option:selected').text();
	
	if(val!="") {
		loc += (text!=""?", ":"") + text;
		zoom = 12;
	}
	
	//backupiramo loc bez kvarta
	loc1 = loc;
	
	if(quartName==""){
		if(document.getElementById("filter_cityarea0")){
			for(i=0;i<200;i++){
				if(document.getElementById("filter_cityarea"+i)){
					if(document.getElementById("filter_cityarea"+i).checked==true){
						loc += (text!=""?", ":"") + (document.getElementById("filter_cityarea"+i).alt);
						zoom = 13;
						break;
					}
				}
				else{
					break;
				}
			}
		}
	}
	else{
		loc += (text!=""?", ":"") + quartName;
		zoom = 13;
	}
	
	el.value = loc;
	//ako nede sa kvartom, probavamo bez njega
	codeAddress(zoom, false);
	generateMapBoundVars();	
}

function setSearchMapAdmin(){
	
	
	el = document.getElementById("address");
	zoom = 6;
	loc = "Hrvatska";
	
	if(document.getElementById("city")){
		selIndex = document.getElementById("city").selectedIndex;
		cityText = document.getElementById("city").options[selIndex].text;
		if(cityText!=""){
			zoom = 9;
			loc += ", "+cityText;
		}
	}
	
	
	if(document.getElementById("street")){		
		if(document.getElementById("street").value!=""){
			zoom = 15;
			loc += ", "+document.getElementById("street").value;
		}
	}
	else if(document.getElementById("cityArea")){
		selIndex = document.getElementById("cityArea").selectedIndex;
		cityAreaText = document.getElementById("cityArea").options[selIndex].text;
		if(cityAreaText!=""){
			zoom = 12;
			loc += ", "+cityAreaText;
		}
	}
	
	el.value = loc;
	
	if(codeAddress(zoom, true)){
		
		
		
	}
	
}

function codeAddress(zoom, showAlert) {
	if(document.getElementById("address")){
		var address = document.getElementById("address").value;		
		geocoder = new google.maps.Geocoder();
		return geocoder.geocode( 
			{ 
				'address': address
			}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setZoom(zoom);
					map.panTo(results[0].geometry.location);					
					return true;					
				} 
				else {
					if(showAlert){alert("Nije moguće naći poziciju na karti po unesenoj adresi. Molimo Vas da sami odredite poziciju!");}
					return false;					
				}
		});
	}
}

function generateMapBoundVars(){
	bounds = map.getBounds()+"";
	arr = bounds.split(",");
	if(arr.length==4 && document.getElementById("map_lat_1")){
		document.getElementById("map_lat_1").value = arr[0].replace("((","").replace("(","").replace("))","").replace(")","").replace(" ","");
		document.getElementById("map_lat_2").value = arr[2].replace("((","").replace("(","").replace("))","").replace(")","").replace(" ","");
		document.getElementById("map_lon_1").value = arr[1].replace("((","").replace("(","").replace("))","").replace(")","").replace(" ","");
		document.getElementById("map_lon_2").value = arr[3].replace("((","").replace("(","").replace("))","").replace(")","").replace(" ","");
	}
}

function checkIntegerValue(element){
	val=parseInt(element.value);
	if(element.value!=""){
		if(isNaN(val)){
			val=0;
		}
		element.value=val;
	}
}

function newWin(url) {
	window.open(url, '_blank');
	return false;
}

function setCookie(name, value, expires) {
	var theDate = new Date();
	var tenYearLater = new Date( theDate.getTime() + 315360000000 );
	var expiryDate = tenYearLater.toGMTString();	
	document.cookie = name + "=" + escape(value) + ((expires == null) ? "; "+expiryDate : "; expires=" + expires.toGMTString());
}

function getCookie(check_name) {
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        a_temp_cookie = a_all_cookies[i].split('=');
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        if (cookie_name == check_name) {
            b_cookie_found = true;
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function initializeTogleSearchResultMap() {
    if(document.getElementById("show_hide_map")){
    	    
    	    if (getCookie("SearchResultMapVisible") != "false") {
    	    	    initializeSearchResultMap();
    	    }
    	    
	    $("#show_search_map_button").click(function() {
	        $('#show_hide_map').slideToggle('slow', function() {if(!map){initializeSearchResultMap();}})
		setCookie("SearchResultMapVisible", "true", null);
		document.getElementById("show_search_map_button").style.display = "none";
		document.getElementById("hide_search_map_button").style.display = "block";  
	    });
	    
	    $("#hide_search_map_button").click(function() {
		$('#show_hide_map').slideToggle('slow', function() {})
		setCookie("SearchResultMapVisible", "false", null);
		document.getElementById("show_search_map_button").style.display = "block";
		document.getElementById("hide_search_map_button").style.display = "none";
	    });
	    
	    
	    if (getCookie("SearchResultMapVisible") == "false") {
		document.getElementById("show_search_map_button").style.display = "block";
		document.getElementById("hide_search_map_button").style.display = "none";
		//setTimeout("$('#show_hide_map').slideToggle('fastest', function() {})",1);
	    }
	    else{
	    //if(getCookie("SearchResultMapVisible") == "true"){
		document.getElementById("show_search_map_button").style.display = "none";
		document.getElementById("hide_search_map_button").style.display = "block";
	    }
    }
}

function initializeTogleMyTools(){
   if(document.getElementById("my_tools_toggle")){
	    
   	   $("#show_my_tools").click(function() {
		$('#my_tools_toggle').slideToggle('slow', function() {})
		setCookie("MyToolsVisible", "true", null);
		document.getElementById("show_my_tools").style.display = "none";
		document.getElementById("hide_my_tools").style.display = "block";  
	    });
	    
	    $("#hide_my_tools").click(function() {
		$('#my_tools_toggle').slideToggle('slow', function() {})
		setCookie("MyToolsVisible", "false", null);
		document.getElementById("show_my_tools").style.display = "block";
		document.getElementById("hide_my_tools").style.display = "none";
	    });
	    
	    if(getCookie("MyToolsVisible") == "false"){
		document.getElementById("show_my_tools").style.display = "block";
		document.getElementById("hide_my_tools").style.display = "none";
		document.getElementById("my_tools_toggle").style.display = "none";
		//setTimeout("$('#show_hide_map').slideToggle('fastest', function() {})",1);
	    	    
	    	
	    }
	    else {
		document.getElementById("show_my_tools").style.display = "none";
		document.getElementById("hide_my_tools").style.display = "block";
	    }
    }
}

function initializeSearchResultMap(){
	if(document.getElementById("search_result_map") && getCookie("SearchResultMapVisible") != "false"){		
		latlng = new google.maps.LatLng(44.8325,15.941162);
		var myOptions = {
			zoom: 6,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false,
			zoomControl: true,
			zoomControlOptions: {
				style: google.maps.ZoomControlStyle.LARGE
			}
		};
		map = new google.maps.Map(document.getElementById("search_result_map"), myOptions);
		setMarkers(map, MarkersArray);
	}
}

function initializeAdminMap(latlng, zoom){
	if(document.getElementById("admin_map")){		
		if(!latlng) latlng = new google.maps.LatLng(44.8325,15.941162);
		if(!zoom) zoom = 6;
		var myOptions = {
			zoom: zoom,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false,
			zoomControl: true,
			zoomControlOptions: {
				style: google.maps.ZoomControlStyle.LARGE
			}
		};
		geocoder = new google.maps.Geocoder();
		map = new google.maps.Map(document.getElementById("admin_map"), myOptions);
		google.maps.event.addListener(map, 'click', function(event) {
			clearOverlays();
			addMarker(event.latLng);
			map.panTo(event.latLng);
		});
		
		google.maps.event.addListener(map, 'zoom_changed', function(event) {			
			if(document.getElementById("zoom")) document.getElementById("zoom").value = map.getZoom();
		});
	}
}

var markersArray = [];
function addMarker(location) {	
	marker = new google.maps.Marker({
		position: location,
		map: map,
		icon: rootPath + "/include/images/icons/marker.png"
	});
	markersArray.push(marker);	
	if(document.getElementById("longitude")) document.getElementById("longitude").value = location.lng();
	if(document.getElementById("latitude")) document.getElementById("latitude").value = location.lat();
	if(document.getElementById("zoom")) document.getElementById("zoom").value = map.getZoom();
}

function clearOverlays() {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);			
		}
	}
}


function initializeSearchMap(){
	if(document.getElementById("map_canvas")){
		latlng = new google.maps.LatLng(44.8325,15.941162);
		geocoder = new google.maps.Geocoder();
		var myOptions = {
			zoom: 6,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false,
			zoomControl: true,
			zoomControlOptions: {
				style: google.maps.ZoomControlStyle.LARGE
			}

		};
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);		
		google.maps.event.addListener(map, 'bounds_changed', function() {
		    generateMapBoundVars();
		});
		setSearchMap('');
	}
}


function createMarker(latlng, html, iconImage) {
    var contentString = html;
    var marker = new google.maps.Marker({
	position: latlng,
	map: map,
	zIndex: Math.round(latlng.lat()*-100000)<<5,
	icon: iconImage
	});

    google.maps.event.addListener(marker, 'click', function() {
	infowindow.setContent(contentString); 
	infowindow.open(map,marker);
	});
}

function setMarkers(map, locations) {
	var bounds = new google.maps.LatLngBounds();
	var marker=[];
	var infowindow=[];
	for (var i = 0; i < locations.length; i++) {
	    var MarkersArray = locations[i];
	    var myLatLng = new google.maps.LatLng(MarkersArray[1], MarkersArray[2]);
	    bounds.extend(myLatLng);
	    var point = new google.maps.LatLng(MarkersArray[1], MarkersArray[2]);
	    var marker = createMarker(point,MarkersArray[4], rootPath+ 'include/images/icons/' + MarkersArray[6]);
	}
	  map.fitBounds(bounds);
}

var redirectCnt = 20;
var redirectCanceled = false;
function Redirect(redirectUrl){                        
	if(!redirectCanceled){
		if (redirectCnt > 0){
			document.getElementById("cntDisp").innerHTML =  redirectCnt;
			redirectCnt = redirectCnt - 1;
			setTimeout("Redirect('"+redirectUrl+"')", 1000);
		}
		else {
			document.getElementById("cntDisp").innerHTML =  "0";
			document.location = redirectUrl;
		}
        }
}

function CancelRedirect(){
	redirectCanceled = true;
	document.getElementById("cntDisp").innerHTML =  "0";
}

function CloseRedirect(){
	document.getElementById("redirectBlock").style.display='none';
}

function delay(){}

var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function markMessageRead(element){
	element.className = 'popup readMessage';
}

function smallSearchFormDataCheck(city, cityArea){
	if(document.getElementById("cityAutocomplete_small").value==city)document.getElementById("cityAutocomplete_small").value = '';
	if(document.getElementById("cityAreaAutocomplete_small").value==cityArea)document.getElementById("cityAreaAutocomplete_small").value = '';
}

function setLoginRedirectPage(page){
	if(document.getElementById("pageToRedirect")){
		document.getElementById("pageToRedirect").value = page;	
	}
}

