var map = null;		// Storing the map obj
var bounds = null;	// Storing the bounds object



(function($){

	// Set up default locations
	if (window.location.search == '') {
		var locations = {'0': {
			'id':'41',
			'name':'Village Roadshow Studios Watertank',
			'distance':'',
			'latitude':'-27.91456',
			'longitude':'153.31936',
			'image':'/uploads/2011/02/thumb/Warner Roadshow Studios Water Tank - Jpeg file.jpg'
		},'1': {
			'id':'113',
			'name':'Fox Studios',
			'distance':'',
			'latitude':'-33.98147',
			'longitude':'151.22348',
			'image':''
		},'2': {
			'id':'115',
			'name':'Docklands Studios Melbourne',
			'distance':'',
			'latitude':'-37.81466',
			'longitude':'144.93696',
			'image':''
		}};
		var currentInfoWindow = null;
		var htmlPopup = '<div id="markerPopup">		<h4 class="locationTitle">__LOCATION_TITLE__</h4>	<img class="locationPopupImage" src="__IMG_SRC__" />	<a href="AusFilm/locations/location-details/?loc=__LOCATION_ID__">Find out more &raquo;</a>		</div>';

		$(document).ready(function() 
		{
			
			if ($('#map_canvas').length > 0) {
				for (var i in locations) {
					// Create new marker on the map
					var marker = createMarker(locations[i], '', htmlPopup);
					locations[i]['marker'] = marker;
				}//end for
				if (locations[1] == null) {
					var newCenter = new GLatLng(locations[i].latitude, locations[i].longitude);
					map.setCenter(newCenter, 4);
				} else {
					// Set Center and Zoom Level based on the returned list of locations.
					map.setZoom(map.getBoundsZoomLevel(bounds));
					map.setCenter(bounds.getCenter());
				}
			}
		});
	}

	$(document).ready(function() 
	{
		if ($("#location-search").length > 0) 
		{
			$("#location-search .states .selectedTxt").tooltip({content:'Select a State or Territory from the dropdown', 'fixed':true, css:{'width':'190px'}})
			$("#location-search .environment .selectedTxt").tooltip({content:'Select an environment type from the dropdown', 'fixed':true, css:{'width':'190px'}})
			$("#location-search .prod-credit .selectedTxt").tooltip({content:'Select the movie credit from the dropdown to  see the locations featured', 'fixed':true, css:{'width':'190px'}})
	
			$('form select:eq(0)').change(function(){
				if ($(this).val() != "0") {
				    $('form select:eq(1)').getSetSSValue('0');
				    $('form select:eq(2)').getSetSSValue('0');
				}
			});
			
			$('form select:eq(1)').change(function(){
				if ($(this).val() != "0") {
				    $('form select:eq(0)').getSetSSValue('0');
				    $('form select:eq(2)').getSetSSValue('0');
				}
			});
			
			$('form select:eq(2)').change(function(){
				if ($(this).val() != "0") {
				    $('form select:eq(0)').getSetSSValue('0');
				    $('form select:eq(1)').getSetSSValue('0');
			    }
			});
			
	
	
		}
	});


	/* set page background */
	function contentBg() {
		var contentHeight = $(window).height(),
			contentWidth = $('#container').width();
		$('#bg').height(contentHeight);
		$('#bg > img')
			.height(contentHeight)
			.width(contentWidth)
			.fadeIn(2000);
	}
	$(window).bind("load resize", contentBg);

	/* locations map */
	var mapCanvasEle = document.getElementById("map_canvas");
	if (mapCanvasEle !== null && mapCanvasEle !== undefined) {
		var centerLatitude = '-26.363882';
		var centerLongitude = '135.044922';
		map = new GMap2(document.getElementById("map_canvas"));
		//retrieveMarkers();
		var location = new GLatLng(centerLatitude, centerLongitude);
		map.setCenter(location, 4);
		map.addControl(new GSmallMapControl());

		// Start with an empty GLatLngBounds object
		bounds = new GLatLngBounds();
	}//end if


	/* display label inside input field */
	$('#navigation label, #enter-keywords label').inFieldLabels();

	/* navigation hover for ie6 */
	var currentNav = $('#navigation ul li.current:first');
	$('#navigation ul li').hover(function(){
		$(this).addClass('drop');
		currentNav.removeClass('current');
	}, function(){
		$(this).removeClass('drop');
		currentNav.addClass('current');
	});

    /* apply Cufon to selected elements */
    cufonize('#navigation ul li a', { hover: true });
    cufonize('#navigation ul li ul li a', { hover: true });
    cufonize('#navigation label', { fontSize : "14px" });

	/* homepage slide show */
	$(".slide").hide();
	$("#slides > div:first").addClass("active").show();
	$(".tab_content:first").show();
	$("#slide-controller li > a").click(function() {
		$("#slide-controller li > a").removeClass("current");
		$(this).addClass("current");
		$(".slide").hide();
		var activeTab = $(this).attr("href");
		$(activeTab).fadeIn();
		return false;
	});

	/* co-productions & co-ventures: slides to SAC test content and toggle it */
	 $('a[href$="#sac"]').click(function(){
	 	$('html,body').animate({scrollTop: $('#sac').offset().top},'slow');
	 	$('#sac').toggleClass('current').next('div').slideToggle();
	 	return false;
	 });

	/* accordion content */
	$('#body h4.subhdr').click(function(){
		$(this).toggleClass('current');
		$(this).next('div').slideToggle();
	});

	/* table styling */
	$('#body th:first').css('border-left','1px solid #d8ddcf');
	$('#body th:last').css('border-right','1px solid #d8ddcf');

	/* form styling */
	$('#states').sSelect({
		defaultText: 'States',
		containerClass: 'states'
	});
	$('#categories').sSelect({
		defaultText: 'Categories',
		containerClass: 'categories'
	});
	$('#environment').sSelect({
		defaultText: 'Environment',
		containerClass: 'environment'
	});
	$('#prod-credit').sSelect({
		defaultText: 'Production Credit',
		containerClass: 'prod-credit',
		ddMaxHeight: '230px'
	});

	/* member directory search */
	$('#refine').hide();
	$('#refine-search').click(function(){
		$('#refine').slideToggle();
	});
	/* refresh search results based on category change */
	$('#categories').change(function(){
		var category = $('#categories option:selected');
		$('#directory-search').submit();
	});
	/* refresh search results based on state change */
	$('#states').change(function(){
		var state = $('#states option:selected');
		$('#directory-search').submit();
	});
	/* show refine search after first search is displayed */
	var url = window.location.href;
	if (url.indexOf("state") >= 0) {
		$('#refine').show();
	}

	/* hero image slide show */
	$('#imageSlide').cycle({
		delay: 2000
	});
	
	$("ul#news-archive h2, ul#news-articles h2").click(function() { 
	    $('ul',$(this).parents("li")).toggle()
	});
	
	$("a.showonmap").click(function(e) { 
		//map.setZoom(5); // zoom map a little bit
		$(window).scrollTop(100);
	})
	


	
	
})(window.jQuery);


/**
 * This function plot individual marker on the map and give them info window
 */
function createMarker(locationInfo, iconUrl, htmlPopup) {
	latitude = locationInfo.latitude;
	longitude = locationInfo.longitude;
	if (iconUrl != '' && iconUrl != null) {
			var iconWidth = 52;
			var iconHeight = 39;
			var icon = new GIcon();
			icon.image = iconUrl;
			icon.iconSize = new GSize(iconWidth, iconHeight);
			icon.iconAnchor  = new GPoint(iconWidth/2, 25);
			icon.infoWindowAnchor = new GPoint(iconWidth/2, 14);
			var point	= new GLatLng(latitude, longitude);
			var marker      = new GMarker(point, icon);
	} else {
			var point	= new GLatLng(latitude, longitude);
			var marker  = new GMarker(point);
	}//end else
	bounds.extend(point);

	if (htmlPopup != '') {
		GEvent.addListener(marker, 'click',
		  function () {
			//map.showMapBlowup(new GLatLng(latitude, longitude), 5, G_HYBRID_MAP);
			current_marker = marker;
			htmlPopup = replaceHtmlPopupContent(locationInfo, htmlPopup);
			marker.openInfoWindowHtml(htmlPopup);
		  }//end function
		)//end addListener
	}//end if

	map.addOverlay(marker);
	return marker;
}

/**
 * This function take a HTML template of the popup windows and fill in the content
 */
function replaceHtmlPopupContent(locationInfo, htmlContent)
{
	htmlContent = htmlContent.replace('__LOCATION_ID__', locationInfo.id);
	htmlContent = htmlContent.replace('__IMG_SRC__', locationInfo.image);
	htmlContent = htmlContent.replace('__LOCATION_TITLE__', locationInfo.name);
	// Replace more content here if it is needed
	return htmlContent;

}//end replaceHtmlPopupContent()

/**
 * This function give any a href link the ability to bring up popup window for the related marker
 */
function focusOnMarker(locations, locationId, htmlPopup)
{
	if (currentInfoWindow !== null) {
		currentInfoWindow.close();
	}

	htmlPopup = replaceHtmlPopupContent(locations[locationId], htmlPopup);
	locations[locationId].marker.openInfoWindowHtml(htmlPopup);

}//end focusOnMarker()




/* trim extra whitespaces in Cuf�n text */
function cufonize(selector, opts) {
    $(selector).each( function() {
           var elem = $(this);
           var text = $.trim(elem.text())
           elem.text(text);

    });
    Cufon.replace(selector, opts);
}


window.log = function(){
  log.history = log.history || [];
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

(function(doc){
  var write = doc.write;
  doc.write = function(q){
    log('document.write(): ',arguments);
    if (/jquery-\d\.\d\.\d(\.min)?\.js/.test(q)) write.apply(doc,arguments);
  };
})(document);

/* TOOL TIP*/
jQuery.fn.extend({
	tooltip: function(settings)
	{
		if (typeof settings == "undefined") {
			return;
		}
		
		var markup = $('<div class="tooltip tooltip_'+((settings.position == "bottom") ? 'bottom': 'top')+'"><div class="tooltip_wrapper">'+settings.content+'</div></div>');
		
		// reset standard css properties  	
		css = {'position':'absolute', 'left':0,'top':0, 'display':'none'};
		if (typeof settings.css != "undefinded") {
			for (prop in settings.css) {
				$(markup).css(prop,settings.css[prop]);
			}
		}
		
		$("body").append(markup);

		if (settings.fixed === true) 
		{
			$(this).mouseover(function(e) {
			
				$(markup).show();
				
				if (settings.position == "bottom") {
					$(markup).css("top",$(this).offset().top+20);
				} else {
					$(markup).css("top",$(this).offset().top-$(markup).height()-10);
				}
				
				var left = (($(markup).width() > $(this).width()) ? $(this).offset().left-$(markup).width()/2+$(this).width()/2 : $(this).offset().left);
				
				$(markup).css("left",left+5);
			
			});
		} else {
			$(this).mousemove(function(e) {
			
				$(markup).show();
			
				if (settings.position == "bottom") {
					$(markup).css("top",e.pageY+20);
				} else {
					$(markup).css("top",e.pageY-$(markup).height()-20);
				}
			
				$(markup).css("left",e.pageX-$(markup).width()/2);
			});
		}  	
		
		$(this).mouseout(function(e) {
			$(markup).hide();
		});
		
		$(this).click(function(e) {
			$(markup).hide();
		});
	
	
	}
});
