/**
 * JQuery Map Popup plugin by Pieter Coucke for Onthoo BVBA.
 */
(function($) {
 
	var geocoder;
	var map_canvas;
	var map;
	var marker;
	var mapOffsetLeft;
	var config;
	var link;
	var address;
	 
   $.fn.mapPopup = function(settings) {
     config = {
    		 'width': 400,
    		 'height': 400
     };
 
     if (settings) $.extend(config, settings);
 
     this.each(function() {
    	 $(this).addClass('mapPopup').bind('click',codeAddress);
     });
 
     return this;
   };
   
   function mapsLoaded() {
   	  geocoder = new google.maps.Geocoder();
   	  var latlng = new google.maps.LatLng(-34.397, 150.644);
   	  var myOptions = {
   	    zoom: 8,
   	    center: latlng,
   	    disableDefaultUI: true,
   	    navigationControl: true,
   	    mapTypeId: google.maps.MapTypeId.ROADMAP
   	  }
   	  map_canvas = $('<div id="mapPopup_canvas_wrapper">'
   			  	+ '<div id="mapPopup_canvas_wrapper_close"><a href="#">' + messages.js.map.close() + '</a></div>'
   			  	+ '<div id="mapPopup_canvas" class="map" style="width: '+config.width+'px; height: '+config.height+'px;"></div>'
   			  +'</div>');
   	  $('#right').append(map_canvas);
   	  //map_canvas.hide();
   	  $('#mapPopup_canvas_wrapper_close a').bind('click',function(){$('#mapPopup_canvas_wrapper').hide('fast');return false;});
   	  map = new google.maps.Map(document.getElementById("mapPopup_canvas"), myOptions);
   	  codeAddressCallback();
   };
     
   window.mapPopupMapsLoaded = mapsLoaded;
   
   function initialize() {
	 //google.load("maps", "2", {"callback" : mapsLoaded});
	 var script = document.createElement("script");
	 script.type = "text/javascript";
	 script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=mapPopupMapsLoaded";
	 document.body.appendChild(script);
   };
   
   function codeAddress(event) {
	 event.preventDefault();
     link = $(this);
     address = $(this).text();
     
     if (!mapOffsetLeft) {
   	  mapOffsetLeft = link.offset().left + link.width() - config.width;
     }
     
     // lazy initialize
     if (!geocoder) {
    	 initialize();
     } else {
    	 codeAddressCallback();
     }
     return false;
  };
   
  function codeAddressCallback() { 
     if (geocoder) {
       geocoder.geocode( {'address': address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
           map.setCenter(results[0].geometry.location);
           
           // clear the previous marker
           if (marker) {
           	marker.setMap(null);
           }
           
           marker = new google.maps.Marker({
               map: map, 
               position: results[0].geometry.location
           });
           
           // The left needs to be specified or IE 8 gives an error
           var top = link.offset().top;
       	   map_canvas.offset({'top':(top+20),'left':mapOffsetLeft});
       	   map_canvas.fadeIn();
           
           if (config.callback) {
        	   config.callback(address);
           }
           
           // Scroll the map in viewable area
           //$(document).scrollTop(offset.top-100);
         } else {
           //alert("Geocode was not successful for the following reason: " + status);
         }
       });
     }
   }
 
})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function zamtam_findInArray(arr,v) {
	for(var i=0; i < arr.length; i++) {	if(arr[i] == v) { return i; } }	return -1;
}

function zamtam_formatNumber(nStr) {
	if(nStr > 3000){
		var rgx = /(\d+)(\d{3})/; nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : '';
	while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + '.' + '$2');	}
		return x1+x2;
	} else {
		return nStr;
	}
}

function zamtam_createPriceSlider(){
	if ($("#priceslider").length > 0) {
		var prices = [0,1,2,3,4,5,6,7,8,9,10,
	   		15,20,25,30,35,40,45,50,
			60,70,80,90,100,
			110,120,130,140,150,
			175,200,225,250,275,
			300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000,
			1100,1200,1300,1400,1500,1600,1700,1800,2000,
			2100,2200,2300,2400,2500,2600,2700,2800,2900,
			3000,3500,4000,4500,5000,5500,6000,6500,7000,7500,8000,8500,9000,9500,10000,
			11000,12000,13000,14000,15000,16000,17000,18000,19000,20000,21000,22000,23000,24000,25000,26000,27000,28000,29000,30000,
			31000,32000,33000,34000,35000,36000,38000,40000,42000,44000,45000,50000,
			60000,65000,70000,75000,80000,85000,90000,95000,100000,
			110000,120000,130000,140000,150000,160000,170000,180000,190000,200000,
			210000,220000,225000,230000,240000,250000,275000,300000,325000,350000,375000,400000,450000,500000];
		$("#priceslider").slider({
			range: true,
			min: 0,
			max: (prices.length-1),
			values: [zamtam_findInArray(prices,$("#min").val()), (zamtam_findInArray(prices,$("#max").val()) > 0 ? zamtam_findInArray(prices,$("#max").val()) : (prices.length-1) )],
			step: 1,
			slide: function(event, ui){
				var maxvalue = ui.values[1];
				$("#min").val(prices[ui.values[0]]);
				if (maxvalue == $("#priceslider").slider("option", "max")) {
					$("#max").val((prices[prices.length-1]));
				} else {
					$("#max").val(prices[ui.values[1]]);
				}
				zamtam_priceslider_updateDisplay();
			},
			change: function(event, ui){
				$("#searchForm").submit();
			},
		});
		
		function zamtam_priceslider_updateDisplay() {
			var minvalue = prices[$("#priceslider").slider("values", 0)];
			var maxvalue = prices[$("#priceslider").slider("values", 1)];
			if (maxvalue == prices[prices.length-1]) {
				if (minvalue == prices[0]) {
					$("#pricesliderInfo").html(messages.js.price.all());
				} else {
					$("#pricesliderInfo").html(messages.js.price.from(zamtam_formatNumber(minvalue)));
				}
			} else {
				if (minvalue == prices[0]) {
					$("#pricesliderInfo").html(messages.js.price.to(zamtam_formatNumber(maxvalue)));
				} else {
					$("#pricesliderInfo").html(messages.js.price.fromto(zamtam_formatNumber(minvalue),zamtam_formatNumber(maxvalue)));
				}
			}
		}
		
		zamtam_priceslider_updateDisplay();
	}
}
	  
/**
 * When a user clicks on an itemlink, the Google Analytics tracker is notified.
 */
function trackItemLink() {
	var provider = 'unknown';
	var prefix = 'provider-';
	var hrefClass = $(this).attr('class');
	if (hrefClass) {
		var allClasses = hrefClass.split(' ');
		if (allClasses) {
			providers = jQuery.grep(allClasses, function(current, index){
		      return (current.substr(0,prefix.length) == prefix);
		    });
			if (providers.length > 0) {
				var provider = providers[0].substr(prefix.length);
			}
		}
	}
	
	_gaq.push(['_trackEvent', 'Item', 'Visit - ' + provider, this.href]);
	//return false;
}

function hideRecommendedSite() {
	_gaq.push(['_trackEvent', 'Recommended Site', 'Hide', window.location.href]);
	$('#recommended-site').fadeOut();
	$.cookie("recommended_site_message", "hide", {expires: 365});
}

//function toggleEmailAlertForm() {
	//$('#email-alert-form').toggle('fast');
//}

function handleEmailAlertSubmit() {
		$("#email-alert-submit").after('<img src="/static/imgs/ajax-loader.gif" alt="" class="ajax-loader" id="email-alert-loading" />');
		//var keywords = $('#email-alert-keywords').val();
		var vars = {};
		$("#email-alert-form input[type=hidden]").each(function(i,el){
			el = $(el);
			vars[el.attr('name')] = el.val();
		});
		$.post("/dyn/alert/subscribe",
		    vars,
		   	function(data){
			    _gaq.push(['_trackPageview','/goal/alert/email/subscribed']);
				$("#email-alert").slideUp("normal", function() {
					$("#email-alert").before('<div class="message">' + messages.js.alert.success() + '</div>');
				});
			}
		);
//	}
	
	return false;
}

$(function(){
	zamtam_createPriceSlider();
	
	$('.item').each(function(i){
		var id = this.id;
		$('#' + id + ' a').each(function(j) {
			if ($(this).attr('href') != '#') {
				$(this).bind('click',trackItemLink);
			}
		});
	});
	
	$('#recommended-site-hide').bind('click',hideRecommendedSite);
	
	$('#email-alert-message').toggle(
	  function () {
		  $('#email-alert-box').slideDown("fast");
	    _gaq.push(['_trackPageview','/goal/alert/email/showform']);
	    return false;
	  },
	  function () {
		  $('#email-alert-box').slideUp("fast");
	    _gaq.push(['_trackPageview','/goal/alert/email/hideform']);
	    return false;
	  }
	 );
	
	$("#email-alert-submit").bind('click',handleEmailAlertSubmit);
	
	$('.location-popup').mapPopup({
		'width':400,
		'height':400,
		'callback':function(address){
			_gaq.push(['_trackEvent', 'Map', 'Show', address]);
		}
	});
	
	//alert(google.loader.ClientLocation.address.city + " / " + google.loader.ClientLocation.address.country_code + " / " + google.loader.ClientLocation.address.region);
	
});
