﻿/* Browser sniffing */
/* Copyright (c) 2010 FoXSE Ltd */

var agt=navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();
var is_minor = parseFloat(appVer);
var is_major = parseInt(is_minor);
var iePos = appVer.indexOf('msie');
if (iePos !=-1) {
is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
is_major = parseInt(is_minor);
}
var is_getElementById = (document.getElementById) ? "true" : "false";
var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false";
var is_documentElement = (document.documentElement) ? "true" : "false";
var is_ie = ((iePos!=-1));
var is_ie3 = (is_ie && (is_major < 4));
var is_ie4 = (is_ie && is_major == 4);
var is_ie4up = (is_ie && is_minor >= 4);
var is_ie5 = (is_ie && is_major == 5);
var is_ie5up = (is_ie && is_minor >= 5);
var is_ie5_5 = (is_ie && (agt.indexOf("msie 5.5") !=-1));
var is_ie5_5up =(is_ie && is_minor >= 5.5);
var is_ie6 = (is_ie && is_major == 6);
var is_ie6up = (is_ie && is_minor >= 6);

/* Tool buttons */

function showCalc() {
    window.open(path_to_root + 'tools/calculator.aspx','Calculator','width=195,height=210,');
}

function showScratchPad() {
    window.open(path_to_root + 'tools/scratchpad.aspx', 'ScratchPad', 'width=300,height=250,');
}

function showChat() {
    window.open(path_to_root + 'social/im_conv.aspx', 'Chat', 'width=550,height=350,');
    try {
        im_button_clicked = true;
    } catch (ex) {
        //sink exception
    }
}

/* 
 * Asynchronous Image Loading.
 *
 * Display an image in the subsection of the side panel,
 * or within a DOM element, such as a DIV, when loaded
 * inline within a page.
 *
 * Show a loading placeholder whilst the image loads.
 */
 
function showImageLoadingSS(img_src, height) {
    showImageLoading(img_src, null, height, null);
}

/* Load images with placeholder text and auto-retry */

var IMAGE_LOAD_TIMEOUT = 5000;
var IMAGE_LOAD_TIMEOUT_BACKOFF_MULTIPLE = 1.5;
var MAX_IMAGE_LOAD_ATTEMPTS = 5;

/* Asynchronous image loading class */
function clsAsyncImage() {
    this.timer_id = null;
    this.img_url = null;
    this.img_object = null;
    this.load_attempts = 0;
    this.id = generateGuid();
    this.div_object = null;
    this.success = false;
    this.timeoutInterval = null;
}

var imgs_loading = new Array();

function showImageLoading(img_src, width, height, div_id) {
    
    var is_div = (div_id != null);
    var div_object = null;
    
    var should_cont = false;
    
    //get div
    if (is_div) {
        div_object = document.getElementById(div_id);
        
        if (div_object) {
            div_object.innerHTML = "<div style='position: relative; top: 0px; left: 0px; width: " + width + "px; height: " + height + "px;'><div style='position: absolute; top: 0px; left: 0px; text-align: center; width: 100%; padding-top: " + ((height / 2) - 10) + "px;'>Loading...</div></div>";
            should_cont = true;
        }
    } else {
        //sub-section of side panel
        setSubSection("<div style='position: relative; top: 0px; left: 0px; height: " + height + "px;'><div style='position: absolute; top: 0px; left: 0px; text-align: center; width: 100%; padding-top: " + ((height / 2) - 10) + "px; color: #FFFFFF;'>Loading...</div></div>");
        should_cont = true;
    }
    
    if (should_cont) {
        
        /* unique id for async image */
        var async_img_id = generateGuid();
        
        /* create new async image object */
        var async_image = new clsAsyncImage();
        async_image.id = async_img_id;
        async_image.img_url = img_src;
        async_image.div_object = div_object;
        async_image.load_attempts = 1;
        async_image.timeoutInterval = IMAGE_LOAD_TIMEOUT;
    
        /* load timeout checker */
        async_image.timer_id = setTimeout("attemptReloadImage('" + async_image.id + "')", async_image.timeoutInterval);
        
        /* DOM image */
        async_image.img_object = new Image;
        
        async_image.img_object.src = img_src;
        async_image.img_object.onload = function() {
            completeLoadAsyncImage(async_img_id);
        };
        
        imgs_loading.push(async_image);
    }
}

/*attempts to reload image up to a limit*/
function attemptReloadImage(async_img_id) {
    
    var async_image = getImageById(async_img_id);
    if (async_image) {
        async_image.timer_id = null;
        
        var should_clear_down = false;
        
        if (!async_image.success) {
        
            /* attempt reload if less than max */
            if (async_image.load_attempts < MAX_IMAGE_LOAD_ATTEMPTS) {
            
                async_image.load_attempts++;
            
                var img_loading = async_image.img_object;
                if (img_loading) {    
                    var img_src = img_loading.src;
                    
                    img_loading.src = "";
                    img_loading.src = img_src;
                }
                
                /* increase timeout */
                async_image.timeoutInterval = (async_image.timeoutInterval * IMAGE_LOAD_TIMEOUT_BACKOFF_MULTIPLE);
                
                /* set timeout checker with new interval */
                async_image.timer_id = setTimeout("attemptReloadImage('" + async_image.id + "')", async_image.timeoutInterval);
                
            } else {
                /*failed to load*/
                should_clear_down = true;
            }
        
        } else {
            /*already succeeded*/
            should_clear_down = true;
        }
        
        /*failed to load or already loaded*/
        if (should_clear_down) {
            clearDownAsyncImage(async_img_id);
        }
        
    } else {
        throw ("could not find async image with id: " + async_img_id);
    }
}

/* complete loading the image */
function completeLoadAsyncImage(async_img_id) {
    
    var async_image = getImageById(async_img_id);
    if (async_image) {
    
        if (async_image.div_object) {
            async_image.div_object.innerHTML = "<img src='" + async_image.img_url + "'>";
        } else {
            setSubSection("<img src='" + async_image.img_url + "'>");
        }
        
        async_image.success = true;
        clearDownAsyncImage(async_img_id);
        
    } else {
        throw ("could not find async image with id: " + async_img_id);
    }
}

/* stop attempting to load the image */
function clearDownAsyncImage(async_img_id) {
    
    var async_image = getImageById(async_img_id);
    if (async_image) {
    
        try {
            if (async_image.timer_id) {
                clearTimeout(async_image.timer_id);
            }
        } catch (timerEx) {
            //sink timer ex
        }
        
        if (!async_image.success) {
            /* show load failure message */
            var failed_load_html = "<div style='color: Red;'>Failed to load image.</div>";
            
            if (async_image.div_object) {
                async_image.div_object.innerHTML = failed_load_html;
            } else {
                setSubSection(failed_load_html);
            }
        }
        
        /*remove async_image*/
        async_img_index = getImageIndexById(async_img_id);
        imgs_loading.splice(async_img_index, 1);
        
    } else {
        throw ("could not find async image with id: " + async_img_id);
    }
}

function getImageById(async_img_id) {
    var async_img_index = getImageIndexById(async_img_id);
    
    if (async_img_index != -1) {
        return imgs_loading[async_img_index];
    } else {
        throw "getImageIndexById('" + async_img_id + "') returned -1";
    }
    
    /*otherwise, null*/
    return null;
}

function getImageIndexById(async_img_id) {
    
    for (i = 0; i < imgs_loading.length; i++) {
        var async_image = imgs_loading[i];
        if (async_image.id == async_img_id) {
            return i;
        }
    }
    /*otherwise, -1*/
    return -1;
}


function generateGuid() {
    var result, i, j;
    result = '';
    
    for(j=0; j<32; j++) {
        if( j == 8 || j == 12|| j == 16|| j == 20) {
            result = result + '-';
        }
        
        i = Math.floor(Math.random()*16).toString(16).toUpperCase();
        result = result + i;
    }
    
    return result
}

/* Clock */

var dayarray = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
var montharray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

/* Get current formatted date */
function getCurrentFormattedDate(monthAndYearOnly) {
	var mydate = new Date();
	
	// Date
	var year = mydate.getYear();
	if (year < 1000) year += 1900;
	var day = mydate.getDay();
	var month = mydate.getMonth();
	var daym = mydate.getDate().toString(); // Get day number as string
	
	// Add -st,-nd,-rd,-th to day number		
	if (daym == "11" || daym == "12" || daym == "13") {
		daym = daym + "th";
	} else {
		if (daym.length == 1)
			var lastNum = daym.charAt(0);
		else
			var lastNum = daym.charAt(1);
		
		// Add suffix based on last number
		switch (lastNum) {
			case "1": daym = daym + "st"; break;
			case "2": daym = daym + "nd"; break;				
			case "3": daym = daym + "rd"; break;
			default: daym = daym + "th"; break;
		}
	}
	
	// Time
	var hours = mydate.getHours();
	var minutes = mydate.getMinutes();
	
	// Add zero before single digits
	if (hours <= 9) hours = "0" + hours;
	if (minutes <= 9) minutes = "0" + minutes;
		
	// Create final string
	var cdate;
	
	if (monthAndYearOnly) {
	    cdate = montharray[month] + " " + daym + " " + mydate.getFullYear();
	} else {
	    cdate = dayarray[day] + ", " + montharray[month] + " " + daym + " " + mydate.getFullYear();
	}
	
	return cdate;
}

/* Print current formatted date */
function printDate(elementIdForDisplay, monthAndYearOnly) {
    
    var calculatedDate = getCurrentFormattedDate(monthAndYearOnly);
    
    if (null != elementIdForDisplay) {
        document.getElementById(elementIdForDisplay).innerHTML = calculatedDate;
    
    } else {
        if (document.all) {
		    document.all.timeDate.innerHTML = calculatedDate;
        } else if (document.getElementById) {
		    document.getElementById("timeDate").innerHTML = calculatedDate;
	    }
	}
}

/* Cross-platform get height */
function getWindowHeight() {
    var myHeight = 0;
    
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myHeight = window.innerHeight;
        
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
        
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
  }
  
  return myHeight;
}

/* get ping-back URL for current page */
function getPingBackUrl() {
    var ping_back_url = path_to_root + "ping_back.aspx?url=";
    return ping_back_url + document.location.href;
}

/* 
 * Get the current scroll Y position
 * of the browser window.
 */
function getScrollY() {
    var scrOfY = 0;
    
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
    }
    else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    }
    else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
    }
    
    return scrOfY;
}

/* wrap the specified exception with the message and throw */
function wrapEx(exMessage, exException) {
    throw new Error(exMessage 
        + " \nMessage:" + exException.message 
        + (exException.description ? " \nDescription:" + exException.description : "")
        + (exException.name ? " \nName:" + exException.name : "")
        + (exException.stack ? " \nStack:" + exException.stack : ""));
}

/* throw a new exception with the specified message */
function throwEx(exToThrowMessage) {
    throw new Error(exToThrowMessage);
}

/* determine if the current browser is Internet Explorer */
function browserIsIE() {
    return (navigator && navigator.appName == "Microsoft Internet Explorer");
}
