function load_ajax(id, page) {
    $.ajax({
	type: "GET",
	url: page,
	success: function(html){
	    $(id).empty();
	    $(id).append(html);
            init_search_bar();
            create_dropdowns();
            $("div.dateList ul.eventsList li.event:odd").css({
                "background-color": "#fff"
            });
            $("ul.rightList li:odd").css({
                "background-color": "#fff"
            });
	}
    });
}

function compare_latlng(point, compare_point) {
	if (point.ee==compare_point.ee && point.ge==compare_point.ge) {
		return true
	}
	return false;
}
var infowindow = new google.maps.InfoWindow({ 
	size: new google.maps.Size(580,400)
}); 


function create_marker(map, latlng, html, title) {
	var image = '/static/images/icon_map_arrow.png';
	
	var marker = new google.maps.Marker({
        position: latlng, 
        map: map, 
        icon: image,
        zIndex: 0,
        clickable: true,
        title: title
    });   
	//console.log(infowindow);
        
	
	//infowindow.content = false;
    google.maps.event.addListener(marker, 'click', function() {
    	infowindow.content = html;
    	infowindow.open(map, marker);
    }); 

}


function load_map(id, event_ids) {
    var url = '/ajax/map/';
	
    $.get(url, {'event': event_ids}, function(results) {
	eval("r="+results);
	
	//console.log(r);
	
	var latlng = new google.maps.LatLng(r.event_list[0].venue.latitude, r.event_list[0].venue.longitude);
	
	
	var mapOptions = {
	    zoom: 15,
	    center: latlng,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	var map = new google.maps.Map(document.getElementById("map_canvas-"+id), mapOptions);
	var map_bounds = new google.maps.LatLngBounds(); 
    
	var windows = [];
	var window_number = false;
	
	$(r.event_list).each(function() {
		var latlng = new google.maps.LatLng(this.venue.latitude, this.venue.longitude);

		create_window = true;
	    for (var win=0; win<=(windows.length+1); win++) {  	
	    	if (windows[win]) {
	  
		    	if (windows[win].latlng.equals(latlng)) {
		    		create_window = false;
		    		window_number = win;
		    	}
	    	}
	    }
	    
	    if (create_window) {
	    	windows.push({latlng: latlng, events: [this]})
	    } else {
	    	windows[window_number].events.push(this);
	    }
	});
	
	for (var win=0; win<=windows.length; win++) {  	
		
		var current_window = windows[win];

		
		if (current_window) {
			var events = current_window.events;
			var venue = current_window.events[0].venue;
			var latlng = current_window.latlng;
			if (current_window.events.length>=2) {
				var title = venue.name;
			    var html = '<div style="width: 450px;">';
			    html += '<div style="float: left; width: 37%;">';
			    html += '<h2><a href="' + venue.url + '">' + venue.name + '</a></h2>';
			    html += venue.address + '<br />';
			    html += venue.city + ', ' + venue.province;
			    html += '</div>';
			    
			    html += '<div style="float left; width: 60%; padding-left: 2%; height: 115px; overflow-y: auto;">';
			    
			    $(current_window.events).each(function() {	
			    	
				html += '<p class="first"><b>' + this.date + '</b> - ' + this.title;
		            
				//console.log(this);
				
	
				html+= '<ol class="buyList">';
				if (this.urmusic_ticket_url) {
				    html+= '<li class="urMusic">';
				    html+= '<a href="'+this.urmusic_ticket_url+'" title="Buy Tickets">Buy Tickets</a>';
		            html+= '</li>';
		            inset_class = '';
				} else {
					inset_class = 'inset';
				}
				if (this.livenation_ticket_url) {
				    html+= '<li class="'+inset_class+'">';
				    html+= '<a href="'+this.livenation_ticket_url+'" title="Buy Tickets">Buy Tickets</a>';
		            html+= '</li>';		
				
				}
				html+= '</ol>';

			
			    });
			    
			    html += '<br /><br /></div><div style="clear: both;"></div>';
			    html += '</div>';
			    
			} else {
				
		        if (current_window.events[0].artists_headline[0]) {
				    var title = current_window.events[0].artists_headline[0].name+' - '+current_window.events[0].venue.name;
				} else {
		            var title = current_window.events[0].artists_other[0].name + ' - ' + current_window.events[0].venue.name;
		        }
		                
				var html = '<div style="width: 400px;">';
				html += '<div style="float: left; width: 37%;">';
				html += '<h2><a href="' + current_window.events[0].venue.url + '">' + current_window.events[0].venue.name + '</a></h2>';
				html += current_window.events[0].venue.address + '<br />';
				html += current_window.events[0].venue.city + ', ' + current_window.events[0].venue.province;
				html += '</div>';
			    html += '<div style="float left; padding-left: 2%; width: 60%; height: 115px; overflow-y: auto;">';
			    html += '<p class="first"><b>'+current_window.events[0].title+'</b> on ' + current_window.events[0].date + '<br />';

				html+= '<ol class="buyList">';
				if (current_window.events[0].urmusic_ticket_url!=null) {
				    html+= '<li class="urMusic">';
				    html+= '<a href="'+current_window.events[0].urmusic_ticket_url+'" title="Buy Tickets">Buy Tickets</a>';
		            html+= '</li>';	
		            inset_class = '';
				} else {
					inset_class = 'inset';
				}
				if (current_window.events[0].livenation_ticket_url) {
				    html+= '<li class="'+inset_class+'">';
				    html+= '<a href="'+current_window.events[0].livenation_ticket_url+'"  title="Buy Tickets">Buy Tickets</a>';
		            html+= '</li>';		
				
				}
				html+= '</ol></p>';

				
			    html += '<br /><br /><div style="clear: both;"></div>';   
			    html += '</div>';
			    html += '</div>';
			}
	
			create_marker(map, latlng, html, title);
			map_bounds.extend(latlng);
			map.set_center(map_bounds.getCenter()); 
			map.fitBounds(map_bounds); 
			
			
		    
		}
		//console.log("Zoom Level", map.get_zoom())
	    //map.set_zoom(map.get_zoom()-5);
	}
        
	
    });
    $('#option-listing-'+id).show();
    $('#option-map-'+id).hide();
    
    $('#listing-'+id).hide();
    $('#map-'+id).show(); 
}

function hide_map(id) {
    $('#option-listing-'+id).hide();
    $('#option-map-'+id).show();
    $('#listing-'+id).show();
    $('#map-'+id).hide(); 
}

function create_dropdowns() {
    $('span.dropdown').each(function() {
	data = $(this).children('ul');
	link = $(this).children('a');

	pos = data.position();
	data.css({position: "absolute",
	          marginLeft: 0, marginTop: 0,
	          top: (pos.top+link.height()+5), left: (pos.left-link.width()-5) });
	
	$(data).hide();
        
	link.bind("click", function() {	    
	    $(this).parent().children('ul').slideDown();
	    $(this).parent().children('ul').children('li').bind("click", function() {

		//console.log($(this).attr("val"));
		
		$(this).parent().parent().children('a').text($(this).text());
		$(this).parent().parent().children('input').attr('value',$(this).attr("val"));
		$(data).hide();
	    });
	});
    });
}

$(document).ready(function () {
	$("div.dateList ul.eventsList li.event:odd").css({
		"background-color": "#fff"
	});
	$("ul.rightList").children("li:odd").css({
		"background-color": "#fff"
	});
	
    $(document).click(function() {
		$('span.dropdown ul').hide();
		$("div.input-select-box ul").hide();
    });    
    init_search_bar();
});

$(window).load(function () {
	create_dropdowns();
});




function init_search_bar() {
	
    $("span.textbox-toggle").each(function() {
		$(this).children("input").hide();
	        
		$(this).children("a").click(function() {
		    $(this).parent().children("input").show();
		    $(this).parent().children("input").focus();
		    $(this).parent().children("input").blur(function() {
		    	$(this).hide();
		    	$(this).parent().children("a").show();
	                
		    	
		    	if ($(this).val()!='') {
			    	if ($(this).parent().children("a").children("span")) {
			    	    $(this).parent().children("a").children("span").html($(this).val());
			    	} else {
			    	    $(this).parent().children("a").html($(this).val());
			    	}
		    	}
		    });
		    $(this).hide();
		});
    });
    
    $("div#searchBox input#query").click( function() {
        if ($(this).val()=='Search by artist, venue or event name')  $(this).val('');
    });
    
    $("div#searchBox input#query").blur( function() {
    	if ($(this).val()=='')  $(this).val('Search by artist, venue or event name');
    });
    
    $("#searchButton").click(function(){
    	if ($("div#searchBox input#query").val()=='Search by artist, venue or event name')
    		return false;
    });
    
    $("#search_box_holder").fadeIn(1000);
    
    $("div.input-select-box").each(function() { 
        
        // Create Selectors
        selectbox = $(this);
        selectinput =  $(this).children('input');
        selectlist =  $(this).children('ul');
        
        // Hide List
        selectlist.hide();
        
        // Get Selected Values
        name = selectlist.children(':first').text();
        value = selectlist.children(':first').attr('value');
        
        
        // Create Selected Item
        selectbox.prepend('<div>'+name+'</div>');
        selectdiv = $(this).children('div');
        
        //console.log(selectbox);
        if (selectlist.css('width')) {
            divwidth = parseInt(selectlist.css('width'));
        } else {
            divwidth = 150;
        }
        selectdiv.width(divwidth);
        
        // Position Selected Item
        selected_item_left = selectinput.width()-divwidth+41;
        selectdiv.attr('style','margin-left: '+selected_item_left+'px;');
        
        // Adjust the Width of the input box
        //selectinput.width(selectinput.width() + selectdiv.width());
        
        // Controls
        selectlist.children().click(function() {
            $('#search_for').val($(this).attr("val"));
            selectdiv.text($(this).text());
            selectlist.hide();
        });
        
        selectdiv.click(function() {
            selectlist.slideToggle(200);
            //selectlist.width(selectdiv.width()+22);
            selectlist.css('left', selected_item_left+divwidth-23);
            

            selectlist.css('top', selectdiv);
        });
    }); 
    
    $("#geo_set_button").click(function() {
        set_location();
    });
    $("#geo_reset_button").click(function() {
        reset_location();
    });
    
}	

function set_location() {
    $.post('/location/set/', {location: $('#geo_location').val(), distance: $('#geo_distance').val()},
           function(data) {         
               // XXX This should only reload the content section. Need some
               // repeatable way to do this. See the filters in content.html.
               window.location.reload();
           });
}

function reset_location() {
    $.post('/location/reset/', {},
           function(data) {
               $('#geo_location').val('');
               // XXX This should only reload the content section. Need some
               // repeatable way to do this. See the filters in content.html.
               window.location.reload();
           });
}
