// jquery bootstrap file

/*  +---------------------------+
    |  DOM READINESS DETECTION  | 
    |  dependency: jQuery       |
    +---------------------------+  */
// run these functions when the DOM is ready
// dojo is currently controlling the document.ready function;

try{
	dojo.addOnLoad(FormatDocument);
	dojo.addOnLoad(InitializeDatepicker);
	dojo.addOnLoad(InitializeFancybox);
	dojo.addOnLoad(InitializeTreeview);
	dojo.addOnLoad(InitializeGoogleMap);
	dojo.addOnLoad(InitializeJcarousel);
	dojo.addOnLoad(InitializePopupWindow);
	dojo.addOnLoad(InitializeForm);
}
catch(e){
	$(document).ready(
		function(){
			FormatDocument();
			InitializeDatepicker();
			InitializeFancybox();
			InitializeTreeview();
			InitializeJcarousel();
			InitializePopupWindow();
			InitializeForm();
		}
	);
}

/*  +----------------------+
    |  JQUERY FORMATTING   |
    |  dependency: jQuery  |
    +----------------------+  */
/**
 * @abstract apply formatting rules to elements in the web page 
 */
function FormatDocument(){
	$('#hd, #bd, #ft').addClass('ui-helper-clearfix page_container');
	$('.body_full, .body_threefourths, .body_twothirds, .body_half, .body_third, .body_fourth').addClass('ui-helper-clearfix');
	$('.sharing_links').addClass('ui-helper-clearfix');
	$('.body_full').each(function(){HideIfEmpty($(this))});
	$(".media_component_video").each(
		function(){
			$(this).hover(
				function(){ $(this).find('.video_title').css('display', 'block'); },
				function(){ $(this).find('.video_title').css('display', 'none'); }
			);
		}
	);
	
	// check for height issues with sections
	// SetBodyHeight();
	
	/*suppress CurvyCorner Obj ID error*/
	var curvyCornersVerbose = false;
}

/**
 * @abstract set the height of the body to that of the tallest item in the body
 */
function SetBodyHeight(){
	if($('#bd').length){ // check to see if exists
		selectors = Array('.body_full','.body_threefourths','.body_twothirds','.body_half','.body_third','.body_fourth');
		$('#bd').css('min-height',GetHeightOfTallestElement(selectors));
	}
}

/**
 * @abstract get the height of the tallest selector submitted
 * @param array of jquery selector strings
 * @return int
 */
function GetHeightOfTallestElement(selectors){
	maxHeight = 0;
	for(iteration in selectors){
		$(selectors[iteration]).each(function(){
			if($(this).height() > maxHeight){
				maxHeight = $(this).height();
			}
		});
	}
	return maxHeight;
}

/**
 * @abstract hide object if does not have html content
 * @param jquery object
 * @return jquery object
 */
function HideIfEmpty(me){
	if($.trim(me.html()).length == 0){
		me.hide();
	}
	return me;
}


/*  +-------------------------+
    |  DATEPICKER             |
    |  dependency: jQuery UI  |
    +-------------------------+  */
function InitializeDatepicker(){
	// initialize birthDay datepicker on signup and profile forms
	if($("#birthDay").length > 0){
		var curyear=new Date();
		curyear=curyear.getFullYear();
	    $("#birthDay").datepicker({
			changeMonth: true,
			changeYear: true,
			yearRange:curyear-103 + ':' + curyear,
			dateFormat:'mm/dd/yy'
		});
	}
}




/*  +-------------------------------+
    |  FANCYBOX                     |
    |  dependency: jQuery fancybox  |
    +-------------------------------+  */
function InitializeFancybox(){
	
	// alter href and disable clickthrough for login button
	if($("#nav_signin").length > 0){
		$('#nav_signin').removeAttr('href').attr('href','/service/login/loginlb');
		$('#nav_signin').attr('onclick','return false;');
		$('#nav_signin').fancybox({
			'autoScale':true,
			'autoDimensions':true,
			'centerOnScroll':true,
			'padding':10,
			'margin':10,
			'width':600,
			'scrolling':'no',
			'titleShow':false,
			'hideOnContentClick':false,
			'onComplete':function(){
				$.fancybox.resize(); // adjust height to fit content
			}
		});
	}
	
	// fancybox images
	$("a[class^='lightbox_images']").fancybox({
		'scrolling':'no',
		'titleShow':false,
		'hideOnContentClick':false,
		'onStart':function(){
			$('#lightbox_images').show();
		},
		'onClosed':function(){
			$('#lightbox_images').hide();
		}
	});
}

/**
 * @abstract post-login hook to redirect user
 * */
function EvaluateLoginResponse(jsonObject){
	if(jsonObject['result'] == 'true'){
		// reload page
		$.fancybox.hideActivity();
		//prompt(jsonObject['loginstate']);
		switch(jsonObject['loginstate']){
			case '1':
				//prompt("1: sending user to update username");
				var sURL ='/service/profile/usernameupdate';
				break;
			case '2':
				//	prompt("2: sending user to renewal message");
				var sURL ='/service/subscribe/renew';
				break;
			case '3':
				//	prompt("3: sending user to verify email message");
				var sURL ='/service/emailverify/index';
				break;
			case '4':
				//	prompt("4: sending user to home page");
				var sURL ='/default/index/home';
				break;
			case '5':
			default : 
			//	prompt("5: sending user to previous page");
				var sURL = unescape(window.location.pathname);
				if(sURL == '/service/user/logout/'){
					sURL = '/default/index/';
				}
				break;
		}
		$('#loginbox .globalError').html('');
		window.location.replace(sURL);
	}
	else{
		// show failure message
		$.fancybox.hideActivity();
		$('#loginbox .globalError').html( "Login Failed" );
	}
}


/*  +-------------------------------+
    |  TREEVIEW                     |
    |  dependency: jQuery treeview  |
    +-------------------------------+  */
function InitializeTreeview(){
	// treeview news archive
	if($("#browser").length > 0){
	    $("#browser").treeview();
	}
}

/*  +--------------------------------+
    |  JCAROUSEL                     |
    |  dependency: jQuery jcarousel  |
    +--------------------------------+  */
function InitializeJcarousel(){
	// jcarousel image slider
	if($('#mycarousel').length > 0){
	    jQuery('#mycarousel').jcarousel({
	    	 vertical: false,
	        auto: 4,
	        wrap: 'last',
	        initCallback: mycarousel_initCallback
	    });
	}
}

/**
 * @abstract bind functions to image slider methods
 * */
function mycarousel_initCallback(carousel){
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});
	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});
    // Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
};


/*  +----------------------------------+
    |  POPUP WINDOW                    |
    |  dependency: jQuery popupWindow  |
    +----------------------------------+  */
function InitializePopupWindow(){
	// popup window for jukebox
	if($('.jukebox').length > 0){
		$('.jukebox').popupWindow({ 
			height: 242, 
			width: 400, 
			top:50, 
			left:50,
			menubar:0,
			status:0,
			toolbar:0
		});
	}
}


/*  +----------------------+
    |  FORMS               |
    |  dependency: jQuery  |
    +----------------------+  */
function InitializeForm(){
	
	// prepopulate country/state dropdown combo
	if($("#country").length > 0){
		getStatesList($("#country").val());
	}
	
}

/**
 * @abstract get list of states/provinces for a given country
 * */
function getStatesList(country){
	if($("#state").length > 0){
		defstate = $("#state").val();
		$.post(
			'/service/subscribe/getstatesajax/format/json', // url
			{'country':country}, // data
			function(data){ EvaluateStateResponse(data,defstate); }, // callback
			"json" // type
		);
	}
}

/**
 * @abstract populate dropdown select state/province
 * */
function EvaluateStateResponse(jsonObject,defstate){
	statelist = eval('('+jsonObject['statelists']+')');
	if(statelist !== false){
		// create new select element
		var statelists = document.createElement('select');
		statelists.id = 'state';
		statelists.name = 'state';
		for(abbreviation in statelist){
			// create new option element
			var newoption = document.createElement('option');
			newoption.value = abbreviation;
			newoption.text = statelist[abbreviation];
			if(defstate == abbreviation){
				newoption.selected = true;
			}
			// append option element to select element
			try{
				statelists.add(newoption,null);
			}
			catch(ex){
				statelists.add(newoption);
			}
		}
		$('#state').replaceWith(statelists);
	}
	else if(document.getElementById('state').tagName != 'INPUT'){
		// create new input text element
		var statelists = document.createElement('input');
		statelists.type = 'text';
		statelists.id = 'state';
		statelists.name = 'state';
		statelists.value = defstate;
		$('#state').replaceWith(statelists);
	}
}


/****** GOOGLE MAP**********/
var infowindow;
var map = null;
var zoomLevel=2;
var centerPoint;
var maptype;

// make sure the map canvas exists first
function InitializeGoogleMap(){
	if($('#map_canvas').length > 0){
		InitializeGoogleMap2();
	}
}

function InitializeGoogleMap2(){
	if(parseFloat(maxLong) ==  parseFloat(minLong)){
		zoomLevel=12;
		mapType='roadmap';
	}	
	else if(Math.abs(parseFloat(maxLong) -  parseFloat(minLong))<60){
		zoomLevel=4;
		mapType='terrain';
	}
	else if(Math.abs(parseFloat(maxLong) -  parseFloat(minLong))<130){
		zoomLevel=3;
		mapType='terrain';
	}	
	infowindow = new google.maps.InfoWindow({
	      content: "<LOADING>"
	    });
	 // make sure closing via the [x] also goes back to full map view
		google.maps.event.addListener(infowindow, 'closeclick', function() {
		fullmap();
	});
	
	
	centerPoint = new google.maps.LatLng((parseFloat(maxLat) + parseFloat(minLat))/2 , (parseFloat(maxLong) +  parseFloat(minLong))/2);
  	
	map = new google.maps.Map(document.getElementById('map_canvas'), {
	    center: centerPoint,
	    zoom: zoomLevel,
	    mapTypeId: mapType,
	    scrollwheel: false
	    	
	});
	 // Prepares the marker object, creating a google.maps.Marker object for each
	var marker;
	for (var venues = 0; venues < tour_dates.length; venues++) {
		/* Map detail */
		
		if (tour_dates.length == 1) {
	  	  var infoContent = "";
	    }
	    else
	    {
	    var infoContent = "<div style='text-transform:capitalize; padding-right: 15px; font-size: 14px; color: #000000;'>"
	        + tour_dates[venues].show_date + " @ " + tour_dates[venues].name.toLowerCase()
	        + "</div>";

	        if ( tour_dates[venues].address1 ) { infoContent += tour_dates[venues].address1 + "<br/>"; }
	        if ( tour_dates[venues].address2 ) { infoContent += tour_dates[venues].address2 + "<br/>"; }

	        if ( tour_dates[venues].city || tour_dates[venues].state || tour_dates[venues].country ) {
	  	var csc;
	  	if ( tour_dates[venues].city ) { csc = tour_dates[venues].city; }
	  	if ( tour_dates[venues].state ) {
	  	  if ( csc ) csc += ", ";
	  	  csc += tour_dates[venues].state;
	  	}
	  	if ( tour_dates[venues].country ) {
	  	  if ( csc ) csc += " ";
	  	  csc += tour_dates[venues].country;
	  	}
	  	infoContent += csc + "<br/>";
	        }

	        infoContent += "<br/><a style='text-decoration:none;padding:2px;background-color:#ff0000;color:#ffffff' href='/tour/date/id/"
	  	+ tour_dates[venues].tour_date_id
	  	+ "'>Event Detail Page &raquo;</a><br/>";

	        infoContent += "<br><a target='_blank' style='color:#ff0000;text-decoration:none' href='http://maps.google.com/maps?daddr="
	  	+ tour_dates[venues].lat + "," + tour_dates[venues].long
	  	+ "+(" + tour_dates[venues].name.replace(/ /g, "+") + ")"
	  	+ "'>Get directions &raquo;</a>";

	        infoContent += " &nbsp;&nbsp;&nbsp;&nbsp; <a style='color:#ff0000;text-decoration:none' onclick='fullmap();'>Back to full map &raquo;</a>";
	    }  
		
		/*End of Map detail*/
		
    	marker = new google.maps.Marker({
             map: map,
             position: new google.maps.LatLng(tour_dates[venues]['lat'], tour_dates[venues]['long']),
             clickable: false,
	         draggable: true,
	         flat: true,
	         title: tour_dates[venues].show_date + ", " + tour_dates[venues].city + " @ " + tour_dates[venues].name,
	     	 infoContent: infoContent
           });
    	
    		 google.maps.event.addListener(marker, 'click', function() {
    			map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    			map.setZoom(8);
    			map.setCenter(this.position); 
    			infowindow.setContent(this.infoContent);
    			infowindow.open(map, this);
    		      });
    }
	
}



function fullmap() {
  if ( map ) {
    map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
    map.setZoom(zoomLevel);
    map.setCenter(centerPoint);
    infowindow.close();
  }
}


