/**
 * Connect - util.js
 * 
 * @author Manish Gupta <manishg@triconinfotech.com>
 * @copyright Copyright © 2009, McGraw-Hill Higher Education, All rights reserved.
 */

/**
 * @class Class containing all utility methods.
 * @static
 */
var Util = {
	/**
	 * @method
	 * Method for facebox based modal window 
	 */
	 modalWindow : function(){
		 
		jQuery('a[rel*=facebox]').facebox();	
		
	 },
	
	/**
	 * @method
	 * Method for opening the window popup in center
	 * 
	 * @param {String} pageToLoad - url string to be loaded
	 * @param {String} winName - name of the window
	 * @param {Integer} width - width of the window popup
	 * @param {Integer} height - height of the window popup
	 * @param {Boolean} center - if window is required at the center
	 */
	openAWindow : function ( pageToLoad, winName, width, height, center) {
    	xposition=0; yposition=0;
	
	    if ((parseInt(navigator.appVersion) >= 4 ) && (center)){
	        xposition = (screen.width - width) / 2;
	        yposition = (screen.height - height) / 2;			
			
	    }	   
		
		//0 => no
		//1 => yes
	    var args = "";
	    	args += "width=" + width + "," + "height=" + height + ","
			+ "location=0,"
			+ "menubar=0,"
			+ "resizable=0,"
			+ "scrollbars=0,"
			+ "statusbar=false,dependent,alwaysraised,"
			+ "status=false,"
			+ "titlebar=no,"
			+ "toolbar=0,"
			+ "hotkeys=0,"
			+ "screenx=" + xposition + ","  //NN Only
			+ "screeny=" + yposition + ","  //NN Only
			+ "left=" + xposition + ","     //IE Only
			+ "top=" + yposition;           //IE Only
			//fullscreen=yes, add for full screen
	    	var dmcaWin = window.open(pageToLoad,winName,args );
	    	dmcaWin.focus();
	    //window.showModalDialog(pageToLoad,"","dialogWidth:650px;dialogHeight:500px");
	},
	
		/**
	 * @method
	 * Utility method to set the domain
	 *
	 */
	fixDomain: function(){
		var dName = document.domain;
		if ((dName.indexOf(".com") > -1) && (dName.indexOf(".") > -1)) {
			var dNameArr = dName.split(".");
			if(dNameArr.length>1)
			dName = dNameArr[dNameArr.length-2]+"."+dNameArr[dNameArr.length-1];
			try {
				document.domain = dName;
			}
			catch(err) {
			}
		}
	},
	

	/**
	 * @method
	 * Method for display the tooltip
	 * 
	 * @param {String} linkref - element id which invokes the tooltip
	 * @param {String} bodyId - element id of tooltip template
	 * @param {String} contentId - element id of content of the tooltip
	 * @param {String} tooltipTxt - tooltip text
	 */
	displayToolTip : function(linkref,bodyId,contentId,tooltipTxt){	
		contenttooltip=$("#"+contentId).html();	
		$("#"+bodyId+" .headingtext").html(tooltipTxt);
		$("#"+bodyId+" .bodydiv").html(contenttooltip);
		$('#tooltip').html($("#"+bodyId));
	},
	/**
	 * @method
	 * Method to initialize the tooltip
	 * 
	 */
	initializeToolTip : function() {
		$('.tooltip').tooltip({
			top:-18,
			left:40,
			track: true,
			showURL: false,
			extraClass: "fancy"
		 });
	 },
	 /**
	 * @method
	 * Method to initialize the Growl message 
	 * 
	 */
	 growlMessage : function(message){
			$("#growlMessage").stop(true,true);
			/*$('#growlMain').corner({
				  tl: { radius: 20 },
				  tr: { radius: 20 },
				  bl: { radius: 20 },
				  br: { radius: 20 },			 
				  antiAlias: true,
				  autoPad: true,
				  validTags: ["div"] 
			});*/
			var winH = $(window).height();
			var winW = $(window).width(); 				
			$("#growlMessage").css("top", ((winH-100) - $("#growlMessage").height())/2 + $(window).scrollTop() + "px");
			$("#growlMessage").css("left",(winW - $("#growlMessage").width()) /2 + $(window).scrollLeft()+ "px");
			$("#growlMessage").show('fast');
			$("#growlcontent").html(message);
			var growlId = 1; 
			if($("#growlMessage").attr('growlId')){
				growlId = parseInt($("#growlMessage").attr('growlId'))+1;
				$("#growlMessage").attr('growlId',growlId);
			}
			else
				$("#growlMessage").attr('growlId',1);
			setTimeout(function(){
					$("#growlMessage[growlId="+growlId+"]").fadeOut('slow');
			},5000);
	 },
	/**
	 * @method
	 * Method to initialize the header curves
	 * 
	 */
	 initializeHeaderCurves: function() {
		//initialize curvy corners
		$('.nav_Selected').corner({
		  tl: { radius: 12 },
		  tr: { radius: 12 },
		  bl: false,
		  br: false,			 
		  antiAlias: true,
		  autoPad: true,
		  validTags: ["div"] 
		});
		$('.subNav_Selected').corner({
		  tl: { radius: 6 },
		  tr: { radius: 6 },
		  bl: false,
		  br: false,			 
		  antiAlias: true,
		  autoPad: true,
		  validTags: ["div"] 
		});
		
		$('.nav_unSelected').corner({
		  tl: { radius: 12 },
		  tr: { radius: 12 },
		  bl: false,
		  br: false,			 
		  antiAlias: true,
		  autoPad: true,
		  validTags: ["div"] 
		});
		$('.subNav_unSelected').corner({
		  tl: { radius: 6 },
		  tr: { radius: 6 },
		  bl: false,
		  br: false,			 
		  antiAlias: true,
		  autoPad: true,
		  validTags: ["div"] 
		});
	 	
	 },
	 /**
	 * @method
	 * Method for ie6 browser only, for curvey corner block
	 */
	iefixassignstudents : function() {
		$(window).resize(function(){
			  if($.browser.msie && $.browser.version < 7){  			  
				$('.curveGrey').css({'clear':'both','display':'none'});
				$('.curveGrey').css({'display':'block'});
		  		}
		});		
	},
	
	/**
	*
	* @method
	* Method to truncate the characters in the header 
	*/
	truncate : function(){
	$('.trunc28').truncate( {length: 28});
	},
	/**
	 * @method
	 * Method for display the tooltip
	 * 
	 * @param {String} linkref - element id which invokes the tooltip
	 * @param {String} bodyId - element id of tooltip template
	 * @param {String} contentId - element id of content of the tooltip
	 * @param {String} tooltipTxt - tooltip text
	 */
	displayToolTip : function(linkref,bodyId,contentId,tooltipTxt){	
		var reloadIEFlag = false;
		try{
			if(!$(linkref).hasClass('tooltipAdded')){
				reloadIEFlag = true;
				$(linkref).tooltip({
					top:-20,
					left:40,
					track: true,
					showBody: " - ",
					showURL: false,
					extraClass: "fancy",
					fixPNG: true
				 }).addClass('tooltipAdded');
			contenttooltip=$("#"+contentId).html();	
			$("#"+bodyId+" .headingtext").html(tooltipTxt);
			$("#"+bodyId+" .bodydiv").html(contenttooltip);
			$('#tooltip').html($("#"+bodyId));
			$(linkref).trigger('mouseover');
			}
			else{
				contenttooltip=$("#"+contentId).html();	
				$("#"+bodyId+" .headingtext").html(tooltipTxt);
				$("#"+bodyId+" .bodydiv").html(contenttooltip);
				$('#tooltip').html($("#"+bodyId));
			}
			if($.browser.msie && $.browser.version < 7){
				$('#tooltip').bgiframe();
			}
		}
		catch(e){
			if($.browser.msie && reloadIEFlag){
				reloadIEFlag = false;
				$(linkref).attr('title','');
				$(linkref).trigger('mouseover');
			}
		}
	},
	
	/**
	 * @method
	 * Method to periodically call touchSession jsp
	 * 
	 * @param {Integer} mins - time interval in minutes
	 */
	startAvoidTimer: function(mins){
		var avoidTimer, p_mins = 45*60000;
		if(mins!=null) p_mins = mins*60000;
		avoidTimer = setInterval(function(){
		$.get("/connect/jsp/touchSession.jsp");
		},p_mins);
	},
	
	/**
	 * @method
	 * Method to set session cookie
	 * 
	 * @param {String} cookieName - name of the cookie
	 * @param {String} cookieValue - value of the cookie
	 */
	setSessionCookie: function(cookieName, cookieValue) {
		document.cookie = cookieName + "=" + escape(cookieValue) + "; path=/; ";
	},
	
	/**
	 * @method
	 * Wrapper for jQuery ajax. Every ajax call in Connect should call this.
	 * 
	 * @param {Object} options - name of the cookie
	 */
	ajax: function(options) {
		var t = this;
		if(!options) return;
		try {
			jQuery.ajax({
				url: options.url,
				data: options.data ? options.data : "",
				dataType: options.dataType,
				async: options.async ? options.async : true,
				type: options.type ? options.type : "GET",
				cache: options.cache ? options.cache : false,
				contentType: options.contentType ? options.contentType : "application/x-www-form-urlencoded",
				success: function(message) {
					if(message && (!options.dataType || options.dataType=="html") && message.indexOf('redirectSessionTimeoutDiv') >= 0) {
						window.location.href = window.location.href;
					}
					options.success ? options.success(message) : "";
				},
				error: options.error ? options.error: function(XMLHttpRequest, textStatus, errorThrown){
					var errorMessage = "The information you requested is not available. Please try again after some time.";
					if(textStatus=='timeout') {
						errorMessage = "The request to server timed out. Please try again. If the problem continues to occur, contact Connect support."
					}

					$.facebox.close();
					$('.loading_image').removeClass('loading_image');
					t.growlMessage(errorMessage);
				}, 
				timeout: options.timeout ? options.timeout : 30000
			});
		} catch(e){
			t.growlMessage("Inside Util.ajax method. Following error occurred.<br/>" + e);
		}
	},

	/**
	 * @method
	 * 
	 * Method to set the footer at the bottom of the screen
	 * 
	 */
	setFooter: function() { 
        $('#mainContent').css('min-height',parseInt($('#mainContent').height())+(parseInt($(window).height())-parseInt($('#outer_container').height()))+'px');
        if($.browser.mozilla){ 
                //NEED TO CALL TWICE AS FF DOESN'T FIX IT FIRST TIME AROUND. THIS SHOULD NOT AFFECT PERFORMANCE
                $('#mainContent').css('min-height',parseInt($('#mainContent').height())+(parseInt($(window).height())-parseInt($('#outer_container').height()))+'px');
        } 
        $('#footer').css('visibility','visible');
	},
	
	/**
	 * @method
	 * Method for checking input text against allowed character set in the application.
	 * @param inputText - input text to be tested.
	 */
	checkAllowedCharacterSet: function(inputText) {
		var allowedCharacterSet = /^[A-Za-z0-9-._`!@#$%^&*()+={}\[\]\\/,|:;<>? ]*$/;
		if(allowedCharacterSet.test(inputText)) {
		    return true;
		} else {
		    return false;
		}
	},

	getContextualHelpPage:function(helpPageId) {
		var f = document.helpForm;
		var defaulthelpUrl = '/student_view0/';
		if($('#'+helpPageId).length != 0) {
			f.helpPageID.value = $('#'+helpPageId).val();
		} else {
			f.helpPageID.value = defaulthelpUrl;
		}
		if(f.helpPageID.value == "") {
			f.helpPageID.value = defaulthelpUrl;
		}
		var helpUrl = f.helpPageServerUrl.value + f.isbn.value + f.helpPageID.value;
		window.open(helpUrl,'helpWindow','');
	},
	
	/**
	 * @method
	 * Method for playing a video in modal window.
	 * @param videoPath - path of the video.
	 * @param headerText - text to be displayed in the modal header.
	 */
	openVideoModal: function(videoPath, headerText) {
		var thisObject = this;

		if($("#facebox #videoPlace #assignVideoPlayer").length != 0) {
			$("#facebox").show();
			if ($('#facebox_overlay').length == 0)
				$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
			$('#facebox_overlay').hide().addClass("facebox_overlayBG").css('opacity', $.facebox.settings.opacity).fadeIn(200);
			$("#assignVideoPlayer div.header").text(headerText);
			$("#assignVideoPlayer .mbody a").attr("href", videoPath);
			thisObject.flowPlayer();
			return false;
		} else {
			thisObject.ajax({
				url: "/classwareweb/html/videoPlaceHolder.html",
				cache: true,
				success: function(html){
					html = html.replace('$$VIDEOPATH$$', videoPath);
					html = html.replace('$$HEADERTEXT$$', headerText);

					$.facebox(function() {
						if($.browser.msie && $.browser.version < 7){
							$("#facebox_overlay").bgiframe();
						}
						$.facebox('<div id="videoPlace" style="width:750px;"></div>');
					});
					$("#facebox").focus();
					$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2));
					$("#videoPlace").html(html);

					//Calling an event on click of close button
					$('.closeIcon').click(function() {
						$(document).trigger('close.facebox');
					});
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("Error:"+ textStatus + ":" + errorThrown);
				}
			});
		}
	},
	
	/**
	 * @method
	 * Method for playing a video in modal window.
	 * @param videoId - id of the video.
	 * @param headerText - text to be displayed in the modal header.
	 */
	openViddlerVideoModal: function(videoId) {
		var thisObject = this;
		var videoPath = "";
		var headerText = "";

		switch(videoId) {
			case "access_code": videoPath = "http://www.viddler.com/simple/60beddce/";
								headerText = "how to register with an access code";
								break;
			case "buy_online": videoPath = "http://www.viddler.com/simple/6672ce55/";
								headerText = "how to buy access online";
								break;
		}

		thisObject.ajax({
			url: "/classwareweb/html/viddlerVideoPlaceHolder.html",
			cache: true,
			success: function(html){
				html = html.replace('$$VIDEOPATH$$', videoPath);
				html = html.replace('$$VIDEOPATH$$', videoPath);
				html = html.replace('$$HEADERTEXT$$', headerText);

				$.facebox(function() {
					if($.browser.msie && $.browser.version < 7){
						$("#facebox_overlay").bgiframe();
					}
					$.facebox('<div id="videoPlace" style="width:575px;"></div>');
				});
				$("#facebox").focus();
				$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2));
				$("#videoPlace").html(html);

				//Calling an event on click of close button
				$('.closeIcon').click(function() {
					$("#facebox #videoPlace").remove();
					$(document).trigger('close.facebox');
				});
			}
		});
	},
	
	/**
	 * @method
	 * Method for initializing the flow player.
	 */
	flowPlayer: function() {
		flowplayer("player", {src: "/classwareweb/player/flowplayer-3.1.0.swf", wmode: 'opaque'}, {
			play: {
			   opacity:0
			},
			clip: { 
		        autoPlay: false,
		        autoBuffering: false
		    },
			screen: {
			 	scaling: 'fit'
			},
			canvas: {
			 	backgroundColor: '#999999',
				background: 'url(/classwareweb/player/player.png) no-repeat 340 175'
			},
			plugins: {
				controls: {
					url:'/classwareweb/player/flowplayer.controls-skinless-3.1.0.swf',
					skin:'customskin',
					playlist: false,
					//now the custom options of the Flash object
					play:true,
					volume:false,
					mute:true,
					time:false,
					stop:false,
					playlist:false,
					height:16,
					fullscreen:false,
					backgroundColor: '#ffffff',
					backgroundGradient: 'none',
					//scrubber height
					scrubberHeightRatio: 0.8,
					sliderColor: '#cacaca',
					sliderGradient:'#cacaca',
					progressColor: '#cacaca',
					progressGradient:'#cacaca',
					bufferColor:'#cacaca',
					bufferGradient:'#cacaca',
					playHeightRatio:0.8,
					//time and the duration color
					timeColor:'#999999'
					},
			        customskin: {
						url: "/classwareweb/player/mycustomskin.swf",
						type: "classLibrary"
					}
		    	}
		});
	},

	/**
	 * @method
	 * Method to block entire application area with a transparent layer
	 * for a definite time or unless unblockConnect is called
	 * 
	 */
	blockConnect: function() {
		var t = this;
		if($('#connect_interstitial').length==0){
			$('body').append('<div id="connect_interstitial"><div class="loading"></div></div>');
			if ($.browser.msie && parseFloat($.browser.version) <= 6.0) {
				$('body').append('<div id="connect_interstitialBgiframe"></div>');
				$('#connect_interstitialBgiframe').bgiframe();
			}
		}
		var h = $('body').height()>$(document).height()?$('body').height():$(document).height();
		$("#connect_interstitial").css({width:'100%',height:h,top:0,left:0});
		if($('#facebox_overlay')){
			$('#facebox_overlay').hide();
		}
		$("#connect_interstitial").show();
		$("#connect_interstitial").css({cursor:'wait'});
		$('#connect_interstitial .loading').css({top:($(window).scrollTop()+parseInt($(window).height())/2)-(parseInt($('#connect_interstitial .loading').height())/2)+'px',left:(parseInt($(window).width())/2)-(parseInt($('#connect_interstitial .loading').width())/2)+'px',position:'absolute'});
		if ($.browser.msie && parseFloat($.browser.version) <= 6.0) {
			$('#connect_interstitialBgiframe').css({width:'100%',height:h,top:0,left:0}).show();
		}
		//call unblock after 10 seconds
		window.setTimeout(t.unblockConnect,10000);
	},
	
	/**
	 * @method
	 * Method to unblock entire application area 
	 * 
	 */
	unblockConnect: function(){
	   	$("#connect_interstitial").css({cursor:'default'});
	   	$("#connect_interstitial").hide();
		if($('#facebox_overlay')){
			$('#facebox_overlay').show();
		}
		if ($.browser.msie && parseFloat($.browser.version) <= 6.0) {
			$('#connect_interstitialBgiframe').hide();
		}
	}
	
};