// Unicorn Custom JQuery Functions
var minWidth = 990;
var minHeight = 220;
var staticTotal = 0;

function resizeTabs() {

  // var height = $(window).height() - $("#calcHeightMainContentContainer").offset().top - ($("#calcHeightFooterContainer").height() + $("#calcHeightFooterImages").height() + 5);
  //   var height = $(window).height() - $("#calcHeightMainContentContainer").offset().top - ($("#EndNavContent").offset().top - $("#calcHeightFooterContainer").offset().top);
  //	var height = $(window).height() - $("#tabMainContentContainer").offset().top-10;
	var height = 0;
    if (height < minHeight)
       height = minHeight;

   // $("#tabMainContentContainer").height(height);		
    
   var intBottomOfPageHeight = $('#displayFooterContainer').height() + $('#calcHeightFooterImages').height() + $('#calcBottomMainContentContainer').height();
   if ($('#Display').length > 0) {
		// Most IFRAME windows
		var fraHeight = ($(window).height() - $('#Display').offset().top)   -   ($(window).height() - $('#calcHeightFooterContainer').offset().top) - intBottomOfPageHeight;
   } else {
		// Pages like assessment
		var fraHeight = ($(window).height() - $('#tabMainContentContainer').offset().top)   -   ($(window).height() - $('#calcHeightFooterContainer').offset().top) - intBottomOfPageHeight;
   }
   
   
   //var tmp = '';
   //tmp += 'Window Height: ' + $(window).height() + '\n';
   //tmp += 'Display Offset: ' + $("#Display").offset().top + '\n';
   //tmp += 'Footer Container Offset: ' + $("#calcHeightFooterContainer").offset().top + '\n';
   //$("#calcHeightFooterContainer").css("display","inline");
   //alert($("#calcHeightFooterContainer").offset().top);
   
   
   // alert(($(window).height() - $("#Display").offset().top) - ($(window).height() - $("#mainContainerContentBottom").offset().top));
   // var fraHeight = height - $("#Display").offset().top-135;
    // var fraHeight = $(window).height() - $("#Display").offset().top-35;
    
  if (fraHeight < minHeight-50)
        fraHeight = minHeight-50;            

	if ($('#Display').length > 0) {
	   $('#Display iframe').height(fraHeight);

		if($('#showPunchthrough').length > 0) {
			$('#Display iframe').width('100%');                
		} else {		    
			$('#Display iframe').width('98%');
		}
	} else {
		 $('#tabMainContentContainer').height(fraHeight);
	}
}

function resize(e) {
    //alert(e);
    $('#dynamic').height(($(window).height() > minHeight ? $(window).height() - staticTotal : minHeight - staticTotal));
}

    
//Global Document Ready for resizing
$(document).ready(function() {
    
    if ($('#holdingTable').width() < minWidth)
        $('#holdingTable').width(minWidth);

    if ($('#dynamic').length > 0)
    {
        var dynamicTop = $('#dynamic').offset().top;
        var dynamicEndTop = $('#dynamicEnd').offset().top;
        var pageEndTop = $('#pageEnd').offset().top;           
     
		// alert("Top: " + dynamicTop + " - End: " + dynamicEndTop + " - Page End: " + pageEndTop + " - Footer: " + $('tr #calcBottomMainContentContainer').offset().top  );   
        //Note: This only applies to full screen
        if ($('#calcHeightNavigationContainer').length == 1)
            minHeight = $('#calcHeightNavigationContainer').height();
       
        //only calculate static total once     
        staticTotal = (dynamicTop + (pageEndTop - dynamicEndTop)) + 10;
        if (minHeight - staticTotal < 0)       
            staticTotal = minHeight;
        
        resize();
        $(window).resize(function() {
            resize();
        });        
    }
        
    if ($('.studyserve-table thead').length != 0)
    {
		$('.studyserve-table:not([nosort=true]) thead th:has(input[type=checkbox])').addClass('{sorter: false}');
		$('.studyserve-table:not([nosort=true])').tablesorter({
			widgets: ['zebra'],
			dateFormat: 'uk'
		}); 
    };
    
 
    
}); 
 
function tableSort(id)
{   
    if ($('#' + id + ' thead').length != 0)
    {
        $('#' + id + ' td.table-row').removeClass('table-row');
        $('#' + id + ' td.table-row-alt').removeClass('table-row-alt');
        $('#' + id).tablesorter({widgets: ['zebra'],dateFormat: 'uk'});
        // uk = dd/mm/yyyy OR you can specify dateFormat: dd/mm/yy
    }
}

var tablesorterShowIcons = function() {
    $('.tablesorterSortImage').remove();

    // {sorter: false} and headerSortNone are BOTH required to disable sorter properly
    $('.headerSortNone').each(function(){
        var innerHTMLContent = $(this).html();
        $(this).html('<div>' + innerHTMLContent.toString() + '</div>' + '<div class="tablesorterSortImage" valign="bottom" style="vertical-align:bottom" ><img src="/images/tablesorter/none.gif" alt="" /></div>');
    });
                
    $('.header').each(function(){
        var innerHTMLContent = $(this).html();
        $(this).html('<div>' + innerHTMLContent.toString() + '</div>' + '<div class="tablesorterSortImage" valign="bottom" align="right" style="vertical-align:bottom;text-align:right;"><img src="/images/tablesorter/bg.gif" alt="" /></div>');
    });

    $('.headerSortUp div.tablesorterSortImage img').attr('src','/images/tablesorter/asc.gif');
    $('.headerSortDown div.tablesorterSortImage img').attr('src','/images/tablesorter/desc.gif');
};
    
function resizeTable(id,size)
{
    //Note: Minimum height of table is 200px
    var _nosort;
    if (arguments.length >= 3)
    {
        _nosort = nosort;
    }
    
    $(document).ready(function() {
        
        var dynHeight = ($('#dynamic').height() > 200 ? $('#dynamic').height() : 250); 
        
        $('#' + id).wrap('<div id="' + id + 'tableDiv" class="tableContainer"></div>');
        
        //Initial Resize
        $('#' + id + 'tableDiv').height(dynHeight-size);
        $('#' + id + 'tableDiv' + ' tbody').height(dynHeight-(size + 25));
        
        //Window Resize, resize
        $(window).resize(function(){                    
            var dynHeight = ($('#dynamic').height() > 200 ? $('#dynamic').height() : 250); 
            $('#' + id+ 'tableDiv').height(dynHeight-size);
            $('#' + id+ 'tableDiv' + ' tbody').height(dynHeight-(size + 25));
        });        
        
    });
}

function resizeTableFixed(id,size)
{
    var _nosort;
    if (arguments.length >= 3)
    {
        _nosort = nosort;
    }
    
    //Note: Minimum height of table is 200px    
    $(document).ready(function() {   
    
        if ($('#' + id).height() > size)
        {
            $('#' + id).wrap('<div id="' + id + 'tableDiv" class="tableContainer"></div>');
            
            //Initial Resize
            $('#' + id + 'tableDiv').height(size);
            $('#' + id+ 'tableDiv' + ' tbody').height(size-25);
            
            //Make smaller to allow room for scrollbar
            $('#' + id + 'tableDiv').width($('#' + id).width()-5);
            
        }
    });
}


//This JavaScript Object handles the tabs
function showKeyline(elementContainingKeyline, tabID) {
	// Clear the keyLine
	    $('keyLine').html('');
		if((elementContainingKeyline != null) && (elementContainingKeyline != 'undefined') && (elementContainingKeyline.toString() != '')) {		 
			if($('#' + elementContainingKeyline).length > 0) {
				// Populate with the selected tab if there is one
				$('#keyLine').html($('#' + elementContainingKeyline).html());
				//Get a handle on those left and right tab "extra" bits and assign them a calculated class
				$('#tabKeylineContentLeft').attr('class', tabID + '_left');
				$('#tabKeylineContentRight').attr('class', tabID + '_right');
				// Show the keyLine
				$('#tabMainContainerKeyline').show();
			} else {
				// We can't get data for the keyline so hide the whole Keyline table row
				$('#tabMainContainerKeyline').hide();
			}
		} else {
			$('#tabMainContainerKeyline').hide();
		}  
	    //Reinitialise Tabs
	    if($('#childbody').count > 0) {
			tabs();
		}
}

function tabs() {
    var $tabs = null;
    var unselectedTab;
    
    $(document).ready(function() {
	
        $tabs = $('#tabMain > ul').tabs({
			selected:null,
	        select: function(ui) {
	            try {     
    			    if($('#punchthrough', parent.document).length > 0) {
					    $('#punchthrough', parent.document).remove();
				    }
				}
				catch (e)
				{
				
				}

	        },
	        show: function(ui) {
                
                try {  
                
    			    if($('#punchthrough', parent.document).length > 0) {
					    $('#punchthrough', parent.document).remove();
				    }
				    
				    //resize tabs
				    resizeTabs();
				    
				    if($('#showPunchthrough').length > 0) {
    				    var intWidth = $('#divTabMainContent').width();
					    var strHTML = '';
					    strHTML += "<div id='punchthrough' class='";
					    strHTML += $(".ui-tabs-selected a", parent.document).attr("id");
					    strHTML += "' style='position:absolute;width:";
					    strHTML += $(".ui-tabs-selected", parent.document).width();
					    strHTML += "px;'></div>";
    					
					    if($('.ui-tabs-selected a', parent.document).length > 0) {
						    $('.ui-tabs-selected a', parent.document).after(strHTML);
					    }
				    }
				    $('.highlighttabimage', parent.document).hide();
				    $('.disabledtabimage', parent.document).show();
				    $('.ui-tabs-selected .highlighttabimage', parent.document).show();
    				    				
		           try { 
		            if (!(isNull(ui.tab))) {
				        var jqTabA = $('a[id=' + ui.tab.id + '],postredirect');
				        if (jqTabA.length > 0) {
					        $tabs.tabs('url', getTabIndex(ui.tab.id), jqTabA.attr('postredirect'));
					        jqTabA.removeAttr('postredirect');
				        }
				    }
			       } catch(e) { // do nothing
			       }
			   
                }
				catch (e)
				{
				
				}
								
	        }
        });
		
		$('#tabMain > ul > li').hover(function() {
			if($(this).attr('class') == 'ui-tabs-selected') {
			} else {
				$('.highlighttabimage', this).show();
			}
		}, function() {
			if($(this).attr('class') == 'ui-tabs-selected') {
			} else {
				$('.highlighttabimage', this).hide();
			}
		}); 
		

        $('#tabMain').show();
        resizeTabs();
        
        $(window).resize(function() {
		    resizeTabs();
        });        
       
    });
	
    function getTabIndex(id)
    {
        //method to resolve index by tab id key
        var tabCount = $('#tabMain ul li > a').length;
        for (var i = 0;i<tabCount;i++)
        {
            if ($($('#tabMain ul li > a')[i]).attr('id') == id)
            {
                return i;
                break;
            };
        }
	    
        //if not found try id as index
        if (parseInt(id)<tabCount)
            return parseInt(id)
        else
            return 0;	   
    }
	
    function setTab(id,redirect)
    {
        $(document).ready(function() { 
           $tabs.tabs('select',getTabIndex(id));
        });
    }
   
	this.setTab = setTab;
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};