// jquery bootstrap file

/*  +---------------------------+
    |  DOM READINESS DETECTION  |
    |  dependency: jQuery       |
    +---------------------------+  */
// run these functions when the DOM is ready

$(document).ready(
	function(){
		FormatDocument();
		InitializeDatepicker();
		InitializeFancybox();
		InitializeCollapser();
		//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'); }
			);
		}
	);
}

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

/*  +----------------------------+
	|  FACEBOOK CONNECT          |
	|  dependency: facebook API  |
	+----------------------------+  */
function InitializeFacebookConnect(){
	// this is loaded asynchronously in the header
}

/**
 * @abstract display the facebook profile pane in the header
 * @param int fb_uid the facebook uid of the current facebook user
 * */
function show_fb_profile_pane(fb_uid){
	if($("#facebook_profile_pane").length > 0){
		// only show facebook profile if user has linked it to the logged-in account
		$.ajax({
			type: 'POST',
			url: '/service/login/facebooklinked/uid/'+fb_uid,
			dataType: 'json',
			success: function(data){
				if(data.msg == 'profile_is_linked'){
					if($("#facebook_profile_pane").length > 0){
						$("#facebook_profile_pane").css('display','block');
					}
					if($("#facebook_linking").length > 0){
						$("#facebook_linking").css('display','block');
					}
				}
			}
		});
	}
}

/**
 * @abstract trigger the php function that will record login history
 * */
function update_facebook_login_history(){
	$.ajax({
		type: 'POST',
		url: '/service/login/facebookhistory',
		dataType: 'json',
		success: function(data){
			// do nothing
		}
	});
}

function goToIndex(){
	parent.window.top.location.href = '/';
}

/**
 * @abstract open url in fancybox window
 * @param string url
 * @param string title
 * @param boolean use_iframe
 * @param int width (only used when use_iframe == true)
 * */
function buildFancybox(url, title, use_iframe, width) {
	if(use_iframe == true){
		parent.window.top.$.fancybox({
			'type':'iframe',
			'width':width,
			'href':url,
			'title':title,
			'titleShow':true,
			'hideOnContentClick':false,
			'onComplete':function(){
				$.fancybox.resize(); // adjust height to fit content
			}
		});
	}
	else{
		parent.window.top.$.fancybox({
			'href':url,
			'title':title,
			'titleShow':true,
			'hideOnContentClick':false,
			'onComplete':function(){
				$.fancybox.resize(); // adjust height to fit content
			}
		});
	}
}

function buildSignup(url,title){
	buildFancybox(url,title,true,650);
}

function buildLogin(url,title){
	buildFancybox(url,title,false,null);
}

function not_a_member_click(){
	url = '/service/subscribe/signupnam?uri='+window.location.href;
	title = 'Sign Up';
	buildFancybox(url,title,true,800);
}

function link_this_profile(){
	url = '/service/login/facebookassociate';
	parent.window.top.location = url;
}

function link_account_click(){
	FB.getLoginStatus(
		function(response){
			if (response.session) {
				$.ajax({
					type: 'POST',
					url: '/service/login/facebooklink',
					data: ({ facebook_id : response.session.uid }),
					dataType: 'json',
					success: function(data){
						if($("#facebook_link_pane").length > 0){
							$("#facebook_link_pane").html(data.msg);
						}
					}
				});
			}
		}
	);
}

function unlink_account_click(){
	FB.getLoginStatus(
		function(response){
			if (response.session) {
				$.ajax({
					type: 'POST',
					url: '/service/user/unlinkfacebook',
					data: ({ facebook_id : response.session.uid }),
					dataType: 'json',
					success: function(data){
						if(data.msg == 'profile_unlinked'){
							if($("#facebook_profile_pane").length > 0){
								$("#facebook_profile_pane").css('display','none');
							}
							if($("#facebook_linking").length > 0){
								$("#facebook_linking").css('display','none');
							}
						}
					}
				});
			}
		}
	);
}

function facebook_login_button_onclick() {
	FB.Connect.requireSession(fb_login_callback);
}

/**
 * @abstract handle the facebook login callback
 * */
function fb_login_callback(){
	FB.getLoginStatus(
		function(response){
			if (response.session) {
				$.ajax({
					type: 'POST',
					url: '/service/login/facebook',
					data: ({ uid : response.session.uid }),
					dataType: 'json',
					success: function(data){
						switch(data.msg){
							case 'signin_successfully' :
								update_facebook_login_history(); // record login event in db 
								parent.window.top.location.href += '?ref=2'; // refresh page
								break;
							case 'profile_not_exist' :
								if(document.location.href != '/service/subscribe/signup'){
									parent.window.top.location.href = '/service/subscribe/signup'; // refresh page
									// buildFancybox('/service/subscribe/signup','Login Using Facebook',true,650); // send user to subscription page
								}
								break;
							case 'invalid_uid' :
							default : // do nothing
						}
					}
				});
			}
		}
	);
}

// setup logout button for facebook users
if(false && $(".nav_logout").length > 0){ // removed; don't logout user from facebook
	if(FB.getLoginStatus()){
		$('.nav_logout').removeAttr('href').attr('href','#');
		$('.nav_logout').attr('onclick','facebook_logout_button_onclick();');
	}
}

function facebook_logout_button_onclick(){
	FB.Connect.logout(fb_logout_callback);
}

function fb_logout_callback(){
	window.parent.location.href = '/service/user/logout/';
}


/*  +-------------------------+
    |  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;');
	}
	
	// disable clickthrough for emaillist button
	if($(".nav_emaillist").length > 0){
		$('.nav_emaillist').attr('onclick','return false;');
	}
	
	// login using fancybox
	$('.nav_signin').fancybox({
		'autoScale':false,
		'autoDimensions':false,
		'height':346,
		'width':800,
		'scrolling':'no',
		'titleShow':false,
		'hideOnContentClick':false,
		'onComplete':function(){
			$.fancybox.resize(); // adjust height to fit content
		}
	});
	
	// emaillist using fancybox
	$('.nav_emaillist').fancybox({
		'type':'iframe',
		'autoScale':false,
		'autoDimensions':false,
		'height':421,
		'width':800,
		'scrolling':'no',
		'titleShow':false,
		'hideOnContentClick':false,
		'onComplete':function(){
			$.fancybox.resize(); // adjust height to fit content
		}
	});
	// fancybox images
	$("a[class^='lightbox_images']").fancybox({
		'scrolling':'no',
		'titlePosition':'inside',
		'hideOnContentClick':false,
		'onComplete': function(){
			$('#fancybox-wrap').hover(function(){
				$('#fancybox-title').show();
			},function(){
				$('#fancybox-title').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.top.location = sURL;
	}
	else{
		// show failure message
		$.fancybox.hideActivity();
		$('#loginbox .globalError').html( "Login Failed" );
	}
}


/*  +--------------------------------+
	|  COLLAPSER                     |
	|  dependency: jQuery collapser  |
	+--------------------------------+  */
function InitializeCollapser(){

	// setup collpaser element
	if($("#comment_head").length > 0){
		$('#comment_head').collapser(
			{
				target: 'next',
				effect: 'slide',
				changeText: 0,
				expandClass: 'expIco',
				collapseClass: 'collIco'
			},
			function(){
				$('.panel').slideUp();
			}
		);
	}
	
	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();
			}
		);
	}
}


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

/**
 * @abstract customize text in comment form text area
 * */
function comment_message(){
	if($('#body').length > 0){
		myCommentBody = $('#body');
		if(myCommentBody.val().length > 0){
			myCommentBody.blur(function(){
				if(myCommentBody.val().length == 0){
					myCommentBody.val('Please share your comments.');
				}
			});
			myCommentBody.focus(function(){
				if(myCommentBody.val() == 'Please share your comments.'){
					myCommentBody.val('');
				}
			});
		}
	}
}

