$(function() {
		enableLoginBar();
		$.fn.enableExpandables();
		enableToolTips();
		retakeModule();
		startModule();
		saveModule();
		$('div#profession-dropdown ul li:last-child').addClass('last');    
		enableSearchButton();
		submitReviw();
		enablePopUps();
		enableErrorExpandables();
		startModuleALert();
		printCertificate();
		$( "button#printable" ).click(function(){
            $(this).print();
            /* Cancel click event.*/
         return( false );
  
         });
	
});

function enableSearchButton(){
	$('span.submit').click(function(){
		$('form#header-search').submit();
	});
}

	
function enableLoginBar(){
    
	$('button.status').live('click',function(){				
		initiatLoginPopUp($(this));
    });
	
	$('a#sign-in').bind('click',function(){	
		if($.browser.version < 8 && $.browser.msie){	
			initiatLoginPopUp($(this));
			
		}else{
			$('button#sign-in').trigger('click');
		}
		return false;
	});
	
	$('a#my-bmj').bind('click',function(){	
		if($.browser.version < 8 && $.browser.msie){
			initiatLoginPopUp($(this));
		}else{
			$('button#my-bmj').trigger('click');
		}
		return false;
	});
	$('a#my-account').bind('click',function(){	
		if($.browser.version < 8 && $.browser.msie){
			initiatLoginPopUp($(this));
		}else{
			$('button#my-account').trigger('click');
		}
		return false;
	});
	
}

function initiatLoginPopUp($this){
	
	$this.addClass('active');
    var popUpId = $this.attr('id') + "_popup";
    if($('div#'+popUpId).is(':visible')){
    	$('div#' + popUpId).hide();
    }else{
    	$('div.status-popup').hide();
    	positionLoginPopUp($this , popUpId);
    	
        $('div#' + popUpId).show();
    }
    return false;
}



function positionLoginPopUp($this , popId){   
    var offset = $($this).offset();    
    var setY = offset.top + $($this).outerHeight();
	var winWidth = $(window).width();
	var setX = winWidth - (offset.left + $($this).outerWidth());
	if( $('body').hasClass('module-flow-page') && $.browser.version < 8 && $.browser.msie){
		var setX = offset.left - $($this).outerWidth();
		$('div#' + popId).css({
			top:    setY,
			left:   setX
		});
		
	}else{
		$('div#' + popId).css({
			top:    setY,
			right:   setX
		});
	}
	
}



//////////////////////////////////////Tool Tip//////////////////////////////////
function enableToolTips(){
	var mouse_is_inside = false;
	
	$(".tool-tips").mouseover(function(){
		  var divId = $(this).attr('id') + '-dropdown';
	      positionToolTip($(this) , divId);
	      $('div#' + divId).show();
		 
	    }).mouseout(function(){
	    	 var divId = '#' + $(this).attr('id') + '-dropdown';			   
	    	 $('div#' + divId).hide();  
	    });

	 $('div.profession-dropdown').mouseover(function(){				  
		 $(this).show();
		    }).mouseout(function(){				    	
		    	 $(this).hide();
		    });
	   
	

}
function positionToolTip($this , popId){   
    var position = $($this).position();
    var setY = position.top ;
	var setX = position.left + $($this).outerWidth();
	if(popId.indexOf('profession')> -1){
		setX = position.left;
	}
	//archived
	
	if(popId.indexOf('archived') > -1){
		setY = position.top + $($this).height();
		setX = setX/1.5;
	}
	
	$('div#' + popId).css({
		top:    setY,
		left:   setX
	});
}
////////////////////////////////////Submit review
function submitReviw(){
	$("form#reviewForm").submit(function() {
	 
	      var action = pathname + 'rest/savereviews';
	      
	       if(jQuery.trim($('div#feedback-form  textarea#feedback').val())==""){
	    	  $("div.feedback-submitted h4").html('Thank you.');
	       }
	       $('div#loading-ajax').show();
	       $.post(action, $('#reviewForm').serialize(), function( data, status ) {				
				 success: $('div#feedback-form , div#loading-ajax').hide();
           					$('div#feedback-ajax , div.print-certificate, div#module-action-buttons-results-page').show();
           					window.scrollTo(0, 0); 				
			});	     
	      return false;
	    });
	}
//////////////////////////////////////////////Module buttons/
function retakeModule(){
	 $("button.retake-btn").click( function() {
		 var moduleId = $(this).attr('id').split('_')[1];
		 var retakeMSG = '<strong>Retaking a module will reset any previously completed score.</strong><br />If you are happy with this, click OK to proceed.';
		 if( $(this).attr('title') == 'ARCH'){
			 retakeMSG = '<strong>This module has been archived - it is no longer being updated. <br />You can review it, but if you do, you will reset any previously completed score,<br /> and you will not be able to print a certificate. </strong><br />If you are happy with this, click OK to proceed. ';
		 }
		 $.fn.bmjConfirm( retakeMSG, 'PLEASE NOTE', function(value) {
			   if(value){
				   parent.location= pathname + '/module-start.html?moduleId=' + moduleId; 
			   }
			  });
	 });
	 
}

function startModule()
{
	$("button.start-btn").click( function() 
	{
		var moduleId = $(this).attr('id').split('_')[1];
		
		if( $(this).attr('title') == 'ARCH')
			{
				var startMSG = '<strong>This module had been archived - it is no longer being updated.</strong><br /> You can take it if you wish, but you will not gain any CPD/CME points for the module,<br />  and you will not be able to print a certificate. <br />If you are happy with this, click OK to proceed.';
		 		$.fn.bmjConfirm( startMSG, 'PLEASE NOTE', function(value) 
		 		{
			   		if(value)
			   		{	
						   parent.location= pathname + '/module-start.html?moduleId=' + moduleId; 
			   		}
				});
		 	}
		 	else
		 	{
			 	parent.location= pathname + '/module-start.html?moduleId=' + moduleId;
		 	}
	 	});
	 
}



function saveModule(){
	$("button#save").click( function() {
		$(this).attr("disabled" , "disabled");
		$(this).addClass("disabled");
		return false;
	 });
	
}

function printCertificate()
{	
	$('#print-certificate').click(function(event){
		var ccIdNo = $('input#ccIdNo').val();
		var moduleId = $('input#moduleId').val();	
		var portfolioUrl = $('input#portfolioUrl').val();
		var completedModuleId = $('input#completedModuleId').val();		
		$('body').append('<div id="overlay"></div>');
		$('body').append('<div id="print-certificate" class="messagepop" style=""><h2>Certificate</h2><div class="close ui-popup-close" title="Close window"><span>Close</span></div></div>');
		var arrPageSizes = getPageSize();
		$('#overlay').css({
				height: arrPageSizes[1],
				opacity: '0.3'
				}).fadeIn();
		$('.messagepop').slideFadeToggle().center();
		$('.messagepop').append("<div id='loading-ajax' class='certificate-loading'>processing...</div>");
		$.ajax({
			type : "GET",
			url : pathname + "rest/accreditingOrgs/userdefault?callback=?",
			dataType: "jsonp",
			data:{'ccIdNo':ccIdNo, 'moduleId':moduleId, 'completedModuleId':completedModuleId},			
			success : function(data) {					
				$('div.certificate-loading').hide();				
				$('.messagepop').append("<div class='print-prefs'><fieldset><div class='settings'>" + data["userpreforghtml"] + data["certproviderhtml"] + "</div></fieldset></div>");	
				_closePopUp();				
			}
		}); // end of ajax
	});
}
//////////////////////////////////////////Pop up
function enablePopUps(){
	 $('.popup').live('click', function(){
			var target = "div#" + $(this).attr('id') + "_pop-up-plate";
			var title = $(this).attr('title'); 
			$('body').append('<div id="overlay"></div>');
			$('body').append('<div id="' + $(this).attr('id') + '" class="messagepop" style=""><h2>' + title + '</h2><div class="close ui-popup-close" title="Close window"><span>Close</span></div></div>');
			var arrPageSizes = getPageSize();
			$('#overlay').css({
					height: arrPageSizes[1],
					opacity: '0.3'
					}).fadeIn();
			$('.messagepop').slideFadeToggle().center();
			$(".messagepop").append( $(target).html());

			_closePopUp();
				
				return false;
			});
}

//////////////

//getPageSize() by quirksmode.com/
//@return Array Return an array with page width, height and window width, height/
function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};


$.fn.slideFadeToggle = function(easing, callback) {    
	return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

jQuery.fn.center = function () {
    this.css('position','absolute');
    this.css("top", "210px");
    this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
};

/*****Close pop up*****/
function _closePopUp(){
	$('.close').live('click',function(e){
		closePopup();	
	});
	
	$(document).keypress(function(e) { 
	    if (e.keyCode == 27) { 
	    	closePopup();
	    }  // esc   
	});
}
function closePopup(){
	//$('embed, object, select').css({ 'visibility' : 'visible' });
	$('.messagepop').slideFadeToggle().remove();
	$('#overlay').fadeOut().remove();
}

/**********start module alert*************/
function startModuleALert(){
	
	if($('div.add-to-portfolio-alert').length > 0){
		$('div.add-to-portfolio-alert').delay(2000).fadeIn(800);
		$('div.add-to-portfolio-alert').delay(8000).fadeOut(800);

	}
}






/******* ERROR *******/
////////////////////EXPAND
function enableErrorExpandables() {

    // Collapse the subsections
    jQuery(".expandable dd").hide();
    // Apply styles
    jQuery(".expandable dt").addClass("collapsed");
    jQuery(".expandable dt").each( function() {
    	setERRORExpandableStyleClass(this);
    });
    // Set the click event handler on subsections.
    jQuery(".expandable dt").click( function(e) {
			clickedThing(e, "dt").next("dd").toggle();    
			// e.target could be the dt or could be a sub-element:
			setERRORExpandableStyleClass(this);
        });
}

/* 
 * Checks the related dd of the 'expandableElement' node is hidden 
 * and sets it's style class accordingly. 
 */
function setERRORExpandableStyleClass(expandableElement) {

    var isHidden = jQuery(expandableElement).next("dd").is(":hidden");
    if (isHidden)      
    {
        jQuery(expandableElement).addClass("collapsed");
        jQuery(expandableElement).removeClass("expanded");
    } else {
        jQuery(expandableElement).addClass("expanded");
        jQuery(expandableElement).removeClass("collapsed");
    }
}

