// jquery bootstrap file

/*  +---------------------------+
    |  DOM READINESS DETECTION  |
    |  dependency: jQuery       |
    +---------------------------+  */
// run these functions when the DOM is ready
$(document).ready(
	function(){
		FormatDocument();
		InitializeDatepicker();
		InitializeFancybox();
		InitializeCollapser();
		InitializeGoogleMap();
		InitializeJcarousel();
		InitializePopupWindow();
		InitializeScrollable();
		InitializeDropdown();
		InitializeForm();
	}
);

/*  +----------------------+
    |  JQUERY FORMATTING   |
    |  dependency: jQuery  |
    +----------------------+  */
/**
 * @abstract apply formatting rules to elements in the web page 
 */
function FormatDocument(){
	$('#hd, #header, #bd, #navigation, #ft').addClass('page_container ui-helper-clearfix ui-border-all');
	$('.body_full, .body_threefourths, .body_twothirds, .body_half, .body_third, .body_fourth').addClass('ui-helper-clearfix');
	$('.body_full').each(function(){HideIfEmpty($(this))});
	$('#member_navlist, #navigation, #ft, #paginationControl, .paginationControl, .moreLink').addClass('nav');
	
	$(".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();
}

/**
 * @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
		if($('#bd').css('position') == 'relative'){
			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($(selectors[iteration]).height() > maxHeight){
				maxHeight = $(selectors[iteration]).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_a_signin").length > 0){
		$('.nav_a_signin').removeAttr('href').attr('href','/service/login/loginlb');
		$('.nav_a_signin').attr('onclick','return false;');
	}
	
	// login using fancybox
	$('.nav_a_signin').fancybox({
		'autoScale':false,
		'padding':10,
		'margin':10,
		'width':600,
		'scrolling':'no',
		'titleShow':false,
		'hideOnContentClick':false,
		'onComplete':function(){
			$.fancybox.resize(); // adjust height to fit content
		}
	});
	
	// fancybox upgrade form
	if($('#upgradebox').length > 0){
		// upgrade box using fancybox
		$("a[rel^='upgradebox']").fancybox({
			'scrolling':'no',
			'titleShow':false,
			'onStart':function(){
			this.showNavArrows = false;
				$('#upgradebox').show();
			},
			'onClosed':function(){
				$('#upgradebox').hide();
			}
		});
	}
	
	// fancybox images
	$("a[class^='lightbox_images']").fancybox({
		'scrolling':'no',
		'titlePosition':'inside',
		'titleShow':true,
		'hideOnContentClick':false,
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
			var str=title.split("|");
		    var ret= "<span><b style='margin-left:20px;float:left;display:inline;'>" + str[0] + "</b></span><p style='float:right;display:inline;margin:0px 30px;'>(" + (currentIndex + 1) + " of " + currentArray.length + ")</p>";
		    if(str[1])
		    {
		    	ret += "<p style='clear:both;margin-left:20px;text-align:left;display:block;'>" + str[1] + "</p>";
		    }
		    return ret;
	}
	});
	
	// fancybox video
	$("a[class^='lightbox_videos']").fancybox({
		'scrolling':'no',
		'type':'iframe',
		'hideOnContentClick':false,
		'autoDimensions'	: false,
		'width'         		: 660,
		'height'        		: 360,
		'titlePosition':'inside',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
			var str=title.split("|");
			var ret= "<span><b style='margin-left:20px;float:left;display:inline;'>" + str[0] + "</b></span><p style='float:right;display:inline;margin:0px 30px;'>(" + (currentIndex + 1) + " of " + currentArray.length + ")</p>";
			    if(str[1])
			    {
			    	ret += "<p style='clear:both;margin-left:20px;text-align:left;display:block;'>" + str[1] + "</p>";
			    }
		    return ret;}
	});
	
	$("a[class^='fanbox']").fancybox({
		'scrolling':'yes',
		'type':'iframe',
		'hideOnContentClick':false,
		'autoDimensions'	: false,
		'width'         		: 720,
		'height'        		: 660,
		'titlePosition':'inside'
	});
	
	// video box using fancybox
	$("a[rel^='videobox']").fancybox({
		'scrolling':'no',
		'titleShow':false,
		'type': 'swf',
		'swf': {
		   	 	'wmode': 'transparent',
		   	 	'allowfullscreen': 'true'
		},
		'onStart':function(){
			$('#videobox').show();
		},
		'onClosed':function(){
			$('#videobox').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 displayname");
				var sURL ='/service/profile/displaynameupdate';
				break;
			case '7':
				//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 '8':
				//	prompt("4: sending user to home page");
				var sURL ='/service/emailverify/invalidemail';
				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" );
	}
}

/**
 * @abstract put lyrics in fancybox
 * */
function abc(arrid){
	// alert("You have activated me by clicking the grey button! Note that the event handler is added within the event that it handles, in this case, the form button event tag");
	var txt=document.getElementById("lyricstext");
	txt.innerHTML=lyrics[arrid];
	// document.all.lyrics.innerText="aejsfi awiefjnoa anwefoaw awenfoaw aowehijaowe oawejnoawj";
}


/*  +-------------------------------+
    |  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($('.nav_a_jukebox').length > 0){
		$('.nav_a_jukebox').popupWindow({ 
			height: 160, 
			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';
		
		var newoption = document.createElement('option');
		newoption.value = 'N-A';
		newoption.text = '-----Pick One-----';
		try{
			statelists.add(newoption,null);
		}
		catch(ex){
			statelists.add(newoption);
		}
		
		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);
	}
}

/*  +-------------------------+
|  Scrollable             |
|  dependency: jQuery UI  |
+-------------------------+  */
function InitializeScrollable(){
	if($("#chained").length > 0){
		$("#chained").scrollable({circular: true, mousewheel: true}).navigator().autoscroll({
			interval: 6000		
		});
	}	
	else if($(".scrollable").length > 0){
		 $(".scrollable").scrollable({
	         items:'items',
	         size:1,
	         speed:500,
	         activeClass:'current',
	         clickable: false,
	 }); 
	}	 
	

}
/*  +-------------------------+
|  Dropdown menu for tour EDP             |
|  dependency: jQuery UI  |
+-------------------------+  */
function InitializeDropdown(){
$('img.tour_archive_head').click(function () {
	
	$('ul.sub_menu').slideToggle('medium');
 });
}
function InitializeCollapser(){

	
	
	if($(".news_year_in").length > 0){
		$('.panel1').hide();
		$('.news_year_in').collapser(
			{
				target: 'next',
				effect: 'slide',
				changeText: 0,
				expandClass: 'expIco',
				collapseClass: 'collIco'
			},
			function(){
				$('.panel1').slideUp();
			}
		);
	}
	
	if($(".news_months_in").length > 0){
		$('.panel2').hide();
		$('.news_months_in').collapser(
			{
				target: 'next',
				effect: 'slide',
				changeText: 0,
				expandClass: 'expIco',
				collapseClass: 'collIco'
			},
			function(){
				$('.panel2').slideUp();
			}
		);
	}
}



/****** GOOGLE MAP**********/
var infowindow;
var map = null;
var zoomLevel=2;
var centerPoint;
var maptype='terrain';
function InitializeGoogleMap(){
	if($("#map_canvas").length > 0){
		maptype='terrain';
		if(parseFloat(maxLong) ==  parseFloat(minLong)){
			zoomLevel=12;
			mapType='roadmap';
			centerPoint = new google.maps.LatLng((parseFloat(maxLat) + parseFloat(minLat))/2 , (parseFloat(maxLong) +  parseFloat(minLong))/2);//auto center
			
		}
		else{ 
			centerPoint = new google.maps.LatLng(27.708412500000001,11.8276785);
			
			if(Math.abs(parseFloat(maxLong) -  parseFloat(minLong))<40){
				zoomLevel=2;
				mapType='terrain';
			}
			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);//auto center
		//centerPoint = new google.maps.LatLng(51.32257,8.359048999999999);//center europe
		
		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++) {
		//	alert(tour_dates[venues]['lat'] + "," + tour_dates[venues]['long']);
			/* 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 + ", " + tour_dates[venues].city + "," + tour_dates[venues].country 
		        + "</div>";
		    //alert(infoContent);
		        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 + ")"
		  	+ "'>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].name + ", " + tour_dates[venues].city + ", " + tour_dates[venues].country,
		     	 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();
  }
}

