// JavaScript Document

;(function( $ ){
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};
	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};
	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};
	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
				if( !isWin )
					return elem;
			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};
	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };	
		if( target == 'max' )
			target = 9e9;
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );
		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');
			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);
				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );
					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}
				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );
				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});
			animate( settings.onAfter );			
			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

$(document).ready(function(){
$('#map-top-left').jmap({
	mapZoom: 16,
	mapCenter: [34.96001,-81.93428]
});
$('#map-top-left').jmap('AddMarker', {
			'pointLatLng': [34.96001,-81.93428],
			'pointHTML': '<h2>Wofford College</h2><p>429 N Church St., Spartanburg, SC 29303</p>'
		});
   
   $(".add-to-trip").click(function() {
      var attrTitle = $('#map-top-right-top h3').text();
	  var attrImg = ' <img src="/static/images/attractions/cancel-button.png" alt="cancel button"/>';
	  var attrAddr = $('#map-top-right-top .street-address').html();
	  $.scrollTo($("#my-trip"), duration=500);
   	  $("#my-trip ol").append('<li>' + attrTitle + attrImg + '<ul class="disappear"><li>' + attrAddr + '</li></ul></li>');
	  $("#my-trip ol li").click(function() {
	   	  $(this).remove();
   	  });
   });

   $("#my-trip ol li").click(function() {
   	  $(this).remove();
   });
   
   $(".wofford-to-trip").click(function() {
   	  $("#map-top-right-top").html("");
	  var newHTML = '<h3><a href="#">Wofford College</a></h3><ul class="map-top-right-ul"><li class="street-address">429 N Church St, Spartanburg, SC, 29303</li><li class="telephone">(864)597-4000</li></ul>' + '<img src="/static/images/attractions/add-to-trip.jpg" class="add-to-trip" alt="add to trip button"/>';
	  $("#map-top-right-top").html(newHTML);
	  var attrTitle = $('#map-top-right-top h3').text();
	  var attrImg = ' <img src="/static/images/attractions/cancel-button.png" alt="cancel button"/>';
	  var attrAddr = '<ul class="disappear"><li>' + $('#map-top-right-top .street-address').html(); + '</li></ul>';
	  $.scrollTo($("#map-info"), duration=500);
   	  $("#my-trip ol").append('<li>' + attrTitle + attrImg + attrAddr + '</li>');
	  $("#my-trip ol li").click(function() {
	   	  $(this).remove();
   	  });
	  $(".add-to-trip").click(function() {
	      var attrTitle = $('#map-top-right-top h3').text();
		  var attrImg = ' <img src="/static/images/attractions/cancel-button.png" alt="cancel button"/>';
		  var attrAddr = '<ul class="disappear"><li>' + $('#map-top-right-top .street-address').html(); + '</li></ul>';
		  $.scrollTo($("#my-trip"), duration=500);
	   	  $("#my-trip ol").append('<li>' + attrTitle + attrImg + attrAddr + '</li>');
		  $("#my-trip ol li").click(function() {
		   	  $(this).remove();
	   	  });
	  });
	  $('#map-top-left').jmap('SearchAddress', {
            'query': "429 N Church St, Spartanburg, SC",
            'returnType': 'getLocations'
        }, function(result, options) {
            
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
            $.each(result.Placemark, function(i, point){
				var attrTitle = $('#map-top-right-top h3').html();
				var attrAddress = $('#map-top-right-top .street-address').html();
				var attrInfo = attrTitle + attrAddress;
				$('#map-top-left').html("");
				$('#map-top-left').jmap('init', {'mapZoom':12,'mapCenter':[point.Point.coordinates[1], point.Point.coordinates[0]]});

                $('#map-top-left').jmap('AddMarker',{
                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML':attrInfo
                    });
                });
            } else {
                $('#address').val(valid.message);
            }
        });
        return false;	
   });
   

   $(".your-address-btn").click(function() {
   	  $("#map-top-right-top").html("");
	  var newHTML = '<h3><a href="#">Home</a></h3><ul class="map-top-right-ul"><li class="street-address">' +  $('#your-address').val() + '</li></ul>' + '<img src="/static/images/attractions/add-to-trip.jpg" class="add-to-trip" alt="add to trip button"/>';
	  $("#map-top-right-top").html(newHTML);
	  $(".add-to-trip").click(function() {
	      var attrTitle = $('#map-top-right-top h3').text();
		  var attrImg = ' <img src="/static/images/attractions/cancel-button.png" alt="cancel button"/>';
		  var attrAddr = '<ul class="disappear"><li>' + $('#map-top-right-top .street-address').html(); + '</li></ul>';
		  $.scrollTo($("#my-trip"), duration=500);
	   	  $("#my-trip ol").append('<li>' + attrTitle + attrImg + attrAddr + '</li>');
		  $("#my-trip ol li").click(function() {
		   	  $(this).remove();
	   	  });
	  });
	  $('#map-top-left').jmap('SearchAddress', {
            'query': $('#your-address').val(),
            'returnType': 'getLocations'
        }, function(result, options) {
            
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
            $.each(result.Placemark, function(i, point){
				var attrTitle = $('#map-top-right-top h3').html();
				var attrAddress = $('#map-top-right-top .street-address').html();
				var attrInfo = attrTitle + attrAddress;
				$('#map-top-left').html("");
				$('#map-top-left').jmap('init', {'mapZoom':12,'mapCenter':[point.Point.coordinates[1], point.Point.coordinates[0]]});

                $('#map-top-left').jmap('AddMarker',{
                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML':attrInfo
                    });
                });
            } else {
                $('#address').val(valid.message);
            }
        });
        return false;	
   });

   $("#attractions li").click(function () { 
     
	  $("#map-top-right-top").html("");
	  var newHTML = $(this).html() + '<img src="/static/images/attractions/add-to-trip.jpg" class="add-to-trip" alt="add to trip button"/>'
	  $("#map-top-right-top").html(newHTML);
	  $(".add-to-trip").click(function() {
	      var attrTitle = $('#map-top-right-top h3').text();
		  var attrImg = ' <img src="/static/images/attractions/cancel-button.png" alt="cancel button"/>';
		  var attrAddr = '<ul class="disappear"><li>' + $('#map-top-right-top .street-address').html(); + '</li></ul>';
		  $.scrollTo($("#my-trip"), duration=500);
	   	  $("#my-trip ol").append('<li>' + attrTitle + attrImg + attrAddr + '</li>');
		  $("#my-trip ol li").click(function() {
		   	  $(this).remove();
	   	  });
	  });
	    $.scrollTo($("#container-light"), duration=500);
        $('#map-top-left').jmap('SearchAddress', {
            'query': $(this).children().eq(1).children().eq(0).text(),
            'returnType': 'getLocations'
        }, function(result, options) {
            
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
            $.each(result.Placemark, function(i, point){
				var attrTitle = $('#map-top-right-top h3').html();
				var attrAddress = $('#map-top-right-top .street-address').html();
				var attrInfo = attrTitle + attrAddress;
				$('#map-top-left').html("");
				$('#map-top-left').jmap('init', {'mapZoom':12,'mapCenter':[point.Point.coordinates[1], point.Point.coordinates[0]]});

                $('#map-top-left').jmap('AddMarker',{
                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML':attrInfo
                    });
                });
            } else {
                $('#address').val(valid.message);
            }
        });
        return false;	

    });
	
	$(".get-directions-btn").click(function() {
		$("#directions-output").html("");
		$("#directions-output").css("background-color","#FFFFFF");
		var route = 'from: ' + $('#my-trip ol li ul li:first').text() + ' ';
		var toArray = new Array();
		$('#my-trip ol li ul li:not(:first)').each(function () {
				toArray.push('to: ' + $(this).text());
		});
		route = route + toArray.join(" ");
		$('#map-top-left').jmap('SearchDirections', {
			'query': route,
			'panel':'#directions-output'
		}, function(result, options) {
             var valid = Mapifies.SearchCode(result.getStatus());
             if (valid.success) {
               $.each(result.Placemark, function(i, point){
                 $('#map1').jmap('AddMarker',{
                   'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                   'pointHTML':point.address
                 });
               });
             } else {
               $('#address').val(valid.message);
             }
       });
       return false;
	});

  });
