// jquery bootstrap file

/*  +---------------------------+
    |  DOM READINESS DETECTION  |
    |  dependency: jQuery       |
    +---------------------------+  */
// run these functions when the DOM is ready
$(document).ready(
	function(){
		FormatDocument();
		InitializeDatepicker();
		InitializeAccordion();
		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');
	$('.body_full').each(function(){HideIfEmpty($(this))});
	$('#paginationControl, .paginationControl').addClass('nav');

	// set style for odd and even rows in tables
	$(".striped tr:visible:even").addClass("evenRow");
	$(".striped tr:visible:odd").addClass("oddRow");
	
	$(".media_component_video").each(
		function(){
			$(this).hover(
				function(){ $(this).find('.video_title').css('display', 'block'); },
				function(){ $(this).find('.video_title').css('display', 'none'); }
			);
		}
	);
	
	// fading disabled images
	$('img.disabled').fadeTo(1000,0.4).hover(
		function(){$(this).fadeTo(0,1)},
		function(){$(this).fadeTo(1000,0.4)}
	);
	
}


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

/*  +------------------------+
    |  ACCORDION             |
    |  dependency: jQueryUI  |
    +------------------------+  */
function InitializeAccordion(){
	if($(".accordion").length > 0){
		$('.accordion').accordion({
			header:'.help_section',
			autoHeight:false,
			collapsible:true,
			navigation:false
		})
		.accordion('option','active',0);
	}
}


/*  +-------------------------------+
    |  FANCYBOX                     |
    |  dependency: jQuery fancybox  |
    +-------------------------------+  */
function InitializeFancybox(){
	
	// alter href and disable clickthrough for login button
	$("a[href='/service/login']")
		.removeAttr('href')
		.attr('href','/service/login/loginlb')
		.attr('onclick','return false;');
	
	// login using fancybox
	$("a[href='/service/login/loginlb']").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 images
	$("a[class='lightbox_images']").fancybox({
		'scrolling':'no',
		'titleShow':false,
		'hideOnContentClick':false,
		'onStart':function(){
			$('#lightbox_images').show();
		},
		'onClosed':function(){
			$('#lightbox_images').hide();
		}
	});
	
	
	// fancybox videos
	$("a[class='video_fancybox']").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'autoScale'     	: true,
		'type'				: 'iframe',
		'scrolling'   		: 'no',
		'width'             : 640,
		'height'            : 360
	});
	
}

/**
 * @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 '8':
				//	prompt("3: sending user to invalid email message");
				var sURL ='/service/emailverify/invalidemail';
				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" );
	}
}

/**
 * @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 email
	
		$('.lnk_newsletter').popupWindow({ 
			height: 360, 
			width: 520, 
			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);
	}
}


// listner

function listener(event){
    var arr=eval('('+event.data+')');
    $('#contest_iframe').css({height:arr.height});
          
}

if (window.addEventListener){
    addEventListener("message", listener, false)
} 
else 
{
    attachEvent("onmessage", listener)
}
