//some global data
var globalObj = {
		cache : {},
		imageLinks : {},
		decsrfc : ''//$.cookie("decsrfc")
};

$(document).ready(function() {
	
	//fancybox
	$("a.fancybox").fancybox({
		'transitionIn'	:	'elastic',
		//'transitionOut'	:	'elastic',
		'speedIn'		:	400,
		'speedOut'		:	300, 
		'overlayShow'	:	true,
		'titlePosition' : 	'over',
		'titleFormat'   : 	function(title, currentArray, currentIndex, currentOpts) {
				return '<span id="fancybox-title-over">' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
		},
		'overlayColor'  :	'#000',
		'opacity'		:	true 	
	});	
	
	//iframe fancybox
	$("a.fancy-frame").fancybox({
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'type'			: 'iframe',
		'width'			: 640,
		'height'		: 480,
		'scrolling'		: 'no'
	});
	
	/**********************************
	 * Collapsible fieldsets
	 **********************************/
	$("fieldset.collapsible").collapse();
	$("fieldset.startClosed").collapse( { closed: true } );
	
	/**********************************
	 * Confirm deleting
	 **********************************/
	$('a.delete').live('click', function(){ return confirm('Biztos, hogy törölni szeretnéd?'); });	
	
	/**********************************
	 * Datepickers
	 **********************************/
	$.datepicker.setDefaults( $.datepicker.regional[ "hu" ] );
	$(".dp1").datepicker({ dateFormat: 'yy-mm-dd', maxDate: new Date() });
	$(".dp2").datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date() });
	
	var dates = $( "#datum_tol, #datum_ig" ).datepicker({
		dateFormat: 'yy-mm-dd', 
		maxDate: "+1d",
		changeMonth: true,
		changeYear: true,
		onSelect: function( selectedDate ) {
			var option = this.id == "datum_tol" ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" ),
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings );
			dates.not( this ).datepicker( "option", option, date );
		}
	});
	
	/**********************************
	 * Default values
	 **********************************/
	var azon_label = $("input#azonosito").siblings("label").text();
	$("input#azonosito").defaultvalue(azon_label, "keresett kifejezés");
	$("#search-input").defaultvalue("keresés hírekben és kérdésekben");

	/**********************************
	 * AJAX pagination
	 **********************************/
	$('.ajax-pagination > div.fc > span a').live('click', function(e){
		e.preventDefault();
		
		var link 	= $(this).attr('href');
		var target 	= "#ajax_content";
		
		//console.log('link');
		
		$.ajax({
			url: link,
			type: "GET",
			dataType: "html",
			beforeSend: function(){
				showBusy(target);
			},	
		  	success: function(html) {
		    	updateContent(target, html);
		 	}
		});
	});
	
	/**********************************
	 * AJAX save property
	 **********************************/
	$(".save_property").click(function(){
		
		var target 	= "#saved-properties .content";
		var id 		= $(this).attr("id"); //e.g. "p123" ("p" and the ID of the property)
		var propId 	= id.substr(1);
		propId 		= parseInt(propId);
		
		if(propId > 0)
		{
			$.ajax({
				url: base_url + 'ajax/save_property',
				type: "POST",
				dataType: "html",
				data: "pid="+ propId,// + "&decsrft=" + globalObj.decsrfc,
			  	success: function(data) {
					
					if(data != '') {
						updateSavedProperties(target, data, 'Az ingatlan sikeresen megjegyezve!');
        			} else {
            			return;
            		}
			 	}
			});
		}		
	});

	/**********************************
	 * AJAX remove saved property
	 **********************************/
	$(".remove_property").live("click", function(){
		
		var target 	= "#saved-properties .content";
		var id 		= $(this).attr("id"); //e.g. "sp123" ("sp" and the ID of the property)
		var propId 	= id.substr(2);
		propId 		= parseInt(propId);
		
		if(propId > 0)
		{
			$.ajax({
				url: base_url + 'ajax/remove_saved_property',
				type: "POST",
				dataType: "html",
				data: "pid="+ propId,// + "&decsrft=" + globalObj.decsrfc,
			  	success: function(data) {
					
					if(data != '') {
						updateSavedProperties(target, data, 'Az ingatlan sikeresen eltávolítva!');
        			} else {
            			return;
            		}
			 	}
			});
		}
	});	
	
	/**********************************
	 * AJAX get cities
	 **********************************/
	$("select[name='megye']").change(function(){
		
		var request 			= [];		
		var sid 				= $(this).val();
		var telepulesSelectObj 	= $("select#telepulesek");

		if(sid > 0)
		{	
			//chached already?
			if(sid in globalObj.cache)
			{
				addOptions(globalObj.cache[sid]);
				return;
			}
			
	        $.ajax({
	            url: base_url + 'ajax/get_cities',
	            dataType: 'json',
	            type: 'POST',
	            data: "sid="+ sid,// +"&decsrft=" + globalObj.decsrfc,
	            success:
	        		function(data)
	        		{
	            		if(data.response == 'true')
	        			{
	            			//cache the message
	            			globalObj.cache[sid] = data.message;
            				addOptions(data.message);
	        			}
	            		else
	            		{
	            			addOptions();
	            		}
	        		}
	        });
		}
	});
	
	/**********************************
	 * AJAX more images
	 **********************************/	
	$("a.images-more").click(function(){
		
		var ajaxFunction = "get_property_images";
		var attrRel = $(this).attr("rel");
		var attrType = attrRel.substr(0,1);
		var propId = attrRel.substr(1);
		
		propId = parseInt(propId);
		
		if(attrType == "f")
		{
			ajaxFunction = "get_floor_map_images";
		}
		
		if(propId > 0)
		{
			imageLinks = new Array();
			
			$.ajax({
	            url: base_url + 'ajax/' + ajaxFunction,
	            dataType: 'json',
	            type: 'POST',
	            data: "pid="+ propId,// + "&decsrft=" + globalObj.decsrfc,
	            success:
	        		function(data)
	        		{
	            		if(data.response == 'true')
	        			{
	            			$.each(data.message, function(i, val) {
	            				imageLinks.push(val.url);
	            		    });
	            			
	            			$.fancybox(
	            					imageLinks,
	            					{
	            						'type'			: 	'image',
	            						'transitionIn'	:	'elastic',
	            						'transitionOut'	:	'elastic',
	            						'speedIn'		:	400,
	            						'speedOut'		:	300,
	            						'overlayShow'	:	true,
	            						'overlayColor'  :	'#000',
	            						'opacity'		:	true,
	            						'titlePosition' : 	'over',
	            						'titleFormat'   : 	function(title, currentArray, currentIndex, currentOpts) {
	            						    					return '<span id="fancybox-title-over">' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
	            											}
	            					}
	            			);
	        			}
	            		else
	            		{
	            			$.fancybox('Jelenleg nincsenek képek az adott ingatlanhoz!', {'modal' : true, 'padding': 20, 'hideOnOverlayClick' : true, 'hideOnContentClick': true, 'overlayOpacity': 0.6});
	            			window.setTimeout(function(){$.fancybox.close();}, 3000);
	            		}
	        		}
	        });		
		}
		else
		{
			return;
		}
	});
	
	//árak beállítása attól függően, hogy eladó/kiadó ingatlant keres 
	$("select#ertekesites").change(function(){
		
		var minSelectObj = $("select#ar-min");
		var maxSelectObj = $("select#ar-max");
		var propType 	 = $(this).val();
		
		setPrices(minSelectObj, maxSelectObj, propType);
		
	});
	
	$("#left #advanced-search").find("input").attr("disabled", "disabled");
	$("#left #advanced-search").find("select").attr("disabled", "disabled");
	
	$("#ct_blocks #toggle-advanced-search").click(function(){

		//collect inputs and selects
		var inputs = $("#ct_blocks #advanced-search").find("input");
		var selects = $("#ct_blocks #advanced-search").find("select");
		
		if($("#ct_blocks #advanced-search").hasClass("open"))
		{
			//hide the advanced search block
			$("#ct_blocks #advanced-search").removeClass("open")
											.stop()
											.animate({"opacity": "hide"}, { queue:false, duration:100 });
			
			//resize the search block
			$("#ct_blocks #search-block-3").stop().animate({'width':'380px'}, { queue:false, duration:500 });
			
			//display the hidden blocks
			window.setTimeout(function(){
				$("#ct_blocks div.block").show();
			}, 500);
			
			//set to the default the input fields, selects --> disable them
			inputs.attr("disabled", "disabled");
			selects.attr("disabled", "disabled");
			
			//remove the cookie
			$.cookie('advanced_search', null, { path: '/', domain: $(location).attr('host') });
		}
		else
		{
			$("#ct_blocks div#block-2").hide();
			
			//resize the search block
			$("#ct_blocks #search-block-3").stop().animate({'width':'770px'}, { queue:false, duration:200 });
			
			//display the advanced search part of the form
			window.setTimeout(function(){
					$("#ct_blocks #advanced-search").addClass("open")
					.css({'margin-left':'10px'})
					.stop()
					.animate({"opacity": "show"}, { queue:false, duration:50 });
			}, 200);
			
			//enable inputs
			inputs.removeAttr("disabled");
			selects.removeAttr("disabled");
			
			//set the cookie
			$.cookie('advanced_search', 1, { path: '/', domain: $(location).attr('host') });
		}
		
	});

	//if the advanced_search cookie is set, display the advanced search part of the form
	if($.cookie('advanced_search') == 1)
	{
		$("#ct_blocks #toggle-advanced-search").trigger('click');
	}
	else
	{
		$("#ct_blocks #advanced-search").hide();
	}
	
	//limit form
	$("form.per-page select[name='plimit']").change(function(){
		
		$("form#prop-filter-form input[name='limit']").val($(this).val());
		$("form#prop-filter-form").submit();
		
	});

	//order form
	$("select[name='order_by']").change(function(){
				
		$("form#prop-filter-form input[name='order']").val($(this).val());
		$("form#prop-filter-form").submit();
		
	});
	
	/*************************************
	 * Scrollables - needs jQuery Tools!!
	 *************************************/
	// initialize scrollables
	//property images
	$("#prop-images").scrollable({prev: '.images-nav .prev', next: '.images-nav .next' });
	//saved properties
    $("#sp-list").scrollable({mousewheel: true, easing: 'linear', speed: 300, vertical: true, prev: '#saved-properties .sp-nav .prev', next: ' #saved-properties .sp-nav .next' });
    //featured properties
    $("#fp-list").scrollable({mousewheel: true, easing: 'linear', speed: 1000, vertical: true, prev: '#featured-properties .sp-nav .prev', next: '#featured-properties .sp-nav .next', circular: true}).autoscroll({ autoplay: true, interval: 4000, steps: 1});
});

//show google map on the property page
//needs google api script before this file!!!
function showMap(id, address, showInfoWindow)
{
  if (GBrowserIsCompatible())
  {
    var map = new GMap2(document.getElementById(id));
    //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    gc = new GClientGeocoder();
    gc.getLatLng(address, function(point){

        if( ! point)
        {
            alert("A cím nem található: " + address);
        }
        else
        {
            map.setCenter(point,15);
            
            var marker = new GMarker(point);
            map.addOverlay(marker);
            
            if(showInfoWindow)
            {
            	marker.openInfoWindowHtml(address);
            }
            
            var mapControl = new GMapTypeControl();
            map.addControl(mapControl);
            map.addControl(new GSmallMapControl());
        }
        
    });
  }
}


function setPrices(minSelectObj, maxSelectObj, propType)
{	
	var options = '<option value="-1"> - </option>';
	
	if(propType == '-1')
	{
		//üres
		minSelectObj.html(options);
		maxSelectObj.html(options);
		return;
	}
	else if(propType == 0)
	{
		//kiadó
		var prices 	= [50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600,700,800,900];
		var suffix 	= "e";
		var text 	= "eFt";
	}
	else
	{
		//eladó és cserélhető
		var prices	= [1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,24,26,28,30,35,40,45,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,340,350,360,370,380,390,400,410,420,430,440,450,460,470,480,490,500];
		var suffix 	= "m";
		var text 	= "mFt";
	}
	
	$.each(prices, function(i, val){
		options += '<option value="' + val + suffix + '">' + val + ' ' + text + '</option>\n';
	});
	
	minSelectObj.html(options);
	maxSelectObj.html(options);
}

function addOptions(data)
{
	var telepules_select = $("select#telepulesek");
	var options = '<option value="-1">Összes település</option>';

	if(data)
	{
		$.each(data, function(i, val) {
			options += '<option value="' + val.id + '">' + val.nev + '</option>\n';
	    });
	}
	
	telepules_select.html(options);
}

function showBusy(target)
{
	$(target).block({
		message: 'Töltődik, türelem...',
		css: {border:'3px solid #000'}
	});
}

function updateContent(target, html)
{	
	window.setTimeout( function(){
		$(target).html(html);
	}, 1000);
}

function updateSavedProperties(target, data, msg)
{	
	window.setTimeout( function(){
		$(target).html(data);
		$("#sp-list").scrollable({mousewheel: true, easing: 'linear', speed: 300, vertical: true, prev: '.sp-nav .prev', next: '.sp-nav .next' });
		$.fancybox(msg + '<a href="javascript:;" id="fancybox-close" onclick="$.fancybox.close()"></a>', {'modal' : true, 'padding': 20, 'hideOnOverlayClick' : true, 'hideOnContentClick': true, 'showCloseButton': true});
	}, 1000);
	window.setTimeout(function(){$.fancybox.close();}, 3000);
}

BookmarkApp = function () {
    var isIEmac = false;
    var isMSIE = (-[1,]) ? false : true;
    var title = "Danubia Estate Ingatlanok";
    var bmHref = location.href;

    function hotKeys() {
        var ua = navigator.userAgent.toLowerCase();
        var str = '';
        var isWebkit = (ua.indexOf('webkit') != - 1);
        var isMac = (ua.indexOf('mac') != - 1);

        if (ua.indexOf('konqueror') != - 1) {
            str = 'CTRL + B'; // Konqueror
        } else if (window.home || isWebkit || isIEmac || isMac) {
            str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab, IE5/Mac
        }
        return ((str) ? 'Az oldal könyvjelzőkhöz adásához nyomja meg a ' + str + ' billentyű kombinációt!' : str);
    }

    function isIE8() {
        var rv = -1;
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
        }
        if (rv > - 1) {
            if (rv >= 8.0) {
                return true;
            }
        }
        return false;
    }

    function addBookmark(a) {
        try {
            if (typeof a == "object" && a.tagName.toLowerCase() == "a") {
                a.style.cursor = 'pointer';
                if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
                    window.sidebar.addPanel(title, bmHref, ""); // Gecko
                    return false;   
                } else if (isMSIE && typeof window.external == "object") {
                    if (isIE8()) {
                        window.external.AddToFavoritesBar(bmHref, title); // IE 8                    
                    } else {
                        window.external.AddFavorite(bmHref, title); // IE <=7
                    }
                    return false;
                } else if (window.opera) {
                    a.href = bmHref;
                    a.title = title;
                    a.rel = 'sidebar'; // Opera 7+
                    return true;
                } else {
                    alert(hotKeys());
                }
            } else {
                throw "Hiba történt.\r\nCsak a tag engedélyezett!";
            }
        } catch (err) {
            alert(err);
        }
        
    }
    
    return {
        addBookmark : addBookmark
    }
}();

