// jquery bootstrap file

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

dojo.addOnLoad(FormatDocument);
dojo.addOnLoad(InitializeDatepicker);
dojo.addOnLoad(InitializeFancybox);
dojo.addOnLoad(InitializeTreeview);
dojo.addOnLoad(InitializeJcarousel);
dojo.addOnLoad(InitializePopupWindow);
dojo.addOnLoad(InitializeForm);

/*

$(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');
	$('.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(){
	// fancybox images
	if($('.lightbox_images').length > 0){
		$("a[class^='lightbox_images']").fancybox({
			'scrolling':'no',
			'titleShow':false,
			'hideOnContentClick':false,
			'onStart':function(){
				$('#lightbox_images').show();
			},
			'onClosed':function(){
				$('#lightbox_images').hide();
			}
		});
	}
	

	// fancybox contest
	if($('.lightbox_contest').length > 0){
		$("a[class^='lightbox_contest']").fancybox({
			'autoDimensions':true,
			'titleShow':false,
			'scrolling':'none',
			/*'titlePosition':'inside',*/
			'hideOnContentClick':false,
			'onComplete':function(){
			$.fancybox.resize(); // adjust height to fit content
			}
		});
	}


}

/**
 * @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);
	}
}

