 jQuery.noConflict();

	var allLocations = '';
	if(ALL_LOCATIONS){
		allLocations = '&all=true';
	}

function loadSafariStyles(){
	if(jQuery.browser.safari){
		//#header .beta

		//#header .alpha
		jQuery('#header .alpha').css({
			'width':'710px'
		});
		
		var currentLeft = parseInt(jQuery('#header .alpha span.current').css('left'));
		currentLeft += 40;
		var target = currentLeft+"px";
		
		//CURRENT Bird
		jQuery('#header .alpha span.current').css('left',target);
		
		
		//.billboard p
		jQuery('.billboard p').css({
			'margin': '0 0 0 -20px'
		});
		
		
		
	}
}jQuery(document).ready(loadSafariStyles);

function submitContactForm(){
		jQuery('#generalContactForm').submit(sendFormData);
}
jQuery(document).ready(submitContactForm);

function sendFormData(eventObj){
//	console.log(eventObj);
	var data = jQuery('#generalContactForm').serialize();
	var url = "../../sendMessage.php";
	jQuery('#errorMsg').html("<img src='/resources/images/backgrounds/loading.gif' />");
	jQuery.post(url, data, handleResponseesponse, "json");
	return false
}
function handleResponse(obj){
	if(!obj.succeed){
		jQuery('#errorMsg').html('There was an error while trying to send the email. All fields are required and you must enter a valid email address. Thank you.')
	}
	else{
		jQuery('#errorMsg').html('<h2>Message Sent... Thank You!!!</h2>');
		jQuery('#generalContactForm').html('');
		
	}
}


var icons = {};
var allmarkers = [];
var map;
var mgr = {};
var geoEncoder = {};
function getOfficeLayer(){
	var url = "../getLocations.php";
	jQuery.post(url,"",function(json){
		officeLayer = eval(json);
		loadMap();
	},"text");
	
}//jQuery(document).ready(getOfficeLayer);

function loadMap(){
	var city = jQuery('#city').val();
	var state = jQuery('#state').val();
	
  if(typeof GBrowserIsCompatible != "undefined" && document.getElementById('mapContainer')){
	  if (GBrowserIsCompatible()) {
	    map = new GMap2(document.getElementById('mapContainer'));

	    /*  GEO-Encoder  */
	    var startingPoint = null;
	    geoEncoder = new GClientGeocoder();
	  	geoEncoder.getLatLng('Idaho',function(point){
	  		startingPoint = point;
	  		map.setCenter(startingPoint, 5);
	  		map.addControl(new GLargeMapControl());
		    map.addControl(new GOverviewMapControl());
	    
		    /* CREATE MARKER MANAGER OBJECT */
		    var mgrOptions = { borderPadding: 50, maxZoom: 15};
		    mgr = new MarkerManager(map);
		    setupOfficeMarkers();
	  	});
	  }		
		if (jQuery('#locationSearch').length >=1) {
			var form = jQuery('#locationSearch');
			form.submit(searchForLocations);
			
			if(city || state){
				var form = jQuery('#locationSearch');
				form.submit();
			}
			else if(window.location.hash){
				var qString = window.location.hash;
				newCity = qString.split('#city=')[1].split('&')[0];
				newCity = newCity.replace('+',' ');
				
				jQuery('#city').val(newCity);
				
				newState = qString.split('&state=')[1].split('&')[0];
				jQuery('#state').val(newState);

				locationNumber = qString.split('&location=')[1];
				jQuery('#locationNumber').val(locationNumber);
				
				form.submit();
			}
			
			
		}
		
	}
}jQuery(document).ready(loadMap);

function loadDetailMap(){
	if (jQuery('#detailMap').length >=1 && GBrowserIsCompatible()) {
		 map = new GMap2(document.getElementById('detailMap'));
	    /*  GEO-Encoder  */
	    var startingPoint = null;
	    geoEncoder = new GClientGeocoder();
	 	var startingPoint = new GLatLng(detailLat, detailLon);
  		map.setCenter(startingPoint, 14);
  		map.addControl(new GLargeMapControl());
	    map.addControl(new GOverviewMapControl());

	    /* CREATE MARKER MANAGER OBJECT */
	    var mgrOptions = { borderPadding: 50, maxZoom: 15};
	    mgr = new MarkerManager(map);
	    setupOfficeMarkers();


		// if (jQuery('#locationSearch').length >=1) {
		// 	var form = jQuery('#locationSearch');
		// 	form.submit(searchForLocations);
		// }

	
	}
}jQuery(document).ready(loadDetailMap);

function setupOfficeMarkers() {
  allmarkers.length = 0;
  for (var i in officeLayer) {
    var layer = officeLayer[i];
    var markers = [];
    for (var j in layer["places"]) {
      var place = layer["places"][j];
	  var icon = getIcon(place["icon"]);
//	if(icon) console.log(icon);
      var title = place["name"];
      var size = place["size"];
      var address = place["address"];
      var posn = new GLatLng(place["posn"][0], place["posn"][1]);
      var marker = createMarker(posn,title,icon,size,address); 
      markers.push(marker);
      allmarkers.push(marker);
    }
    mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
  }
  mgr.refresh();
  
}

function getIcon(images) {
	var icon = null;
     if (images) {
       if (icons[images[0]]) {
         icon = icons[images[0]];
       } else {
         icon = new GIcon();
         icon.image = "/resources/images/" + images[0] + ".png";
         var size = iconData[images[0]];
         icon.iconSize = new GSize(size.width, size.height);
         icon.iconAnchor = new GPoint(size.width >> 1, size.height >> 1);
         icon.shadow = "";
         size = iconData[images[1]];
         icon.shadowSize = new GSize(size.width, size.height);
         icons[images[0]] = icon;
       }
     }
	return icon;
}

function createMarker(posn, title, icon, size, address) {
//	if(icon) console.log(icon);
  	var marker = new GMarker(posn, {title: title, icon: icon});

  GEvent.addListener(marker, "click", function(marker) {
  		var zoom = map.getZoom();
  		if(zoom <= 5){
	  		map.setCenter(posn, 7);
  		}
  		else if(zoom > 5 && zoom < 9){
  			map.setCenter(posn,9);
  		}
  		else{
  			//console.log(address);
  			map.panTo(posn);
//			console.log(escape(title));

  			map.openInfoWindowHtml(posn,"<br /><p>"+title+"-"+address+"<br /> <a href='./location?location="+escape(title)+allLocations+"'>View Details</a></p>");
  			//console.log(marker);
//  			console.log(window.location);
  			//window.location = window.location+"location?location="+title;
  		}
	});
  return marker;
}

if (typeof console == "undefined") {
	console = {}
	console.log = function(obj){}
};


function currentNav(){
	var button = jQuery('#header a.current');
	var bird = jQuery('#header span.current');
//	console.log(button, bird);
}jQuery(document).ready(currentNav);


function loadingFile () {
	if(jQuery('#fileUpload').length >=1){
		jQuery('#fileUpload').submit(function(){
			jQuery('#loadingForm').css('display','block');
		});
	}
}jQuery(document).ready(loadingFile)

function searchForLocations(eventObj){
	var data = jQuery('#locationSearch').serialize();
	var url = "../../queryLocations.php";
	if(ALL_LOCATIONS){
		url+="?all=true";
	}
	location.hash = data;
	jQuery('#results').html("<img src='/resources/images/backgrounds/loading.gif' />");
	jQuery.post(url, data, showSearchResults, "json");
	return false
}

function showSearchResults(respObj) {
	var resultsContainer = jQuery('#results');
	
	var city = jQuery('#city').val();
	var state = jQuery('#state').val();
	
	if(state !=""){
		var searchTerm = city + ", "+ state;
	}
	else if(city != ""){
		searchTerm = city
	}
	else if(city == "" && state == ""){
		searchTerm = "Idaho";
	}
	
	
	if(respObj.locations.length > 0){
		
		var results = "<h2>Results:</h2><ul sytle='list-style: none;'>";
		jQuery(respObj.locations).each(function (index,location) {
			var locationNumber = "";
			var address = "";
			var lat = "";
			var lon = "";
			
			for(name in location){
				var key = "location."+name;
				var value = eval(key);
				
				if(name == "locationNumber") locationNumber = value;
				if(name == 'address') address = value;
				if(name == 'lat') lat = value;
				if(name == 'lon') lon = value;
				
				if(index==0){
					var clickedLocation = new GLatLng(lat, lon);
			  		map.setCenter(clickedLocation, 8);
				}
			}
			if(locationNumber != "undefined"){
				if(jQuery.browser.msie && index < respObj.locations.length - 1){
					results += "<li id='loc_"+index+"'>"+locationNumber+" - "+address+"<br /> <a href='javascript: void(0);' title='location|"+locationNumber+"' rel='"+lat+"|"+lon+"' class='showOnMap'>Show On Map</a> <a class='getDetails' href='./location?location="+locationNumber+allLocations+"'>View Details</a></li>";
				}
				if(!jQuery.browser.msie){
					results += "<li id='loc_"+index+"'>"+locationNumber+" - "+address+"<br /> <a href='javascript: void(0);' title='location|"+locationNumber+"' rel='"+lat+"|"+lon+"' class='showOnMap'>Show On Map</a> <a class='getDetails' href='./location?location="+locationNumber+allLocations+"'>View Details</a></li>";
				}
			}
		});
		results += "</ul>";
	}
	else{
		var results = "<h3>Sorry, no billboards currently available. Please <a href='http://www.meadowoutdoor.com/contact/general-contact-form/'>contact our sales team</a> for upcoming options.</h3>";
		
		if( searchTerm != "Idaho"){
			geoEncoder.getLatLng(searchTerm,function(point){
		  		startingPoint = point;
		  		map.setCenter(startingPoint, 8);
			});
	
		}
		else{
			geoEncoder.getLatLng(searchTerm,function(point){
		  		startingPoint = point;
		  		map.setCenter(startingPoint, 5);
			});
		}

	}
	resultsContainer.html(results);
	var links = jQuery('#results ul li a.showOnMap');
	links.bind('click',function(){
		var link = jQuery(this);
		var latLon = jQuery(this).attr('rel');
		latLon = latLon.split('|');
		
		var locNum = jQuery(this).attr('title');
		locNum = locNum.split('|');
		locNum = locNum[1];
		
		var clickedLocation = new GLatLng(latLon[0], latLon[1]);
  		map.setCenter(clickedLocation, 12);
		
		var currentMarker = createCurrentMarker(latLon[0], latLon[1]);
		mgr.addMarker(currentMarker,1,16);
		
		var showCurrentInfo = function(){
			var HTML = link.parent().html();
			currentMarker.openInfoWindowHtml("<br />"+HTML);
		}
		
		var to = setTimeout(showCurrentInfo,100);
	
	});
}

function createCurrentMarker(lat,lon){
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var point = new GLatLng(lat,lon);
	baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(27, 41);
	baseIcon.shadowSize = new GSize(34, 26);
	baseIcon.iconAnchor = new GPoint(9, 26);
	baseIcon.infoWindowAnchor = new GPoint(14, 0);
	baseIcon.infoShadowAnchor = new GPoint(27, 41);
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "";
	// letteredIcon.image = "/resources/images/clickedMarker.png";
	
	
	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	
	// GEvent.addListener(marker, "click", function() {
	// 	marker.openInfoWindowHtml("<h2>THIS IS THE INFO WINDOW</h2>");
	// });
	
	return marker;
}

function openPrintWindow (locNum,face) {
	window.open("../../printDetails.php?location="+locNum+"&face="+face,"printWindow",
	"width=500,height=600,toolbar=no");
}
