var browserName=navigator.appName;
if (browserName=="Netscape"){
    var browser = 'netscape';
}else {
    if(browserName=="Microsoft Internet Explorer"){
        var browser = 'ie'
    }else{
        var browser = 'unknown';
        alert(browserName);
    }
}


/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


function showModal(myID, myTitle, myURL, myWidth, myHeight, resizeable){
    MochaUI.typeWindow = function(myID, myTitle, myURL, myWidth, myHeight){
        new MochaUI.Window({
            id: myID,
            title: myTitle,
            loadMethod: 'iframe',
            contentURL: myURL,
            collapsible: false,
            minimizable: false,
            maximizable: false,
            type: 'modal',
            footerHeight: 20,
            cornerRadius: 10,
            shadowBlur: 10,
            resizable: resizeable,
            width: myWidth,
            height: myHeight,
            draggable: true,
            headerStartColor: [255,0,0],
            headerStopColor: [0,0,0]
        });
    }

    MochaUI.typeWindow(myID, myTitle, myURL, myWidth, myHeight);
}


function setCookie( name, value, expires, path, domain, secure ){
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires ){
        expires = expires * 1000 * 60 * 60 * 24;
    }

    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ){
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ){
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ){
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}

	if ( !b_cookie_found ){
		return null;
	}
}

function deleteCookie( name, path, domain ){
    if ( getCookie( name ) )
        document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function _fillInMenu(menu_id, values, selected){
    var menu = document.getElementById(menu_id);
    if(typeof menu  == "object"){
        _emptyMenuItems(menu);
        _setMenuItems(menu, values, selected);
    }
}

function _emptyMenuItems(menu){
    if(typeof(menu) != "object"){ menu = document.getElementById(menu); }
    if(typeof(menu) == "object"){ menu.options.length = 0; }
}

function _setMenuItems(menu, items, selected){
    var opt;
    var f = 0;
    if(typeof(menu) != "object"){ menu = document.getElementById(menu); }
    if(typeof(menu) == "object"){
        var i = 0;
        for(var key in items){
            opt = new Option(items[key], key);
            menu.options[i++] = opt;
            if(selected == key){ f = (i - 1); }
        }
    }

    menu.selectedIndex = f;
}

function showMenu(id){
    document.getElementById(id).style.display='block';
}

function hideMenu(id){
    document.getElementById(id).style.display='none';
}

function selectAll(id){
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

function grey(){
    var loading = document.getElementById('HTML_AJAX_LOADING');
    var g = document.getElementById('gc-overlay');
    if(g.style.display == 'block'){
        g.style.display = 'none';
        loading.style.display = 'none';
    }else{
        g.style.display = 'block';
        loading.style.display = 'block';
    }
}


function checkMessages(){
    var msg = document.getElementById('message');
    if(msg.innerHTML != ''){
        grey();
        alert(msg.innerHTML);
        grey();
    }
}

var aremote = new auth();


function idle(){
    var left = aremote.checkIdle();

    if(left == false){
        grey();
        if(!confirm('You have been idle too long. Would you like to stay logged in?')){
            aremote.logout();
            grey();
            window.location.href='/';
        }else{
            aremote.updateIdle();
            idle();
            grey();
            return true;
        }
    }

    document.getElementById('timer').innerHTML = left;
    setTimeout("idle()",5000);
}


function checkObject(obj){
    var f = false;
    for(var i in obj){
        if(obj[i] != ''){
            f = true;
            return f;
        }
    }
}

function setTableSize(){
    var h = window.innerHeight;

    var ci = document.getElementById('cimage');

    if(typeof h == 'undefined'){
        var h = document.body.clientHeight;
        var newSize = (h - 73) + 'px';
    }else{
        var newSize = (h - 125) + 'px';
    }

    if(checkObject(ci) == true){
        ci.style.height = newSize;
    }
}

function validateZipcode(s){
    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);

    if (!reZip.test(s)){ return false; }
    return true;
}

function validateEmail(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   //alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   //alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    //alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

 		 return true
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}
