var $j = jQuery.noConflict();
var map = null;
var geocoder = null;
var base_dir = '/';
var markers = [];
var baseIcon;


function loadMap( container , x, y ) {
  if (GBrowserIsCompatible()) {
	var x = (x) ? x : -75.698547;
	var y = (y) ? y : 45.425444;
	showMap( container , x, y );
	
	GEvent.addListener(map, "dragend", function() { loadCinemas() });
	GEvent.addListener(map, "zoomend", function() { loadCinemas() });
	$j(window).unload( function () { GUnload(); } );
	loadCinemas();
  }
}

function ExtendShowtimes() {
	$('showtimes-times').observe('mousemove', function(event) {
		var element = event.element();
		var pos = element.cumulativeOffset();
		
		if(element.hasClassName('cnamejs')) {

			if($('cnamejs')){
				$('cnamejs').update(element.innerHTML);
				$('cnamejs').show();
				$('cnamejs').style.top = pos.top + 'px';
				$('cnamejs').style.left = pos.left + 'px';
			} else {
				var cname = new Element('div', { "id" : "cnamejs", "class" : 'cinemas cnamejs', 
					'style': 'padding: 2px 0; font-size:80%; background: #ffffff; position: absolute; top: '+pos.top+'px; left: '+pos.left+'px' } )
					.update(element.innerHTML).observe('mousemove', function(event) {$('cnamejs').show();});
				$$('body').first().appendChild(cname);
			}
			
		} else {
			if($('cnamejs'))
				$('cnamejs').hide();
			if(element.hasClassName('movie-line')) {
				
				if($('float-time')){
					$('float-time').update(element.title);
					$('float-time').show();
					$('float-time').style.top = (pos.top - 40) + 'px';
					$('float-time').style.left = (pos.left - 29) + 'px';
				} else {
					var cname = new Element('div', { "id" : "float-time", 
					'style': 'position: absolute; top: '+(pos.top - 40)+'px; left: '+(pos.left - 29)+'px' } )
					.update(element.innerHTML);
					$$('body').first().appendChild(cname);
				}
		
			} else if($('float-time')){
				$('float-time').hide();
			}
		}
		
		
		
	});
	$('showtimes-times').observe('mouseout', function(event) {
		if($('cnamejs')) $('cnamejs').hide(); 
	});
}

var cityList = {
	
	init : function (container, x, y, data) {
		//this.per_page = (data.perPage) ? data.perPage : 10;
		//this.total_pages = (data.total) ? data.total : ( Math.ceil( data.items.length / this.per_page ));
		this.map(container, x, y, data);
	},	
	map : function (container, x, y, data){
		var self = this;
		if (GBrowserIsCompatible()) {
			var x = (x) ? x : -75.698547;
			var y = (y) ? y : 45.425444;
			showMap( container , x, y );
			$j(window).unload( function () { GUnload(); } );
			var citems = $$('#result-container-main .iconer');
			$j.each(data, function(i,item){ 
				
				var markerText = '<div class="showtimes-window"><b>'+item.name+'</b><br />'+item.address+'<br />'+item.phone+ '<div id="showtimes" style="height: 150px;"></div></div>';
				var marker = getCityMarker(item, i, markerText); 
				$(citems[i]).observe('click', function(){
					marker.openInfoWindowHtml(markerText);
					//pageTracker._trackPageview('/ajax/marker/' + item.id);
					//getShowtimesByTheater(item.id);
				});
				map.addOverlay(marker);
			});
		}
	},
	rearrange_results : function(){
		var s = new Element('ol', {'class':'sresult th line'});
		$('result-container').insert(s);
		$$('#result-container-main li').each(function (item, index){
			$(s).insert(item);
			if(index > 5) throw $break;
		});
	}
	
	
	
};
function getCityMarker( item, index, text ) {
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	return createMarker(
		item.id, 
		new GLatLng(item.coordinate_y, item.coordinate_x), 
		text, item.name, letter);
}

function loadCityMap( container , x, y, data ) {
  if (GBrowserIsCompatible()) {
	var x = (x) ? x : -75.698547;
	var y = (y) ? y : 45.425444;
	showMap( container , x, y );

	$j(window).unload( function () { GUnload(); } );

	//var marker = createBasicMarker(new GLatLng(y, x));
	//map.addOverlay(marker);
	$j.each(data, function(i,item){ 
		addCityMarker(item, i); 
	});
  }
}



function loadMoviesMap( container , x, y, tmp_data) {
  if (GBrowserIsCompatible()) {
	var x = (x) ? x : -75.698547;
	var y = (y) ? y : 45.425444;
	showMap( container , x, y );
	
	//GEvent.addListener(map, "dragend", function() { loadShowtimesByMovie() });
	//GEvent.addListener(map, "zoomend", function() { loadShowtimesByMovie() });
	$j(window).unload( function () { GUnload(); } );
	//loadShowtimesByMovie();
	var tmp_data = (tmp_data) ? tmp_data : null;
	reloadMovieShowtimes(tmp_data);
  }
}

function reloadMovieShowtimes(tmp_data){
	var tmp_data = (tmp_data) ? tmp_data : $('cboCity').options[$('cboCity').selectedIndex].value;
	if(tmp_data == 0) return;
	var adata = tmp_data.split('|');
	loadShowtimesByMovie(adata[0]);
	map.setCenter(new GLatLng(adata[2], adata[1]));
}

function loadTheaterMap( container , x, y ) {
  if (GBrowserIsCompatible()) {
	var x = (x) ? x : -75.698547;
	var y = (y) ? y : 45.425444;
	showBasicMap( container , x, y );

	$j(window).unload( function () { GUnload(); } );

	var marker = createBasicMarker(new GLatLng(y, x));
	map.addOverlay(marker);
	
  }
}

function showBasicMap( container , x, y ){
	var x = (x) ? x : -75.698547;
	var y = (y) ? y : 45.425444;
	var mapTypes = G_DEFAULT_MAP_TYPES;
	for(var i = 0; i < mapTypes.length; i++){
		mapTypes[i].getMaximumResolution = function(latlng){ return 19;};
		mapTypes[i].getMinimumResolution = function(latlng){ return 12;};
	}
	map = new GMap2(document.getElementById( container ), {mapTypes: mapTypes});
	map.setCenter(new GLatLng(y, x), 13);
	map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
	geocoder = new GClientGeocoder();
	
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.goodmovies.ca/public/images/icons/shadow.png";
	baseIcon.iconSize = new GSize(24, 30);
	baseIcon.shadowSize = new GSize(48, 33);
	baseIcon.iconAnchor = new GPoint(9, 33);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
}


function createBasicMarker(point) {
	
	var showmore = (showmore) ? showmore : false;
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "http://www.goodmovies.ca/public/images/icons/icon.png";
	var opts = { icon:letteredIcon };
	var marker = new GMarker(point, opts);	
	return marker;
}




function showMap( container , x, y ){
	var x = (x) ? x : -75.698547;
	var y = (y) ? y : 45.425444;
	var mapTypes = G_DEFAULT_MAP_TYPES;
	for(var i = 0; i < mapTypes.length; i++){
		mapTypes[i].getMaximumResolution = function(latlng){ return 19;};
		mapTypes[i].getMinimumResolution = function(latlng){ return 12;};
	}
	map = new GMap2(document.getElementById( container ), {mapTypes: mapTypes});
	map.setCenter(new GLatLng(y, x), 13);
	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
	geocoder = new GClientGeocoder();
	
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.goodmovies.ca/public/images/icons/shadow.png";
	baseIcon.iconSize = new GSize(24, 30);
	baseIcon.shadowSize = new GSize(48, 33);
	baseIcon.iconAnchor = new GPoint(9, 33);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
}



var dTimer=null;
var mTimer=null;
function setMenus(){
	$j('div.box-search').bind("mouseenter mouseleave", function(e){
			$j(this).toggleClass("lr-over");
    });
	
	$('btn-city').observe('mousemove', function(event){
		window.clearTimeout(dTimer);
		$('city-list').show();
		$('btn-city').addClassName('menu-button-hover');
	});
	$('btn-city').observe('mouseout', function(event){
		dTimer = setTimeout("$('city-list').hide();$('btn-city').removeClassName('menu-button-hover');",500);
	});
	$('city-list').observe('mousemove', function(event){
		window.clearTimeout(dTimer);
		$('city-list').show();
		$('btn-city').addClassName('menu-button-hover');
	});
	$('city-list').observe('mouseout', function(event){
		dTimer = setTimeout("$('city-list').hide();$('btn-city').removeClassName('menu-button-hover');",500);
		//$('city-list').hide();
		//$('btn-city').removeClassName('menu-button-hover');
	});
	
	$('btn-movie').observe('mousemove', function(event){
		window.clearTimeout(mTimer);
		$('movies-list').show();
		$('btn-movie').addClassName('menu-button-hover');
	});
	$('btn-movie').observe('mouseout', function(event){
		mTimer = setTimeout("$('movies-list').hide();$('btn-movie').removeClassName('menu-button-hover');",500);
	});
	$('movies-list').observe('mousemove', function(event){
		window.clearTimeout(mTimer);
		$('movies-list').show();
		$('btn-movie').addClassName('menu-button-hover');
	});
	$('movies-list').observe('mouseout', function(event){
		mTimer = setTimeout("$('movies-list').hide();$('btn-movie').removeClassName('menu-button-hover');",500);
		//$('movies-list').hide();
		//$('btn-movie').removeClassName('menu-button-hover');
	});
}
/*
$j(document).ready( function(event) {
	$j('div.box-search').bind("mouseenter mouseleave", function(e){
			$j(this).toggleClass("lr-over");
    });
	
	$('btn-city').observe('mousemove', function(event){
		window.clearTimeout(dTimer);
		$('city-list').show();
		$('btn-city').addClassName('menu-button-hover');
	});
	$('btn-city').observe('mouseout', function(event){
		dTimer = setTimeout("$('city-list').hide();$('btn-city').removeClassName('menu-button-hover');",500);
	});
	$('city-list').observe('mousemove', function(event){
		window.clearTimeout(dTimer);
		$('city-list').show();
		$('btn-city').addClassName('menu-button-hover');
	});
	$('city-list').observe('mouseout', function(event){
		dTimer = setTimeout("$('city-list').hide();$('btn-city').removeClassName('menu-button-hover');",500);
		//$('city-list').hide();
		//$('btn-city').removeClassName('menu-button-hover');
	});
	
	$('btn-movie').observe('mousemove', function(event){
		window.clearTimeout(mTimer);
		$('movies-list').show();
		$('btn-movie').addClassName('menu-button-hover');
	});
	$('btn-movie').observe('mouseout', function(event){
		mTimer = setTimeout("$('movies-list').hide();$('btn-movie').removeClassName('menu-button-hover');",500);
	});
	$('movies-list').observe('mousemove', function(event){
		window.clearTimeout(mTimer);
		$('movies-list').show();
		$('btn-movie').addClassName('menu-button-hover');
	});
	$('movies-list').observe('mouseout', function(event){
		mTimer = setTimeout("$('movies-list').hide();$('btn-movie').removeClassName('menu-button-hover');",500);
		//$('movies-list').hide();
		//$('btn-movie').removeClassName('menu-button-hover');
	});
});
*/



function loadCinemas(){
	/*if(map.getZoom() < 13){
		$j('#map-info').text("Zoom in to see more theaters");
		return false;
	}*/
	$j('#map-info').text("");
	var bnds = map.getBounds()
	var s = bnds.getSouthWest();
	var e = bnds.getNorthEast();
	var x1 = s.lng();
	var x2 = e.lng();
	var y1 = s.lat();
	var y2 = e.lat();
	var thHtml = '';
	
	$j.getJSON(base_dir + "ajax/cinemas", {"x1" : x1,"x2" : x2,"y1" : y1,"y2" : y2}, function(data){
			map.clearOverlays();
			$('theater-list').update('');
			$j.each(data, function(i,item){ addHomeMarker(item, i); });
	});
}


function getShowtimesByTheater(theater){
	$j.get(base_dir + "ajax/showtimes", {"id" : theater}, function(data){
		pageTracker._trackPageview('/ajax/showtimes/' + theater);
		$('showtimes').update(data);
	});
}

function loadShowtimesByMovie(city){
	var thHtml = '';
	$j.getJSON(base_dir + "ajax/movieshowtimesbycity", {"city" : city, "id":movie_id}, function(data){
			pageTracker._trackPageview('/ajax/movieshowtimesbycity/' + city + '/' + movie_id);
			map.clearOverlays();
			$('showtimes-times').update(data.html_data);
			$j.each(data.map_data, function(i,item){ addMovieMarker(item, i); });
	});
}

function addMovieMarker( item, index ) {
	var letter = String.fromCharCode("A".charCodeAt(0) + index);

	//var markerText = '<div class="showtimes-window"><b>'+item.name+'</b><br />'+item.address+'<br />'+item.phone+ '<div id="showtimes"></div></div>';
	var markerText = '<div class="showtimes-window"><b>'+item.name+'</b><br />'+item.address+'<br />'+item.phone+ '</div>';
	var marker = createMarker(item.id, 
						new GLatLng(item.coordinate_y, item.coordinate_x),
						markerText,
						item.name, letter, true);
						
	$$('#cinema-row-'+item.id+' span').first().insert(new Element('span', {"class" : "iconer"}).observe('click', function(){
			pageTracker._trackPageview('/ajax/marker/' + item.id);
			marker.openInfoWindowHtml(markerText);
		}).update(letter));
	map.addOverlay(marker);
	
}

function addHomeMarker( item, index ) {
	var letter = String.fromCharCode("A".charCodeAt(0) + index);

	var markerText = '<div class="showtimes-window"><b>'+item.name+'</b><br />'+item.address+'<br />'+item.phone+ '<div id="showtimes"></div></div>';
	var marker = createMarker(item.id, 
						new GLatLng(item.coordinate_y, item.coordinate_x),
						markerText,
						item.name, letter);
	var z = new Element('li');
	
	$(z).insert(new Element('img', { "src" : base_dir + 'public/images/icons/icon'+letter+'.png' } ).observe('click', function(){
			marker.openInfoWindowHtml(markerText);
			pageTracker._trackPageview('/ajax/marker/' + item.id);
			//getShowtimesByTheater(item.id);
		}),  { position: 'after' } ).insert(new Element('span').update('<a href="'+base_dir+'theaters/'+item.url+'">'+item.name+'</a>'));
	
	$('theater-list').insert(z);
	map.addOverlay(marker);
}


function createMarker(id, point, text, mtitle, index, showmore) {
	
	var showmore = (showmore) ? showmore : false;
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "http://www.goodmovies.ca/public/images/icons/icon" + index + ".png";

	var opts = { icon:letteredIcon, title: mtitle };
	var marker = new GMarker(point, opts);
	if(!showmore){
		GEvent.addListener(marker, "infowindowopen", function() {
			getShowtimesByTheater(id);
		});
	}
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(text);
		//getShowtimesByTheater(id);
	});
	GEvent.addListener(marker, "mouseover", function() {
		$('map-info').update(mtitle).show();
	});
	GEvent.addListener(marker, "mouseout", function() {
		$('map-info').update("").hide();
	});
	
	return marker;
}




function ToggleDescription() {
	var limit;
	limit = 615;
	var des = $('movie-description').down('p');
	if(des.innerHTML.length > limit) {
		var desFull = des.innerHTML;
		var desTrunc = des.innerHTML.truncate(limit, '&nbsp;...');
		des.innerHTML = desTrunc;
		$('toggle').observe('click', function(e) {
			Event.stop(e);
			//pageTracker._trackPageview('/ajax/marker/' + item.id);
			if(des.hasClassName('expanded')) {
				des.innerHTML = desTrunc;
				des.removeClassName('expanded');
				$('toggle').down('a').innerHTML = 'View more';
			} else {
				des.innerHTML = desFull;
				var fullHeight = des.getHeight()/12;
				$('toggle').down('a').innerHTML = 'View less';
				des.addClassName('expanded');
			}
		});
	} else if($('toggle')) {
		$('toggle').style.display='none';
	}
};





function checkURL() {
	var items = parseUri(document.location.href);
	if(items.anchor.match(/center_big\?/)){
		//var tmp = items.anchor.split('?');
		var new_loc = document.location.href.replace('#center_big', '');
		ajax_page(new_loc);
	}
}

function getURL(include_query){
	if(!include_query){
		var dl = document.location.href.split("?");
		return dl[0];
	} else
		return document.location;
}

/*
	parseUri 1.2.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};